blob: f6f8405b0e01d7b85f8c0c946c122bc74c5f0703 [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"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000040 llvm::Value *Cell =
41 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000042 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000043 }
44}
45
John McCalla1dee5302010-08-22 10:59:02 +000046static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000047 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000048 T->isMemberFunctionPointerType();
49}
50
John McCall7f416cc2015-09-08 08:05:57 +000051ABIArgInfo
52ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
53 llvm::Type *Padding) const {
54 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
55 ByRef, Realign, Padding);
56}
57
58ABIArgInfo
59ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
60 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
61 /*ByRef*/ false, Realign);
62}
63
Charles Davisc7d5c942015-09-17 20:55:33 +000064Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
65 QualType Ty) const {
66 return Address::invalid();
67}
68
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000069ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000070
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000071static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000072 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000073 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
74 if (!RD)
75 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000076 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000077}
78
79static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000080 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000081 const RecordType *RT = T->getAs<RecordType>();
82 if (!RT)
83 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000084 return getRecordArgABI(RT, CXXABI);
85}
86
Reid Klecknerb1be6832014-11-15 01:41:41 +000087/// Pass transparent unions as if they were the type of the first element. Sema
88/// should ensure that all elements of the union have the same "machine type".
89static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
90 if (const RecordType *UT = Ty->getAsUnionType()) {
91 const RecordDecl *UD = UT->getDecl();
92 if (UD->hasAttr<TransparentUnionAttr>()) {
93 assert(!UD->field_empty() && "sema created an empty transparent union");
94 return UD->field_begin()->getType();
95 }
96 }
97 return Ty;
98}
99
Mark Lacey3825e832013-10-06 01:33:34 +0000100CGCXXABI &ABIInfo::getCXXABI() const {
101 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000102}
103
Chris Lattner2b037972010-07-29 02:01:43 +0000104ASTContext &ABIInfo::getContext() const {
105 return CGT.getContext();
106}
107
108llvm::LLVMContext &ABIInfo::getVMContext() const {
109 return CGT.getLLVMContext();
110}
111
Micah Villmowdd31ca12012-10-08 16:25:52 +0000112const llvm::DataLayout &ABIInfo::getDataLayout() const {
113 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000114}
115
John McCallc8e01702013-04-16 22:48:15 +0000116const TargetInfo &ABIInfo::getTarget() const {
117 return CGT.getTarget();
118}
Chris Lattner2b037972010-07-29 02:01:43 +0000119
Reid Klecknere9f6a712014-10-31 17:10:41 +0000120bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
121 return false;
122}
123
124bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
125 uint64_t Members) const {
126 return false;
127}
128
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000129bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
130 return false;
131}
132
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000133void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000134 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000135 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000136 switch (TheKind) {
137 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000138 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000139 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000140 Ty->print(OS);
141 else
142 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000143 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000144 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000145 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000146 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000147 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000148 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000149 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000150 case InAlloca:
151 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
152 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000153 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000154 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000155 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000156 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000157 break;
158 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000159 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000160 break;
161 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000162 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163}
164
Petar Jovanovic402257b2015-12-04 00:26:47 +0000165// Dynamically round a pointer up to a multiple of the given alignment.
166static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
167 llvm::Value *Ptr,
168 CharUnits Align) {
169 llvm::Value *PtrAsInt = Ptr;
170 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
171 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
172 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
173 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
174 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
175 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
176 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
177 Ptr->getType(),
178 Ptr->getName() + ".aligned");
179 return PtrAsInt;
180}
181
John McCall7f416cc2015-09-08 08:05:57 +0000182/// Emit va_arg for a platform using the common void* representation,
183/// where arguments are simply emitted in an array of slots on the stack.
184///
185/// This version implements the core direct-value passing rules.
186///
187/// \param SlotSize - The size and alignment of a stack slot.
188/// Each argument will be allocated to a multiple of this number of
189/// slots, and all the slots will be aligned to this value.
190/// \param AllowHigherAlign - The slot alignment is not a cap;
191/// an argument type with an alignment greater than the slot size
192/// will be emitted on a higher-alignment address, potentially
193/// leaving one or more empty slots behind as padding. If this
194/// is false, the returned address might be less-aligned than
195/// DirectAlign.
196static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
197 Address VAListAddr,
198 llvm::Type *DirectTy,
199 CharUnits DirectSize,
200 CharUnits DirectAlign,
201 CharUnits SlotSize,
202 bool AllowHigherAlign) {
203 // Cast the element type to i8* if necessary. Some platforms define
204 // va_list as a struct containing an i8* instead of just an i8*.
205 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
206 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
207
208 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
209
210 // If the CC aligns values higher than the slot size, do so if needed.
211 Address Addr = Address::invalid();
212 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000213 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
214 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000215 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000216 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000217 }
218
219 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000220 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000221 llvm::Value *NextPtr =
222 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
223 "argp.next");
224 CGF.Builder.CreateStore(NextPtr, VAListAddr);
225
226 // If the argument is smaller than a slot, and this is a big-endian
227 // target, the argument will be right-adjusted in its slot.
228 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
229 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
230 }
231
232 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
233 return Addr;
234}
235
236/// Emit va_arg for a platform using the common void* representation,
237/// where arguments are simply emitted in an array of slots on the stack.
238///
239/// \param IsIndirect - Values of this type are passed indirectly.
240/// \param ValueInfo - The size and alignment of this type, generally
241/// computed with getContext().getTypeInfoInChars(ValueTy).
242/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
243/// Each argument will be allocated to a multiple of this number of
244/// slots, and all the slots will be aligned to this value.
245/// \param AllowHigherAlign - The slot alignment is not a cap;
246/// an argument type with an alignment greater than the slot size
247/// will be emitted on a higher-alignment address, potentially
248/// leaving one or more empty slots behind as padding.
249static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
250 QualType ValueTy, bool IsIndirect,
251 std::pair<CharUnits, CharUnits> ValueInfo,
252 CharUnits SlotSizeAndAlign,
253 bool AllowHigherAlign) {
254 // The size and alignment of the value that was passed directly.
255 CharUnits DirectSize, DirectAlign;
256 if (IsIndirect) {
257 DirectSize = CGF.getPointerSize();
258 DirectAlign = CGF.getPointerAlign();
259 } else {
260 DirectSize = ValueInfo.first;
261 DirectAlign = ValueInfo.second;
262 }
263
264 // Cast the address we've calculated to the right type.
265 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
266 if (IsIndirect)
267 DirectTy = DirectTy->getPointerTo(0);
268
269 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
270 DirectSize, DirectAlign,
271 SlotSizeAndAlign,
272 AllowHigherAlign);
273
274 if (IsIndirect) {
275 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
276 }
277
278 return Addr;
279
280}
281
282static Address emitMergePHI(CodeGenFunction &CGF,
283 Address Addr1, llvm::BasicBlock *Block1,
284 Address Addr2, llvm::BasicBlock *Block2,
285 const llvm::Twine &Name = "") {
286 assert(Addr1.getType() == Addr2.getType());
287 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
288 PHI->addIncoming(Addr1.getPointer(), Block1);
289 PHI->addIncoming(Addr2.getPointer(), Block2);
290 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
291 return Address(PHI, Align);
292}
293
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000294TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
295
John McCall3480ef22011-08-30 01:42:09 +0000296// If someone can figure out a general rule for this, that would be great.
297// It's probably just doomed to be platform-dependent, though.
298unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
299 // Verified for:
300 // x86-64 FreeBSD, Linux, Darwin
301 // x86-32 FreeBSD, Linux, Darwin
302 // PowerPC Linux, Darwin
303 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000304 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000305 return 32;
306}
307
John McCalla729c622012-02-17 03:33:10 +0000308bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
309 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000310 // The following conventions are known to require this to be false:
311 // x86_stdcall
312 // MIPS
313 // For everything else, we just prefer false unless we opt out.
314 return false;
315}
316
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000317void
318TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
319 llvm::SmallString<24> &Opt) const {
320 // This assumes the user is passing a library name like "rt" instead of a
321 // filename like "librt.a/so", and that they don't care whether it's static or
322 // dynamic.
323 Opt = "-l";
324 Opt += Lib;
325}
326
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000327static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000328
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000329/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000330/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000331static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
332 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000333 if (FD->isUnnamedBitfield())
334 return true;
335
336 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000337
Eli Friedman0b3f2012011-11-18 03:47:20 +0000338 // Constant arrays of empty records count as empty, strip them off.
339 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000340 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000341 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
342 if (AT->getSize() == 0)
343 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000344 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000345 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000346
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000347 const RecordType *RT = FT->getAs<RecordType>();
348 if (!RT)
349 return false;
350
351 // C++ record fields are never empty, at least in the Itanium ABI.
352 //
353 // FIXME: We should use a predicate for whether this behavior is true in the
354 // current ABI.
355 if (isa<CXXRecordDecl>(RT->getDecl()))
356 return false;
357
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000358 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000359}
360
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000361/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000362/// fields. Note that a structure with a flexible array member is not
363/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000364static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000365 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000366 if (!RT)
367 return 0;
368 const RecordDecl *RD = RT->getDecl();
369 if (RD->hasFlexibleArrayMember())
370 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000371
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000372 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000373 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000374 for (const auto &I : CXXRD->bases())
375 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000376 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000377
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000378 for (const auto *I : RD->fields())
379 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000380 return false;
381 return true;
382}
383
384/// isSingleElementStruct - Determine if a structure is a "single
385/// element struct", i.e. it has exactly one non-empty field or
386/// exactly one field which is itself a single element
387/// struct. Structures with flexible array members are never
388/// considered single element structs.
389///
390/// \return The field declaration for the single non-empty field, if
391/// it exists.
392static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000393 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000394 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000395 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000396
397 const RecordDecl *RD = RT->getDecl();
398 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000399 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000400
Craig Topper8a13c412014-05-21 05:09:00 +0000401 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000402
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000403 // If this is a C++ record, check the bases first.
404 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000405 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000406 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000407 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000408 continue;
409
410 // If we already found an element then this isn't a single-element struct.
411 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000412 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000413
414 // If this is non-empty and not a single element struct, the composite
415 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000416 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000417 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000418 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000419 }
420 }
421
422 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000423 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000424 QualType FT = FD->getType();
425
426 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000427 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000428 continue;
429
430 // If we already found an element then this isn't a single-element
431 // struct.
432 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000433 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000434
435 // Treat single element arrays as the element.
436 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
437 if (AT->getSize().getZExtValue() != 1)
438 break;
439 FT = AT->getElementType();
440 }
441
John McCalla1dee5302010-08-22 10:59:02 +0000442 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000443 Found = FT.getTypePtr();
444 } else {
445 Found = isSingleElementStruct(FT, Context);
446 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000447 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000448 }
449 }
450
Eli Friedmanee945342011-11-18 01:25:50 +0000451 // We don't consider a struct a single-element struct if it has
452 // padding beyond the element type.
453 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000454 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000455
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000456 return Found;
457}
458
459static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000460 // Treat complex types as the element type.
461 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
462 Ty = CTy->getElementType();
463
464 // Check for a type which we know has a simple scalar argument-passing
465 // convention without any padding. (We're specifically looking for 32
466 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000467 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000468 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000469 return false;
470
471 uint64_t Size = Context.getTypeSize(Ty);
472 return Size == 32 || Size == 64;
473}
474
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000475/// canExpandIndirectArgument - Test whether an argument type which is to be
476/// passed indirectly (on the stack) would have the equivalent layout if it was
477/// expanded into separate arguments. If so, we prefer to do the latter to avoid
478/// inhibiting optimizations.
479///
480// FIXME: This predicate is missing many cases, currently it just follows
481// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
482// should probably make this smarter, or better yet make the LLVM backend
483// capable of handling it.
484static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
485 // We can only expand structure types.
486 const RecordType *RT = Ty->getAs<RecordType>();
487 if (!RT)
488 return false;
489
490 // We can only expand (C) structures.
491 //
492 // FIXME: This needs to be generalized to handle classes as well.
493 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000494 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000495 return false;
496
Manman Ren27382782015-04-03 18:10:29 +0000497 // We try to expand CLike CXXRecordDecl.
498 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
499 if (!CXXRD->isCLike())
500 return false;
501 }
502
Eli Friedmane5c85622011-11-18 01:32:26 +0000503 uint64_t Size = 0;
504
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000505 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000506 if (!is32Or64BitBasicType(FD->getType(), Context))
507 return false;
508
509 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
510 // how to expand them yet, and the predicate for telling if a bitfield still
511 // counts as "basic" is more complicated than what we were doing previously.
512 if (FD->isBitField())
513 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000514
515 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000516 }
517
Eli Friedmane5c85622011-11-18 01:32:26 +0000518 // Make sure there are not any holes in the struct.
519 if (Size != Context.getTypeSize(Ty))
520 return false;
521
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000522 return true;
523}
524
525namespace {
526/// DefaultABIInfo - The default implementation for ABI specific
527/// details. This implementation provides information which results in
528/// self-consistent and sensible LLVM IR generation, but does not
529/// conform to any particular ABI.
530class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000531public:
532 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000533
Chris Lattner458b2aa2010-07-29 02:16:43 +0000534 ABIArgInfo classifyReturnType(QualType RetTy) const;
535 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000536
Craig Topper4f12f102014-03-12 06:41:41 +0000537 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000538 if (!getCXXABI().classifyReturnType(FI))
539 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000540 for (auto &I : FI.arguments())
541 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000542 }
543
John McCall7f416cc2015-09-08 08:05:57 +0000544 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
545 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000546};
547
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000548class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
549public:
Chris Lattner2b037972010-07-29 02:01:43 +0000550 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
551 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000552};
553
John McCall7f416cc2015-09-08 08:05:57 +0000554Address DefaultABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
555 QualType Ty) const {
556 return Address::invalid();
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000557}
558
Chris Lattner458b2aa2010-07-29 02:16:43 +0000559ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000560 Ty = useFirstFieldIfTransparentUnion(Ty);
561
562 if (isAggregateTypeForABI(Ty)) {
563 // Records with non-trivial destructors/copy-constructors should not be
564 // passed by value.
565 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000566 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000567
John McCall7f416cc2015-09-08 08:05:57 +0000568 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000569 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000570
Chris Lattner9723d6c2010-03-11 18:19:55 +0000571 // Treat an enum type as its underlying type.
572 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
573 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000574
Chris Lattner9723d6c2010-03-11 18:19:55 +0000575 return (Ty->isPromotableIntegerType() ?
576 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000577}
578
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000579ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
580 if (RetTy->isVoidType())
581 return ABIArgInfo::getIgnore();
582
583 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000584 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000585
586 // Treat an enum type as its underlying type.
587 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
588 RetTy = EnumTy->getDecl()->getIntegerType();
589
590 return (RetTy->isPromotableIntegerType() ?
591 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
592}
593
Derek Schuff09338a22012-09-06 17:37:28 +0000594//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000595// WebAssembly ABI Implementation
596//
597// This is a very simple ABI that relies a lot on DefaultABIInfo.
598//===----------------------------------------------------------------------===//
599
600class WebAssemblyABIInfo final : public DefaultABIInfo {
601public:
602 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
603 : DefaultABIInfo(CGT) {}
604
605private:
606 ABIArgInfo classifyReturnType(QualType RetTy) const;
607 ABIArgInfo classifyArgumentType(QualType Ty) const;
608
609 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
610 // non-virtual, but computeInfo is virtual, so we overload that.
611 void computeInfo(CGFunctionInfo &FI) const override {
612 if (!getCXXABI().classifyReturnType(FI))
613 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
614 for (auto &Arg : FI.arguments())
615 Arg.info = classifyArgumentType(Arg.type);
616 }
617};
618
619class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
620public:
621 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
622 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
623};
624
625/// \brief Classify argument of given type \p Ty.
626ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
627 Ty = useFirstFieldIfTransparentUnion(Ty);
628
629 if (isAggregateTypeForABI(Ty)) {
630 // Records with non-trivial destructors/copy-constructors should not be
631 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000632 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000633 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000634 // Ignore empty structs/unions.
635 if (isEmptyRecord(getContext(), Ty, true))
636 return ABIArgInfo::getIgnore();
637 // Lower single-element structs to just pass a regular value. TODO: We
638 // could do reasonable-size multiple-element structs too, using getExpand(),
639 // though watch out for things like bitfields.
640 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
641 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000642 }
643
644 // Otherwise just do the default thing.
645 return DefaultABIInfo::classifyArgumentType(Ty);
646}
647
648ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
649 if (isAggregateTypeForABI(RetTy)) {
650 // Records with non-trivial destructors/copy-constructors should not be
651 // returned by value.
652 if (!getRecordArgABI(RetTy, getCXXABI())) {
653 // Ignore empty structs/unions.
654 if (isEmptyRecord(getContext(), RetTy, true))
655 return ABIArgInfo::getIgnore();
656 // Lower single-element structs to just return a regular value. TODO: We
657 // could do reasonable-size multiple-element structs too, using
658 // ABIArgInfo::getDirect().
659 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
660 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
661 }
662 }
663
664 // Otherwise just do the default thing.
665 return DefaultABIInfo::classifyReturnType(RetTy);
666}
667
668//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000669// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000670//
671// This is a simplified version of the x86_32 ABI. Arguments and return values
672// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000673//===----------------------------------------------------------------------===//
674
675class PNaClABIInfo : public ABIInfo {
676 public:
677 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
678
679 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000680 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000681
Craig Topper4f12f102014-03-12 06:41:41 +0000682 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000683 Address EmitVAArg(CodeGenFunction &CGF,
684 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000685};
686
687class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
688 public:
689 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
690 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
691};
692
693void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000694 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000695 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
696
Reid Kleckner40ca9132014-05-13 22:05:45 +0000697 for (auto &I : FI.arguments())
698 I.info = classifyArgumentType(I.type);
699}
Derek Schuff09338a22012-09-06 17:37:28 +0000700
John McCall7f416cc2015-09-08 08:05:57 +0000701Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
702 QualType Ty) const {
703 return Address::invalid();
Derek Schuff09338a22012-09-06 17:37:28 +0000704}
705
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000706/// \brief Classify argument of given type \p Ty.
707ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000708 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000709 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000710 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
711 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000712 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
713 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000714 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000715 } else if (Ty->isFloatingType()) {
716 // Floating-point types don't go inreg.
717 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000718 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000719
720 return (Ty->isPromotableIntegerType() ?
721 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000722}
723
724ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
725 if (RetTy->isVoidType())
726 return ABIArgInfo::getIgnore();
727
Eli Benderskye20dad62013-04-04 22:49:35 +0000728 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000729 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000730 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000731
732 // Treat an enum type as its underlying type.
733 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
734 RetTy = EnumTy->getDecl()->getIntegerType();
735
736 return (RetTy->isPromotableIntegerType() ?
737 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
738}
739
Chad Rosier651c1832013-03-25 21:00:27 +0000740/// IsX86_MMXType - Return true if this is an MMX type.
741bool IsX86_MMXType(llvm::Type *IRType) {
742 // 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 +0000743 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
744 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
745 IRType->getScalarSizeInBits() != 64;
746}
747
Jay Foad7c57be32011-07-11 09:56:20 +0000748static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000749 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000750 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000751 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
752 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
753 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000754 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000755 }
756
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000757 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000758 }
759
760 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000761 return Ty;
762}
763
Reid Kleckner80944df2014-10-31 22:00:51 +0000764/// Returns true if this type can be passed in SSE registers with the
765/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
766static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
767 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
768 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
769 return true;
770 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
771 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
772 // registers specially.
773 unsigned VecSize = Context.getTypeSize(VT);
774 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
775 return true;
776 }
777 return false;
778}
779
780/// Returns true if this aggregate is small enough to be passed in SSE registers
781/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
782static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
783 return NumMembers <= 4;
784}
785
Chris Lattner0cf24192010-06-28 20:05:43 +0000786//===----------------------------------------------------------------------===//
787// X86-32 ABI Implementation
788//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000789
Reid Kleckner661f35b2014-01-18 01:12:41 +0000790/// \brief Similar to llvm::CCState, but for Clang.
791struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000792 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000793
794 unsigned CC;
795 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000796 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000797};
798
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000799/// X86_32ABIInfo - The X86-32 ABI information.
800class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000801 enum Class {
802 Integer,
803 Float
804 };
805
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000806 static const unsigned MinABIStackAlignInBytes = 4;
807
David Chisnallde3a0692009-08-17 23:08:21 +0000808 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000809 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000810 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000811 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000812 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000813 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000814
815 static bool isRegisterSize(unsigned Size) {
816 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
817 }
818
Reid Kleckner80944df2014-10-31 22:00:51 +0000819 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
820 // FIXME: Assumes vectorcall is in use.
821 return isX86VectorTypeForVectorCall(getContext(), Ty);
822 }
823
824 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
825 uint64_t NumMembers) const override {
826 // FIXME: Assumes vectorcall is in use.
827 return isX86VectorCallAggregateSmallEnough(NumMembers);
828 }
829
Reid Kleckner40ca9132014-05-13 22:05:45 +0000830 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000831
Daniel Dunbar557893d2010-04-21 19:10:51 +0000832 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
833 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000834 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
835
John McCall7f416cc2015-09-08 08:05:57 +0000836 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000837
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000838 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000839 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000840
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000841 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000842 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000843 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000844 /// \brief Updates the number of available free registers, returns
845 /// true if any registers were allocated.
846 bool updateFreeRegs(QualType Ty, CCState &State) const;
847
848 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
849 bool &NeedsPadding) const;
850 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000851
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000852 /// \brief Rewrite the function info so that all memory arguments use
853 /// inalloca.
854 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
855
856 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000857 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000858 QualType Type) const;
859
Rafael Espindola75419dc2012-07-23 23:30:29 +0000860public:
861
Craig Topper4f12f102014-03-12 06:41:41 +0000862 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000863 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
864 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000865
Michael Kupersteindc745202015-10-19 07:52:25 +0000866 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
867 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000868 unsigned NumRegisterParameters, bool SoftFloatABI)
Michael Kupersteindc745202015-10-19 07:52:25 +0000869 : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
870 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
871 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000872 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000873 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000874 DefaultNumRegisterParameters(NumRegisterParameters) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000875};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000876
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000877class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
878public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000879 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
880 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000881 unsigned NumRegisterParameters, bool SoftFloatABI)
882 : TargetCodeGenInfo(new X86_32ABIInfo(
883 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
884 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000885
John McCall1fe2a8c2013-06-18 02:46:29 +0000886 static bool isStructReturnInRegABI(
887 const llvm::Triple &Triple, const CodeGenOptions &Opts);
888
Eric Christopher162c91c2015-06-05 22:03:00 +0000889 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000890 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000891
Craig Topper4f12f102014-03-12 06:41:41 +0000892 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000893 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000894 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000895 return 4;
896 }
897
898 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000899 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000900
Jay Foad7c57be32011-07-11 09:56:20 +0000901 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000902 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000903 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000904 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
905 }
906
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000907 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
908 std::string &Constraints,
909 std::vector<llvm::Type *> &ResultRegTypes,
910 std::vector<llvm::Type *> &ResultTruncRegTypes,
911 std::vector<LValue> &ResultRegDests,
912 std::string &AsmString,
913 unsigned NumOutputs) const override;
914
Craig Topper4f12f102014-03-12 06:41:41 +0000915 llvm::Constant *
916 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000917 unsigned Sig = (0xeb << 0) | // jmp rel8
918 (0x06 << 8) | // .+0x08
919 ('F' << 16) |
920 ('T' << 24);
921 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
922 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000923};
924
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000925}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000926
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000927/// Rewrite input constraint references after adding some output constraints.
928/// In the case where there is one output and one input and we add one output,
929/// we need to replace all operand references greater than or equal to 1:
930/// mov $0, $1
931/// mov eax, $1
932/// The result will be:
933/// mov $0, $2
934/// mov eax, $2
935static void rewriteInputConstraintReferences(unsigned FirstIn,
936 unsigned NumNewOuts,
937 std::string &AsmString) {
938 std::string Buf;
939 llvm::raw_string_ostream OS(Buf);
940 size_t Pos = 0;
941 while (Pos < AsmString.size()) {
942 size_t DollarStart = AsmString.find('$', Pos);
943 if (DollarStart == std::string::npos)
944 DollarStart = AsmString.size();
945 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
946 if (DollarEnd == std::string::npos)
947 DollarEnd = AsmString.size();
948 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
949 Pos = DollarEnd;
950 size_t NumDollars = DollarEnd - DollarStart;
951 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
952 // We have an operand reference.
953 size_t DigitStart = Pos;
954 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
955 if (DigitEnd == std::string::npos)
956 DigitEnd = AsmString.size();
957 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
958 unsigned OperandIndex;
959 if (!OperandStr.getAsInteger(10, OperandIndex)) {
960 if (OperandIndex >= FirstIn)
961 OperandIndex += NumNewOuts;
962 OS << OperandIndex;
963 } else {
964 OS << OperandStr;
965 }
966 Pos = DigitEnd;
967 }
968 }
969 AsmString = std::move(OS.str());
970}
971
972/// Add output constraints for EAX:EDX because they are return registers.
973void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
974 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
975 std::vector<llvm::Type *> &ResultRegTypes,
976 std::vector<llvm::Type *> &ResultTruncRegTypes,
977 std::vector<LValue> &ResultRegDests, std::string &AsmString,
978 unsigned NumOutputs) const {
979 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
980
981 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
982 // larger.
983 if (!Constraints.empty())
984 Constraints += ',';
985 if (RetWidth <= 32) {
986 Constraints += "={eax}";
987 ResultRegTypes.push_back(CGF.Int32Ty);
988 } else {
989 // Use the 'A' constraint for EAX:EDX.
990 Constraints += "=A";
991 ResultRegTypes.push_back(CGF.Int64Ty);
992 }
993
994 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
995 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
996 ResultTruncRegTypes.push_back(CoerceTy);
997
998 // Coerce the integer by bitcasting the return slot pointer.
999 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1000 CoerceTy->getPointerTo()));
1001 ResultRegDests.push_back(ReturnSlot);
1002
1003 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1004}
1005
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001006/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001007/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001008bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1009 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001010 uint64_t Size = Context.getTypeSize(Ty);
1011
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001012 // For i386, type must be register sized.
1013 // For the MCU ABI, it only needs to be <= 8-byte
1014 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1015 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001016
1017 if (Ty->isVectorType()) {
1018 // 64- and 128- bit vectors inside structures are not returned in
1019 // registers.
1020 if (Size == 64 || Size == 128)
1021 return false;
1022
1023 return true;
1024 }
1025
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001026 // If this is a builtin, pointer, enum, complex type, member pointer, or
1027 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001028 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001029 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001030 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001031 return true;
1032
1033 // Arrays are treated like records.
1034 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001035 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001036
1037 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001038 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001039 if (!RT) return false;
1040
Anders Carlsson40446e82010-01-27 03:25:19 +00001041 // FIXME: Traverse bases here too.
1042
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001043 // Structure types are passed in register if all fields would be
1044 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001045 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001046 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001047 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001048 continue;
1049
1050 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001051 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001052 return false;
1053 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001054 return true;
1055}
1056
John McCall7f416cc2015-09-08 08:05:57 +00001057ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001058 // If the return value is indirect, then the hidden argument is consuming one
1059 // integer register.
1060 if (State.FreeRegs) {
1061 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001062 if (!IsMCUABI)
1063 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001064 }
John McCall7f416cc2015-09-08 08:05:57 +00001065 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001066}
1067
Eric Christopher7565e0d2015-05-29 23:09:49 +00001068ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1069 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001070 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001071 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001072
Reid Kleckner80944df2014-10-31 22:00:51 +00001073 const Type *Base = nullptr;
1074 uint64_t NumElts = 0;
1075 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1076 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1077 // The LLVM struct type for such an aggregate should lower properly.
1078 return ABIArgInfo::getDirect();
1079 }
1080
Chris Lattner458b2aa2010-07-29 02:16:43 +00001081 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001082 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001083 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001084 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001085
1086 // 128-bit vectors are a special case; they are returned in
1087 // registers and we need to make sure to pick a type the LLVM
1088 // backend will like.
1089 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001090 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001091 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001092
1093 // Always return in register if it fits in a general purpose
1094 // register, or if it is 64 bits and has a single element.
1095 if ((Size == 8 || Size == 16 || Size == 32) ||
1096 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001097 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001098 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001099
John McCall7f416cc2015-09-08 08:05:57 +00001100 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001101 }
1102
1103 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001104 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001105
John McCalla1dee5302010-08-22 10:59:02 +00001106 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001107 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001108 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001109 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001110 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001111 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001112
David Chisnallde3a0692009-08-17 23:08:21 +00001113 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001114 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001115 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001117 // Small structures which are register sized are generally returned
1118 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001119 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001120 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001121
1122 // As a special-case, if the struct is a "single-element" struct, and
1123 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001124 // floating-point register. (MSVC does not apply this special case.)
1125 // We apply a similar transformation for pointer types to improve the
1126 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001127 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001128 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001129 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001130 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1131
1132 // FIXME: We should be able to narrow this integer in cases with dead
1133 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001134 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001135 }
1136
John McCall7f416cc2015-09-08 08:05:57 +00001137 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001138 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001139
Chris Lattner458b2aa2010-07-29 02:16:43 +00001140 // Treat an enum type as its underlying type.
1141 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1142 RetTy = EnumTy->getDecl()->getIntegerType();
1143
1144 return (RetTy->isPromotableIntegerType() ?
1145 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001146}
1147
Eli Friedman7919bea2012-06-05 19:40:46 +00001148static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1149 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1150}
1151
Daniel Dunbared23de32010-09-16 20:42:00 +00001152static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1153 const RecordType *RT = Ty->getAs<RecordType>();
1154 if (!RT)
1155 return 0;
1156 const RecordDecl *RD = RT->getDecl();
1157
1158 // If this is a C++ record, check the bases first.
1159 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001160 for (const auto &I : CXXRD->bases())
1161 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001162 return false;
1163
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001164 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001165 QualType FT = i->getType();
1166
Eli Friedman7919bea2012-06-05 19:40:46 +00001167 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001168 return true;
1169
1170 if (isRecordWithSSEVectorType(Context, FT))
1171 return true;
1172 }
1173
1174 return false;
1175}
1176
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001177unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1178 unsigned Align) const {
1179 // Otherwise, if the alignment is less than or equal to the minimum ABI
1180 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001181 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001182 return 0; // Use default alignment.
1183
1184 // On non-Darwin, the stack type alignment is always 4.
1185 if (!IsDarwinVectorABI) {
1186 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001187 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001188 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001189
Daniel Dunbared23de32010-09-16 20:42:00 +00001190 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001191 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1192 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001193 return 16;
1194
1195 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001196}
1197
Rafael Espindola703c47f2012-10-19 05:04:37 +00001198ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001199 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001200 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001201 if (State.FreeRegs) {
1202 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001203 if (!IsMCUABI)
1204 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001205 }
John McCall7f416cc2015-09-08 08:05:57 +00001206 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001207 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001208
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001209 // Compute the byval alignment.
1210 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1211 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1212 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001213 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001214
1215 // If the stack alignment is less than the type alignment, realign the
1216 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001217 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001218 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1219 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001220}
1221
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001222X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1223 const Type *T = isSingleElementStruct(Ty, getContext());
1224 if (!T)
1225 T = Ty.getTypePtr();
1226
1227 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1228 BuiltinType::Kind K = BT->getKind();
1229 if (K == BuiltinType::Float || K == BuiltinType::Double)
1230 return Float;
1231 }
1232 return Integer;
1233}
1234
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001235bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001236 if (!IsSoftFloatABI) {
1237 Class C = classify(Ty);
1238 if (C == Float)
1239 return false;
1240 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001241
Rafael Espindola077dd592012-10-24 01:58:58 +00001242 unsigned Size = getContext().getTypeSize(Ty);
1243 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001244
1245 if (SizeInRegs == 0)
1246 return false;
1247
Michael Kuperstein68901882015-10-25 08:18:20 +00001248 if (!IsMCUABI) {
1249 if (SizeInRegs > State.FreeRegs) {
1250 State.FreeRegs = 0;
1251 return false;
1252 }
1253 } else {
1254 // The MCU psABI allows passing parameters in-reg even if there are
1255 // earlier parameters that are passed on the stack. Also,
1256 // it does not allow passing >8-byte structs in-register,
1257 // even if there are 3 free registers available.
1258 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1259 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001260 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001261
Reid Kleckner661f35b2014-01-18 01:12:41 +00001262 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001263 return true;
1264}
1265
1266bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1267 bool &InReg,
1268 bool &NeedsPadding) const {
1269 NeedsPadding = false;
1270 InReg = !IsMCUABI;
1271
1272 if (!updateFreeRegs(Ty, State))
1273 return false;
1274
1275 if (IsMCUABI)
1276 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001277
Reid Kleckner80944df2014-10-31 22:00:51 +00001278 if (State.CC == llvm::CallingConv::X86_FastCall ||
1279 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001280 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001281 NeedsPadding = true;
1282
Rafael Espindola077dd592012-10-24 01:58:58 +00001283 return false;
1284 }
1285
Rafael Espindola703c47f2012-10-19 05:04:37 +00001286 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001287}
1288
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001289bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1290 if (!updateFreeRegs(Ty, State))
1291 return false;
1292
1293 if (IsMCUABI)
1294 return false;
1295
1296 if (State.CC == llvm::CallingConv::X86_FastCall ||
1297 State.CC == llvm::CallingConv::X86_VectorCall) {
1298 if (getContext().getTypeSize(Ty) > 32)
1299 return false;
1300
1301 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1302 Ty->isReferenceType());
1303 }
1304
1305 return true;
1306}
1307
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001308ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1309 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001310 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001311
Reid Klecknerb1be6832014-11-15 01:41:41 +00001312 Ty = useFirstFieldIfTransparentUnion(Ty);
1313
Reid Kleckner80944df2014-10-31 22:00:51 +00001314 // Check with the C++ ABI first.
1315 const RecordType *RT = Ty->getAs<RecordType>();
1316 if (RT) {
1317 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1318 if (RAA == CGCXXABI::RAA_Indirect) {
1319 return getIndirectResult(Ty, false, State);
1320 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1321 // The field index doesn't matter, we'll fix it up later.
1322 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1323 }
1324 }
1325
1326 // vectorcall adds the concept of a homogenous vector aggregate, similar
1327 // to other targets.
1328 const Type *Base = nullptr;
1329 uint64_t NumElts = 0;
1330 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1331 isHomogeneousAggregate(Ty, Base, NumElts)) {
1332 if (State.FreeSSERegs >= NumElts) {
1333 State.FreeSSERegs -= NumElts;
1334 if (Ty->isBuiltinType() || Ty->isVectorType())
1335 return ABIArgInfo::getDirect();
1336 return ABIArgInfo::getExpand();
1337 }
1338 return getIndirectResult(Ty, /*ByVal=*/false, State);
1339 }
1340
1341 if (isAggregateTypeForABI(Ty)) {
1342 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001343 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001344 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001345 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001346
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001347 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001348 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001349 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001350 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001351
Eli Friedman9f061a32011-11-18 00:28:11 +00001352 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001353 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001354 return ABIArgInfo::getIgnore();
1355
Rafael Espindolafad28de2012-10-24 01:59:00 +00001356 llvm::LLVMContext &LLVMContext = getVMContext();
1357 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001358 bool NeedsPadding, InReg;
1359 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001360 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001361 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001362 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001363 if (InReg)
1364 return ABIArgInfo::getDirectInReg(Result);
1365 else
1366 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001367 }
Craig Topper8a13c412014-05-21 05:09:00 +00001368 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001369
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001370 // Expand small (<= 128-bit) record types when we know that the stack layout
1371 // of those arguments will match the struct. This is important because the
1372 // LLVM backend isn't smart enough to remove byval, which inhibits many
1373 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001374 // Don't do this for the MCU if there are still free integer registers
1375 // (see X86_64 ABI for full explanation).
Chris Lattner458b2aa2010-07-29 02:16:43 +00001376 if (getContext().getTypeSize(Ty) <= 4*32 &&
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001377 canExpandIndirectArgument(Ty, getContext()) &&
1378 (!IsMCUABI || State.FreeRegs == 0))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001379 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001380 State.CC == llvm::CallingConv::X86_FastCall ||
1381 State.CC == llvm::CallingConv::X86_VectorCall,
1382 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001383
Reid Kleckner661f35b2014-01-18 01:12:41 +00001384 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001385 }
1386
Chris Lattnerd774ae92010-08-26 20:05:13 +00001387 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001388 // On Darwin, some vectors are passed in memory, we handle this by passing
1389 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001390 if (IsDarwinVectorABI) {
1391 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001392 if ((Size == 8 || Size == 16 || Size == 32) ||
1393 (Size == 64 && VT->getNumElements() == 1))
1394 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1395 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001396 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001397
Chad Rosier651c1832013-03-25 21:00:27 +00001398 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1399 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001400
Chris Lattnerd774ae92010-08-26 20:05:13 +00001401 return ABIArgInfo::getDirect();
1402 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001403
1404
Chris Lattner458b2aa2010-07-29 02:16:43 +00001405 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1406 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001407
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001408 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001409
1410 if (Ty->isPromotableIntegerType()) {
1411 if (InReg)
1412 return ABIArgInfo::getExtendInReg();
1413 return ABIArgInfo::getExtend();
1414 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001415
Rafael Espindola703c47f2012-10-19 05:04:37 +00001416 if (InReg)
1417 return ABIArgInfo::getDirectInReg();
1418 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001419}
1420
Rafael Espindolaa6472962012-07-24 00:01:07 +00001421void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001422 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001423 if (IsMCUABI)
1424 State.FreeRegs = 3;
1425 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001426 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001427 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1428 State.FreeRegs = 2;
1429 State.FreeSSERegs = 6;
1430 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001431 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001432 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001433 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001434
Reid Kleckner677539d2014-07-10 01:58:55 +00001435 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001436 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001437 } else if (FI.getReturnInfo().isIndirect()) {
1438 // The C++ ABI is not aware of register usage, so we have to check if the
1439 // return value was sret and put it in a register ourselves if appropriate.
1440 if (State.FreeRegs) {
1441 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001442 if (!IsMCUABI)
1443 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001444 }
1445 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001446
Peter Collingbournef7706832014-12-12 23:41:25 +00001447 // The chain argument effectively gives us another free register.
1448 if (FI.isChainCall())
1449 ++State.FreeRegs;
1450
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001451 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001452 for (auto &I : FI.arguments()) {
1453 I.info = classifyArgumentType(I.type, State);
1454 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001455 }
1456
1457 // If we needed to use inalloca for any argument, do a second pass and rewrite
1458 // all the memory arguments to use inalloca.
1459 if (UsedInAlloca)
1460 rewriteWithInAlloca(FI);
1461}
1462
1463void
1464X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001465 CharUnits &StackOffset, ABIArgInfo &Info,
1466 QualType Type) const {
1467 // Arguments are always 4-byte-aligned.
1468 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1469
1470 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001471 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1472 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001473 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001474
John McCall7f416cc2015-09-08 08:05:57 +00001475 // Insert padding bytes to respect alignment.
1476 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001477 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001478 if (StackOffset != FieldEnd) {
1479 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001480 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001481 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001482 FrameFields.push_back(Ty);
1483 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001484}
1485
Reid Kleckner852361d2014-07-26 00:12:26 +00001486static bool isArgInAlloca(const ABIArgInfo &Info) {
1487 // Leave ignored and inreg arguments alone.
1488 switch (Info.getKind()) {
1489 case ABIArgInfo::InAlloca:
1490 return true;
1491 case ABIArgInfo::Indirect:
1492 assert(Info.getIndirectByVal());
1493 return true;
1494 case ABIArgInfo::Ignore:
1495 return false;
1496 case ABIArgInfo::Direct:
1497 case ABIArgInfo::Extend:
1498 case ABIArgInfo::Expand:
1499 if (Info.getInReg())
1500 return false;
1501 return true;
1502 }
1503 llvm_unreachable("invalid enum");
1504}
1505
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001506void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1507 assert(IsWin32StructABI && "inalloca only supported on win32");
1508
1509 // Build a packed struct type for all of the arguments in memory.
1510 SmallVector<llvm::Type *, 6> FrameFields;
1511
John McCall7f416cc2015-09-08 08:05:57 +00001512 // The stack alignment is always 4.
1513 CharUnits StackAlign = CharUnits::fromQuantity(4);
1514
1515 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001516 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1517
1518 // Put 'this' into the struct before 'sret', if necessary.
1519 bool IsThisCall =
1520 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1521 ABIArgInfo &Ret = FI.getReturnInfo();
1522 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1523 isArgInAlloca(I->info)) {
1524 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1525 ++I;
1526 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001527
1528 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001529 if (Ret.isIndirect() && !Ret.getInReg()) {
1530 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1531 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001532 // On Windows, the hidden sret parameter is always returned in eax.
1533 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001534 }
1535
1536 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001537 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001538 ++I;
1539
1540 // Put arguments passed in memory into the struct.
1541 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001542 if (isArgInAlloca(I->info))
1543 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001544 }
1545
1546 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001547 /*isPacked=*/true),
1548 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001549}
1550
John McCall7f416cc2015-09-08 08:05:57 +00001551Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1552 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001553
John McCall7f416cc2015-09-08 08:05:57 +00001554 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001555
John McCall7f416cc2015-09-08 08:05:57 +00001556 // x86-32 changes the alignment of certain arguments on the stack.
1557 //
1558 // Just messing with TypeInfo like this works because we never pass
1559 // anything indirectly.
1560 TypeInfo.second = CharUnits::fromQuantity(
1561 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001562
John McCall7f416cc2015-09-08 08:05:57 +00001563 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1564 TypeInfo, CharUnits::fromQuantity(4),
1565 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001566}
1567
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001568bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1569 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1570 assert(Triple.getArch() == llvm::Triple::x86);
1571
1572 switch (Opts.getStructReturnConvention()) {
1573 case CodeGenOptions::SRCK_Default:
1574 break;
1575 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1576 return false;
1577 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1578 return true;
1579 }
1580
Michael Kupersteind749f232015-10-27 07:46:22 +00001581 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001582 return true;
1583
1584 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001585 case llvm::Triple::DragonFly:
1586 case llvm::Triple::FreeBSD:
1587 case llvm::Triple::OpenBSD:
1588 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001589 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001590 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001591 default:
1592 return false;
1593 }
1594}
1595
Eric Christopher162c91c2015-06-05 22:03:00 +00001596void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001597 llvm::GlobalValue *GV,
1598 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001599 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001600 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1601 // Get the LLVM function.
1602 llvm::Function *Fn = cast<llvm::Function>(GV);
1603
1604 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001605 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001606 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001607 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1608 llvm::AttributeSet::get(CGM.getLLVMContext(),
1609 llvm::AttributeSet::FunctionIndex,
1610 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001611 }
1612 }
1613}
1614
John McCallbeec5a02010-03-06 00:35:14 +00001615bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1616 CodeGen::CodeGenFunction &CGF,
1617 llvm::Value *Address) const {
1618 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001619
Chris Lattnerece04092012-02-07 00:39:47 +00001620 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001621
John McCallbeec5a02010-03-06 00:35:14 +00001622 // 0-7 are the eight integer registers; the order is different
1623 // on Darwin (for EH), but the range is the same.
1624 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001625 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001626
John McCallc8e01702013-04-16 22:48:15 +00001627 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001628 // 12-16 are st(0..4). Not sure why we stop at 4.
1629 // These have size 16, which is sizeof(long double) on
1630 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001631 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001632 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001633
John McCallbeec5a02010-03-06 00:35:14 +00001634 } else {
1635 // 9 is %eflags, which doesn't get a size on Darwin for some
1636 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001637 Builder.CreateAlignedStore(
1638 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1639 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001640
1641 // 11-16 are st(0..5). Not sure why we stop at 5.
1642 // These have size 12, which is sizeof(long double) on
1643 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001644 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001645 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1646 }
John McCallbeec5a02010-03-06 00:35:14 +00001647
1648 return false;
1649}
1650
Chris Lattner0cf24192010-06-28 20:05:43 +00001651//===----------------------------------------------------------------------===//
1652// X86-64 ABI Implementation
1653//===----------------------------------------------------------------------===//
1654
1655
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001656namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001657/// The AVX ABI level for X86 targets.
1658enum class X86AVXABILevel {
1659 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001660 AVX,
1661 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001662};
1663
1664/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1665static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1666 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001667 case X86AVXABILevel::AVX512:
1668 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001669 case X86AVXABILevel::AVX:
1670 return 256;
1671 case X86AVXABILevel::None:
1672 return 128;
1673 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001674 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001675}
1676
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001677/// X86_64ABIInfo - The X86_64 ABI information.
1678class X86_64ABIInfo : public ABIInfo {
1679 enum Class {
1680 Integer = 0,
1681 SSE,
1682 SSEUp,
1683 X87,
1684 X87Up,
1685 ComplexX87,
1686 NoClass,
1687 Memory
1688 };
1689
1690 /// merge - Implement the X86_64 ABI merging algorithm.
1691 ///
1692 /// Merge an accumulating classification \arg Accum with a field
1693 /// classification \arg Field.
1694 ///
1695 /// \param Accum - The accumulating classification. This should
1696 /// always be either NoClass or the result of a previous merge
1697 /// call. In addition, this should never be Memory (the caller
1698 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001699 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001700
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001701 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1702 ///
1703 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1704 /// final MEMORY or SSE classes when necessary.
1705 ///
1706 /// \param AggregateSize - The size of the current aggregate in
1707 /// the classification process.
1708 ///
1709 /// \param Lo - The classification for the parts of the type
1710 /// residing in the low word of the containing object.
1711 ///
1712 /// \param Hi - The classification for the parts of the type
1713 /// residing in the higher words of the containing object.
1714 ///
1715 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1716
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001717 /// classify - Determine the x86_64 register classes in which the
1718 /// given type T should be passed.
1719 ///
1720 /// \param Lo - The classification for the parts of the type
1721 /// residing in the low word of the containing object.
1722 ///
1723 /// \param Hi - The classification for the parts of the type
1724 /// residing in the high word of the containing object.
1725 ///
1726 /// \param OffsetBase - The bit offset of this type in the
1727 /// containing object. Some parameters are classified different
1728 /// depending on whether they straddle an eightbyte boundary.
1729 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001730 /// \param isNamedArg - Whether the argument in question is a "named"
1731 /// argument, as used in AMD64-ABI 3.5.7.
1732 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001733 /// If a word is unused its result will be NoClass; if a type should
1734 /// be passed in Memory then at least the classification of \arg Lo
1735 /// will be Memory.
1736 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001737 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001738 ///
1739 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1740 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001741 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1742 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001743
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001744 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001745 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1746 unsigned IROffset, QualType SourceTy,
1747 unsigned SourceOffset) const;
1748 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1749 unsigned IROffset, QualType SourceTy,
1750 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001751
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001752 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001753 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001754 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001755
1756 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001757 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001758 ///
1759 /// \param freeIntRegs - The number of free integer registers remaining
1760 /// available.
1761 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001762
Chris Lattner458b2aa2010-07-29 02:16:43 +00001763 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001764
Bill Wendling5cd41c42010-10-18 03:41:31 +00001765 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001766 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001767 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001768 unsigned &neededSSE,
1769 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001770
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001771 bool IsIllegalVectorType(QualType Ty) const;
1772
John McCalle0fda732011-04-21 01:20:55 +00001773 /// The 0.98 ABI revision clarified a lot of ambiguities,
1774 /// unfortunately in ways that were not always consistent with
1775 /// certain previous compilers. In particular, platforms which
1776 /// required strict binary compatibility with older versions of GCC
1777 /// may need to exempt themselves.
1778 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001779 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001780 }
1781
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001782 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001783 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1784 // 64-bit hardware.
1785 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001786
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001787public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001788 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1789 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001790 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001791 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001792
John McCalla729c622012-02-17 03:33:10 +00001793 bool isPassedUsingAVXType(QualType type) const {
1794 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001795 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001796 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1797 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001798 if (info.isDirect()) {
1799 llvm::Type *ty = info.getCoerceToType();
1800 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1801 return (vectorTy->getBitWidth() > 128);
1802 }
1803 return false;
1804 }
1805
Craig Topper4f12f102014-03-12 06:41:41 +00001806 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001807
John McCall7f416cc2015-09-08 08:05:57 +00001808 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1809 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001810 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1811 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001812
1813 bool has64BitPointers() const {
1814 return Has64BitPointers;
1815 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001816};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001817
Chris Lattner04dc9572010-08-31 16:44:54 +00001818/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001819class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001820public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001821 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1822 : ABIInfo(CGT),
1823 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001824
Craig Topper4f12f102014-03-12 06:41:41 +00001825 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001826
John McCall7f416cc2015-09-08 08:05:57 +00001827 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1828 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001829
1830 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1831 // FIXME: Assumes vectorcall is in use.
1832 return isX86VectorTypeForVectorCall(getContext(), Ty);
1833 }
1834
1835 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1836 uint64_t NumMembers) const override {
1837 // FIXME: Assumes vectorcall is in use.
1838 return isX86VectorCallAggregateSmallEnough(NumMembers);
1839 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001840
1841private:
1842 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1843 bool IsReturnType) const;
1844
1845 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00001846};
1847
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001848class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1849public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001850 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001851 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001852
John McCalla729c622012-02-17 03:33:10 +00001853 const X86_64ABIInfo &getABIInfo() const {
1854 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1855 }
1856
Craig Topper4f12f102014-03-12 06:41:41 +00001857 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001858 return 7;
1859 }
1860
1861 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001862 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001863 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001864
John McCall943fae92010-05-27 06:19:26 +00001865 // 0-15 are the 16 integer registers.
1866 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001867 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001868 return false;
1869 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001870
Jay Foad7c57be32011-07-11 09:56:20 +00001871 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001872 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001873 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001874 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1875 }
1876
John McCalla729c622012-02-17 03:33:10 +00001877 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001878 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001879 // The default CC on x86-64 sets %al to the number of SSA
1880 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001881 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001882 // that when AVX types are involved: the ABI explicitly states it is
1883 // undefined, and it doesn't work in practice because of how the ABI
1884 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001885 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001886 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001887 for (CallArgList::const_iterator
1888 it = args.begin(), ie = args.end(); it != ie; ++it) {
1889 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1890 HasAVXType = true;
1891 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001892 }
1893 }
John McCalla729c622012-02-17 03:33:10 +00001894
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001895 if (!HasAVXType)
1896 return true;
1897 }
John McCallcbc038a2011-09-21 08:08:30 +00001898
John McCalla729c622012-02-17 03:33:10 +00001899 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001900 }
1901
Craig Topper4f12f102014-03-12 06:41:41 +00001902 llvm::Constant *
1903 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001904 unsigned Sig;
1905 if (getABIInfo().has64BitPointers())
1906 Sig = (0xeb << 0) | // jmp rel8
1907 (0x0a << 8) | // .+0x0c
1908 ('F' << 16) |
1909 ('T' << 24);
1910 else
1911 Sig = (0xeb << 0) | // jmp rel8
1912 (0x06 << 8) | // .+0x08
1913 ('F' << 16) |
1914 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001915 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1916 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001917};
1918
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001919class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1920public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001921 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1922 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001923
1924 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001925 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001926 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001927 // If the argument contains a space, enclose it in quotes.
1928 if (Lib.find(" ") != StringRef::npos)
1929 Opt += "\"" + Lib.str() + "\"";
1930 else
1931 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001932 }
1933};
1934
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001935static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001936 // If the argument does not end in .lib, automatically add the suffix.
1937 // If the argument contains a space, enclose it in quotes.
1938 // This matches the behavior of MSVC.
1939 bool Quote = (Lib.find(" ") != StringRef::npos);
1940 std::string ArgStr = Quote ? "\"" : "";
1941 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001942 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001943 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001944 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001945 return ArgStr;
1946}
1947
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001948class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1949public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001950 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00001951 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1952 unsigned NumRegisterParameters)
1953 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001954 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001955
Eric Christopher162c91c2015-06-05 22:03:00 +00001956 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001957 CodeGen::CodeGenModule &CGM) const override;
1958
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001959 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001960 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001961 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001962 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001963 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001964
1965 void getDetectMismatchOption(llvm::StringRef Name,
1966 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001967 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001968 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001969 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001970};
1971
Hans Wennborg77dc2362015-01-20 19:45:50 +00001972static void addStackProbeSizeTargetAttribute(const Decl *D,
1973 llvm::GlobalValue *GV,
1974 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001975 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00001976 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1977 llvm::Function *Fn = cast<llvm::Function>(GV);
1978
Eric Christopher7565e0d2015-05-29 23:09:49 +00001979 Fn->addFnAttr("stack-probe-size",
1980 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001981 }
1982 }
1983}
1984
Eric Christopher162c91c2015-06-05 22:03:00 +00001985void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001986 llvm::GlobalValue *GV,
1987 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001988 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001989
1990 addStackProbeSizeTargetAttribute(D, GV, CGM);
1991}
1992
Chris Lattner04dc9572010-08-31 16:44:54 +00001993class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1994public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001995 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1996 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001997 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001998
Eric Christopher162c91c2015-06-05 22:03:00 +00001999 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002000 CodeGen::CodeGenModule &CGM) const override;
2001
Craig Topper4f12f102014-03-12 06:41:41 +00002002 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002003 return 7;
2004 }
2005
2006 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002007 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002008 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002009
Chris Lattner04dc9572010-08-31 16:44:54 +00002010 // 0-15 are the 16 integer registers.
2011 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002012 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002013 return false;
2014 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002015
2016 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002017 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002018 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002019 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002020 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002021
2022 void getDetectMismatchOption(llvm::StringRef Name,
2023 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002024 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002025 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002026 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002027};
2028
Eric Christopher162c91c2015-06-05 22:03:00 +00002029void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002030 llvm::GlobalValue *GV,
2031 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002032 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002033
2034 addStackProbeSizeTargetAttribute(D, GV, CGM);
2035}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002036}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002037
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002038void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2039 Class &Hi) const {
2040 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2041 //
2042 // (a) If one of the classes is Memory, the whole argument is passed in
2043 // memory.
2044 //
2045 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2046 // memory.
2047 //
2048 // (c) If the size of the aggregate exceeds two eightbytes and the first
2049 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2050 // argument is passed in memory. NOTE: This is necessary to keep the
2051 // ABI working for processors that don't support the __m256 type.
2052 //
2053 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2054 //
2055 // Some of these are enforced by the merging logic. Others can arise
2056 // only with unions; for example:
2057 // union { _Complex double; unsigned; }
2058 //
2059 // Note that clauses (b) and (c) were added in 0.98.
2060 //
2061 if (Hi == Memory)
2062 Lo = Memory;
2063 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2064 Lo = Memory;
2065 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2066 Lo = Memory;
2067 if (Hi == SSEUp && Lo != SSE)
2068 Hi = SSE;
2069}
2070
Chris Lattnerd776fb12010-06-28 21:43:59 +00002071X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002072 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2073 // classified recursively so that always two fields are
2074 // considered. The resulting class is calculated according to
2075 // the classes of the fields in the eightbyte:
2076 //
2077 // (a) If both classes are equal, this is the resulting class.
2078 //
2079 // (b) If one of the classes is NO_CLASS, the resulting class is
2080 // the other class.
2081 //
2082 // (c) If one of the classes is MEMORY, the result is the MEMORY
2083 // class.
2084 //
2085 // (d) If one of the classes is INTEGER, the result is the
2086 // INTEGER.
2087 //
2088 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2089 // MEMORY is used as class.
2090 //
2091 // (f) Otherwise class SSE is used.
2092
2093 // Accum should never be memory (we should have returned) or
2094 // ComplexX87 (because this cannot be passed in a structure).
2095 assert((Accum != Memory && Accum != ComplexX87) &&
2096 "Invalid accumulated classification during merge.");
2097 if (Accum == Field || Field == NoClass)
2098 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002099 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002100 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002101 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002102 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002103 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002104 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002105 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2106 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002107 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002108 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002109}
2110
Chris Lattner5c740f12010-06-30 19:14:05 +00002111void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002112 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002113 // FIXME: This code can be simplified by introducing a simple value class for
2114 // Class pairs with appropriate constructor methods for the various
2115 // situations.
2116
2117 // FIXME: Some of the split computations are wrong; unaligned vectors
2118 // shouldn't be passed in registers for example, so there is no chance they
2119 // can straddle an eightbyte. Verify & simplify.
2120
2121 Lo = Hi = NoClass;
2122
2123 Class &Current = OffsetBase < 64 ? Lo : Hi;
2124 Current = Memory;
2125
John McCall9dd450b2009-09-21 23:43:11 +00002126 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002127 BuiltinType::Kind k = BT->getKind();
2128
2129 if (k == BuiltinType::Void) {
2130 Current = NoClass;
2131 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2132 Lo = Integer;
2133 Hi = Integer;
2134 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2135 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002136 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002137 Current = SSE;
2138 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002139 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2140 if (LDF == &llvm::APFloat::IEEEquad) {
2141 Lo = SSE;
2142 Hi = SSEUp;
2143 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2144 Lo = X87;
2145 Hi = X87Up;
2146 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2147 Current = SSE;
2148 } else
2149 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002150 }
2151 // FIXME: _Decimal32 and _Decimal64 are SSE.
2152 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002153 return;
2154 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002155
Chris Lattnerd776fb12010-06-28 21:43:59 +00002156 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002157 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002158 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002159 return;
2160 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002161
Chris Lattnerd776fb12010-06-28 21:43:59 +00002162 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002163 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002164 return;
2165 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002166
Chris Lattnerd776fb12010-06-28 21:43:59 +00002167 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002168 if (Ty->isMemberFunctionPointerType()) {
2169 if (Has64BitPointers) {
2170 // If Has64BitPointers, this is an {i64, i64}, so classify both
2171 // Lo and Hi now.
2172 Lo = Hi = Integer;
2173 } else {
2174 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2175 // straddles an eightbyte boundary, Hi should be classified as well.
2176 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2177 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2178 if (EB_FuncPtr != EB_ThisAdj) {
2179 Lo = Hi = Integer;
2180 } else {
2181 Current = Integer;
2182 }
2183 }
2184 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002185 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002186 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002187 return;
2188 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002189
Chris Lattnerd776fb12010-06-28 21:43:59 +00002190 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002191 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002192 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2193 // gcc passes the following as integer:
2194 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2195 // 2 bytes - <2 x char>, <1 x short>
2196 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002197 Current = Integer;
2198
2199 // If this type crosses an eightbyte boundary, it should be
2200 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002201 uint64_t EB_Lo = (OffsetBase) / 64;
2202 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2203 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002204 Hi = Lo;
2205 } else if (Size == 64) {
2206 // gcc passes <1 x double> in memory. :(
2207 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2208 return;
2209
2210 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002211 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002212 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2213 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2214 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002215 Current = Integer;
2216 else
2217 Current = SSE;
2218
2219 // If this type crosses an eightbyte boundary, it should be
2220 // split.
2221 if (OffsetBase && OffsetBase != 64)
2222 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002223 } else if (Size == 128 ||
2224 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002225 // Arguments of 256-bits are split into four eightbyte chunks. The
2226 // least significant one belongs to class SSE and all the others to class
2227 // SSEUP. The original Lo and Hi design considers that types can't be
2228 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2229 // This design isn't correct for 256-bits, but since there're no cases
2230 // where the upper parts would need to be inspected, avoid adding
2231 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002232 //
2233 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2234 // registers if they are "named", i.e. not part of the "..." of a
2235 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002236 //
2237 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2238 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002239 Lo = SSE;
2240 Hi = SSEUp;
2241 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002242 return;
2243 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002244
Chris Lattnerd776fb12010-06-28 21:43:59 +00002245 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002246 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002247
Chris Lattner2b037972010-07-29 02:01:43 +00002248 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002249 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002250 if (Size <= 64)
2251 Current = Integer;
2252 else if (Size <= 128)
2253 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002254 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002255 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002256 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002257 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002258 } else if (ET == getContext().LongDoubleTy) {
2259 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2260 if (LDF == &llvm::APFloat::IEEEquad)
2261 Current = Memory;
2262 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2263 Current = ComplexX87;
2264 else if (LDF == &llvm::APFloat::IEEEdouble)
2265 Lo = Hi = SSE;
2266 else
2267 llvm_unreachable("unexpected long double representation!");
2268 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002269
2270 // If this complex type crosses an eightbyte boundary then it
2271 // should be split.
2272 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002273 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002274 if (Hi == NoClass && EB_Real != EB_Imag)
2275 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002276
Chris Lattnerd776fb12010-06-28 21:43:59 +00002277 return;
2278 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002279
Chris Lattner2b037972010-07-29 02:01:43 +00002280 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002281 // Arrays are treated like structures.
2282
Chris Lattner2b037972010-07-29 02:01:43 +00002283 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002284
2285 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002286 // than four eightbytes, ..., it has class MEMORY.
2287 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002288 return;
2289
2290 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2291 // fields, it has class MEMORY.
2292 //
2293 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002294 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002295 return;
2296
2297 // Otherwise implement simplified merge. We could be smarter about
2298 // this, but it isn't worth it and would be harder to verify.
2299 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002300 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002301 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002302
2303 // The only case a 256-bit wide vector could be used is when the array
2304 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2305 // to work for sizes wider than 128, early check and fallback to memory.
2306 if (Size > 128 && EltSize != 256)
2307 return;
2308
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002309 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2310 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002311 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002312 Lo = merge(Lo, FieldLo);
2313 Hi = merge(Hi, FieldHi);
2314 if (Lo == Memory || Hi == Memory)
2315 break;
2316 }
2317
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002318 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002319 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002320 return;
2321 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002322
Chris Lattnerd776fb12010-06-28 21:43:59 +00002323 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002324 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002325
2326 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002327 // than four eightbytes, ..., it has class MEMORY.
2328 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002329 return;
2330
Anders Carlsson20759ad2009-09-16 15:53:40 +00002331 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2332 // copy constructor or a non-trivial destructor, it is passed by invisible
2333 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002334 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002335 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002336
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002337 const RecordDecl *RD = RT->getDecl();
2338
2339 // Assume variable sized types are passed in memory.
2340 if (RD->hasFlexibleArrayMember())
2341 return;
2342
Chris Lattner2b037972010-07-29 02:01:43 +00002343 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002344
2345 // Reset Lo class, this will be recomputed.
2346 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002347
2348 // If this is a C++ record, classify the bases first.
2349 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002350 for (const auto &I : CXXRD->bases()) {
2351 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002352 "Unexpected base class!");
2353 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002354 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002355
2356 // Classify this field.
2357 //
2358 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2359 // single eightbyte, each is classified separately. Each eightbyte gets
2360 // initialized to class NO_CLASS.
2361 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002362 uint64_t Offset =
2363 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002364 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002365 Lo = merge(Lo, FieldLo);
2366 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002367 if (Lo == Memory || Hi == Memory) {
2368 postMerge(Size, Lo, Hi);
2369 return;
2370 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002371 }
2372 }
2373
2374 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002375 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002376 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002377 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002378 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2379 bool BitField = i->isBitField();
2380
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002381 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2382 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002383 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002384 // The only case a 256-bit wide vector could be used is when the struct
2385 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2386 // to work for sizes wider than 128, early check and fallback to memory.
2387 //
2388 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2389 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002390 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002391 return;
2392 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002393 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002394 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002395 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002396 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002397 return;
2398 }
2399
2400 // Classify this field.
2401 //
2402 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2403 // exceeds a single eightbyte, each is classified
2404 // separately. Each eightbyte gets initialized to class
2405 // NO_CLASS.
2406 Class FieldLo, FieldHi;
2407
2408 // Bit-fields require special handling, they do not force the
2409 // structure to be passed in memory even if unaligned, and
2410 // therefore they can straddle an eightbyte.
2411 if (BitField) {
2412 // Ignore padding bit-fields.
2413 if (i->isUnnamedBitfield())
2414 continue;
2415
2416 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002417 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002418
2419 uint64_t EB_Lo = Offset / 64;
2420 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002421
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002422 if (EB_Lo) {
2423 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2424 FieldLo = NoClass;
2425 FieldHi = Integer;
2426 } else {
2427 FieldLo = Integer;
2428 FieldHi = EB_Hi ? Integer : NoClass;
2429 }
2430 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002431 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002432 Lo = merge(Lo, FieldLo);
2433 Hi = merge(Hi, FieldHi);
2434 if (Lo == Memory || Hi == Memory)
2435 break;
2436 }
2437
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002438 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002439 }
2440}
2441
Chris Lattner22a931e2010-06-29 06:01:59 +00002442ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002443 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2444 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002445 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002446 // Treat an enum type as its underlying type.
2447 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2448 Ty = EnumTy->getDecl()->getIntegerType();
2449
2450 return (Ty->isPromotableIntegerType() ?
2451 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2452 }
2453
John McCall7f416cc2015-09-08 08:05:57 +00002454 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002455}
2456
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002457bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2458 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2459 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002460 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002461 if (Size <= 64 || Size > LargestVector)
2462 return true;
2463 }
2464
2465 return false;
2466}
2467
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002468ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2469 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002470 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2471 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002472 //
2473 // This assumption is optimistic, as there could be free registers available
2474 // when we need to pass this argument in memory, and LLVM could try to pass
2475 // the argument in the free register. This does not seem to happen currently,
2476 // but this code would be much safer if we could mark the argument with
2477 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002478 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002479 // Treat an enum type as its underlying type.
2480 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2481 Ty = EnumTy->getDecl()->getIntegerType();
2482
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002483 return (Ty->isPromotableIntegerType() ?
2484 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002485 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002486
Mark Lacey3825e832013-10-06 01:33:34 +00002487 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002488 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002489
Chris Lattner44c2b902011-05-22 23:21:23 +00002490 // Compute the byval alignment. We specify the alignment of the byval in all
2491 // cases so that the mid-level optimizer knows the alignment of the byval.
2492 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002493
2494 // Attempt to avoid passing indirect results using byval when possible. This
2495 // is important for good codegen.
2496 //
2497 // We do this by coercing the value into a scalar type which the backend can
2498 // handle naturally (i.e., without using byval).
2499 //
2500 // For simplicity, we currently only do this when we have exhausted all of the
2501 // free integer registers. Doing this when there are free integer registers
2502 // would require more care, as we would have to ensure that the coerced value
2503 // did not claim the unused register. That would require either reording the
2504 // arguments to the function (so that any subsequent inreg values came first),
2505 // or only doing this optimization when there were no following arguments that
2506 // might be inreg.
2507 //
2508 // We currently expect it to be rare (particularly in well written code) for
2509 // arguments to be passed on the stack when there are still free integer
2510 // registers available (this would typically imply large structs being passed
2511 // by value), so this seems like a fair tradeoff for now.
2512 //
2513 // We can revisit this if the backend grows support for 'onstack' parameter
2514 // attributes. See PR12193.
2515 if (freeIntRegs == 0) {
2516 uint64_t Size = getContext().getTypeSize(Ty);
2517
2518 // If this type fits in an eightbyte, coerce it into the matching integral
2519 // type, which will end up on the stack (with alignment 8).
2520 if (Align == 8 && Size <= 64)
2521 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2522 Size));
2523 }
2524
John McCall7f416cc2015-09-08 08:05:57 +00002525 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002526}
2527
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002528/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2529/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002530llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002531 // Wrapper structs/arrays that only contain vectors are passed just like
2532 // vectors; strip them off if present.
2533 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2534 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002535
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002536 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002537 if (isa<llvm::VectorType>(IRType) ||
2538 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002539 return IRType;
2540
2541 // We couldn't find the preferred IR vector type for 'Ty'.
2542 uint64_t Size = getContext().getTypeSize(Ty);
2543 assert((Size == 128 || Size == 256) && "Invalid type found!");
2544
2545 // Return a LLVM IR vector type based on the size of 'Ty'.
2546 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2547 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002548}
2549
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002550/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2551/// is known to either be off the end of the specified type or being in
2552/// alignment padding. The user type specified is known to be at most 128 bits
2553/// in size, and have passed through X86_64ABIInfo::classify with a successful
2554/// classification that put one of the two halves in the INTEGER class.
2555///
2556/// It is conservatively correct to return false.
2557static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2558 unsigned EndBit, ASTContext &Context) {
2559 // If the bytes being queried are off the end of the type, there is no user
2560 // data hiding here. This handles analysis of builtins, vectors and other
2561 // types that don't contain interesting padding.
2562 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2563 if (TySize <= StartBit)
2564 return true;
2565
Chris Lattner98076a22010-07-29 07:43:55 +00002566 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2567 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2568 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2569
2570 // Check each element to see if the element overlaps with the queried range.
2571 for (unsigned i = 0; i != NumElts; ++i) {
2572 // If the element is after the span we care about, then we're done..
2573 unsigned EltOffset = i*EltSize;
2574 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002575
Chris Lattner98076a22010-07-29 07:43:55 +00002576 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2577 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2578 EndBit-EltOffset, Context))
2579 return false;
2580 }
2581 // If it overlaps no elements, then it is safe to process as padding.
2582 return true;
2583 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002584
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002585 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2586 const RecordDecl *RD = RT->getDecl();
2587 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002588
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002589 // If this is a C++ record, check the bases first.
2590 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002591 for (const auto &I : CXXRD->bases()) {
2592 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002593 "Unexpected base class!");
2594 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002595 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002596
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002597 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002598 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002599 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002600
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002601 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002602 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002603 EndBit-BaseOffset, Context))
2604 return false;
2605 }
2606 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002607
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002608 // Verify that no field has data that overlaps the region of interest. Yes
2609 // this could be sped up a lot by being smarter about queried fields,
2610 // however we're only looking at structs up to 16 bytes, so we don't care
2611 // much.
2612 unsigned idx = 0;
2613 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2614 i != e; ++i, ++idx) {
2615 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002616
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002617 // If we found a field after the region we care about, then we're done.
2618 if (FieldOffset >= EndBit) break;
2619
2620 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2621 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2622 Context))
2623 return false;
2624 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002625
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002626 // If nothing in this record overlapped the area of interest, then we're
2627 // clean.
2628 return true;
2629 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002630
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002631 return false;
2632}
2633
Chris Lattnere556a712010-07-29 18:39:32 +00002634/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2635/// float member at the specified offset. For example, {int,{float}} has a
2636/// float at offset 4. It is conservatively correct for this routine to return
2637/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002638static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002639 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002640 // Base case if we find a float.
2641 if (IROffset == 0 && IRType->isFloatTy())
2642 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002643
Chris Lattnere556a712010-07-29 18:39:32 +00002644 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002645 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002646 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2647 unsigned Elt = SL->getElementContainingOffset(IROffset);
2648 IROffset -= SL->getElementOffset(Elt);
2649 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2650 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002651
Chris Lattnere556a712010-07-29 18:39:32 +00002652 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002653 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2654 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002655 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2656 IROffset -= IROffset/EltSize*EltSize;
2657 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2658 }
2659
2660 return false;
2661}
2662
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002663
2664/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2665/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002666llvm::Type *X86_64ABIInfo::
2667GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002668 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002669 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002670 // pass as float if the last 4 bytes is just padding. This happens for
2671 // structs that contain 3 floats.
2672 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2673 SourceOffset*8+64, getContext()))
2674 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002675
Chris Lattnere556a712010-07-29 18:39:32 +00002676 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2677 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2678 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002679 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2680 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002681 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002682
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002683 return llvm::Type::getDoubleTy(getVMContext());
2684}
2685
2686
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002687/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2688/// an 8-byte GPR. This means that we either have a scalar or we are talking
2689/// about the high or low part of an up-to-16-byte struct. This routine picks
2690/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002691/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2692/// etc).
2693///
2694/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2695/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2696/// the 8-byte value references. PrefType may be null.
2697///
Alp Toker9907f082014-07-09 14:06:35 +00002698/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002699/// an offset into this that we're processing (which is always either 0 or 8).
2700///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002701llvm::Type *X86_64ABIInfo::
2702GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002703 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002704 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2705 // returning an 8-byte unit starting with it. See if we can safely use it.
2706 if (IROffset == 0) {
2707 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002708 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2709 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002710 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002711
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002712 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2713 // goodness in the source type is just tail padding. This is allowed to
2714 // kick in for struct {double,int} on the int, but not on
2715 // struct{double,int,int} because we wouldn't return the second int. We
2716 // have to do this analysis on the source type because we can't depend on
2717 // unions being lowered a specific way etc.
2718 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002719 IRType->isIntegerTy(32) ||
2720 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2721 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2722 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002723
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002724 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2725 SourceOffset*8+64, getContext()))
2726 return IRType;
2727 }
2728 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002729
Chris Lattner2192fe52011-07-18 04:24:23 +00002730 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002731 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002732 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002733 if (IROffset < SL->getSizeInBytes()) {
2734 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2735 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002736
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002737 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2738 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002739 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002740 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002741
Chris Lattner2192fe52011-07-18 04:24:23 +00002742 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002743 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002744 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002745 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002746 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2747 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002748 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002749
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002750 // Okay, we don't have any better idea of what to pass, so we pass this in an
2751 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002752 unsigned TySizeInBytes =
2753 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002754
Chris Lattner3f763422010-07-29 17:34:39 +00002755 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002756
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002757 // It is always safe to classify this as an integer type up to i64 that
2758 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002759 return llvm::IntegerType::get(getVMContext(),
2760 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002761}
2762
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002763
2764/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2765/// be used as elements of a two register pair to pass or return, return a
2766/// first class aggregate to represent them. For example, if the low part of
2767/// a by-value argument should be passed as i32* and the high part as float,
2768/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002769static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002770GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002771 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002772 // In order to correctly satisfy the ABI, we need to the high part to start
2773 // at offset 8. If the high and low parts we inferred are both 4-byte types
2774 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2775 // the second element at offset 8. Check for this:
2776 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2777 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002778 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002779 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002780
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002781 // To handle this, we have to increase the size of the low part so that the
2782 // second element will start at an 8 byte offset. We can't increase the size
2783 // of the second element because it might make us access off the end of the
2784 // struct.
2785 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002786 // There are usually two sorts of types the ABI generation code can produce
2787 // for the low part of a pair that aren't 8 bytes in size: float or
2788 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2789 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002790 // Promote these to a larger type.
2791 if (Lo->isFloatTy())
2792 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2793 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002794 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2795 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002796 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2797 }
2798 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002799
Reid Kleckneree7cf842014-12-01 22:02:27 +00002800 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002801
2802
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002803 // Verify that the second element is at an 8-byte offset.
2804 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2805 "Invalid x86-64 argument pair!");
2806 return Result;
2807}
2808
Chris Lattner31faff52010-07-28 23:06:14 +00002809ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002810classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002811 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2812 // classification algorithm.
2813 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002814 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002815
2816 // Check some invariants.
2817 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002818 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2819
Craig Topper8a13c412014-05-21 05:09:00 +00002820 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002821 switch (Lo) {
2822 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002823 if (Hi == NoClass)
2824 return ABIArgInfo::getIgnore();
2825 // If the low part is just padding, it takes no register, leave ResType
2826 // null.
2827 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2828 "Unknown missing lo part");
2829 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002830
2831 case SSEUp:
2832 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002833 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002834
2835 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2836 // hidden argument.
2837 case Memory:
2838 return getIndirectReturnResult(RetTy);
2839
2840 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2841 // available register of the sequence %rax, %rdx is used.
2842 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002843 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002844
Chris Lattner1f3a0632010-07-29 21:42:50 +00002845 // If we have a sign or zero extended integer, make sure to return Extend
2846 // so that the parameter gets the right LLVM IR attributes.
2847 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2848 // Treat an enum type as its underlying type.
2849 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2850 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002851
Chris Lattner1f3a0632010-07-29 21:42:50 +00002852 if (RetTy->isIntegralOrEnumerationType() &&
2853 RetTy->isPromotableIntegerType())
2854 return ABIArgInfo::getExtend();
2855 }
Chris Lattner31faff52010-07-28 23:06:14 +00002856 break;
2857
2858 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2859 // available SSE register of the sequence %xmm0, %xmm1 is used.
2860 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002861 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002862 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002863
2864 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2865 // returned on the X87 stack in %st0 as 80-bit x87 number.
2866 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002867 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002868 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002869
2870 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2871 // part of the value is returned in %st0 and the imaginary part in
2872 // %st1.
2873 case ComplexX87:
2874 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002875 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002876 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002877 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002878 break;
2879 }
2880
Craig Topper8a13c412014-05-21 05:09:00 +00002881 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002882 switch (Hi) {
2883 // Memory was handled previously and X87 should
2884 // never occur as a hi class.
2885 case Memory:
2886 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002887 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002888
2889 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002890 case NoClass:
2891 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002892
Chris Lattner52b3c132010-09-01 00:20:33 +00002893 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002894 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002895 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2896 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002897 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002898 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002899 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002900 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2901 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002902 break;
2903
2904 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002905 // is passed in the next available eightbyte chunk if the last used
2906 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002907 //
Chris Lattner57540c52011-04-15 05:22:18 +00002908 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002909 case SSEUp:
2910 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002911 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002912 break;
2913
2914 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2915 // returned together with the previous X87 value in %st0.
2916 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002917 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002918 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002919 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002920 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002921 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002922 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002923 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2924 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002925 }
Chris Lattner31faff52010-07-28 23:06:14 +00002926 break;
2927 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002928
Chris Lattner52b3c132010-09-01 00:20:33 +00002929 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002930 // known to pass in the high eightbyte of the result. We do this by forming a
2931 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002932 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002933 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002934
Chris Lattner1f3a0632010-07-29 21:42:50 +00002935 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002936}
2937
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002938ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002939 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2940 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002941 const
2942{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002943 Ty = useFirstFieldIfTransparentUnion(Ty);
2944
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002945 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002946 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002947
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002948 // Check some invariants.
2949 // FIXME: Enforce these by construction.
2950 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002951 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2952
2953 neededInt = 0;
2954 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002955 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002956 switch (Lo) {
2957 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002958 if (Hi == NoClass)
2959 return ABIArgInfo::getIgnore();
2960 // If the low part is just padding, it takes no register, leave ResType
2961 // null.
2962 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2963 "Unknown missing lo part");
2964 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002965
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002966 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2967 // on the stack.
2968 case Memory:
2969
2970 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2971 // COMPLEX_X87, it is passed in memory.
2972 case X87:
2973 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002974 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002975 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002976 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002977
2978 case SSEUp:
2979 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002980 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002981
2982 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2983 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2984 // and %r9 is used.
2985 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002986 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002987
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002988 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002989 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002990
2991 // If we have a sign or zero extended integer, make sure to return Extend
2992 // so that the parameter gets the right LLVM IR attributes.
2993 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2994 // Treat an enum type as its underlying type.
2995 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2996 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002997
Chris Lattner1f3a0632010-07-29 21:42:50 +00002998 if (Ty->isIntegralOrEnumerationType() &&
2999 Ty->isPromotableIntegerType())
3000 return ABIArgInfo::getExtend();
3001 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003002
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003003 break;
3004
3005 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3006 // available SSE register is used, the registers are taken in the
3007 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003008 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003009 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003010 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003011 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003012 break;
3013 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003014 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003015
Craig Topper8a13c412014-05-21 05:09:00 +00003016 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003017 switch (Hi) {
3018 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003019 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003020 // which is passed in memory.
3021 case Memory:
3022 case X87:
3023 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003024 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003025
3026 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003027
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003028 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003029 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003030 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003031 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003032
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003033 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3034 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003035 break;
3036
3037 // X87Up generally doesn't occur here (long double is passed in
3038 // memory), except in situations involving unions.
3039 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003040 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003041 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003042
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003043 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3044 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003045
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003046 ++neededSSE;
3047 break;
3048
3049 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3050 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003051 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003052 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003053 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003054 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003055 break;
3056 }
3057
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003058 // If a high part was specified, merge it together with the low part. It is
3059 // known to pass in the high eightbyte of the result. We do this by forming a
3060 // first class struct aggregate with the high and low part: {low, high}
3061 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003062 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003063
Chris Lattner1f3a0632010-07-29 21:42:50 +00003064 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003065}
3066
Chris Lattner22326a12010-07-29 02:31:05 +00003067void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003068
Reid Kleckner40ca9132014-05-13 22:05:45 +00003069 if (!getCXXABI().classifyReturnType(FI))
3070 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003071
3072 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003073 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003074
3075 // If the return value is indirect, then the hidden argument is consuming one
3076 // integer register.
3077 if (FI.getReturnInfo().isIndirect())
3078 --freeIntRegs;
3079
Peter Collingbournef7706832014-12-12 23:41:25 +00003080 // The chain argument effectively gives us another free register.
3081 if (FI.isChainCall())
3082 ++freeIntRegs;
3083
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003084 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003085 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3086 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003087 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003088 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003089 it != ie; ++it, ++ArgNo) {
3090 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003091
Bill Wendling9987c0e2010-10-18 23:51:38 +00003092 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003093 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003094 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003095
3096 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3097 // eightbyte of an argument, the whole argument is passed on the
3098 // stack. If registers have already been assigned for some
3099 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003100 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003101 freeIntRegs -= neededInt;
3102 freeSSERegs -= neededSSE;
3103 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003104 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003105 }
3106 }
3107}
3108
John McCall7f416cc2015-09-08 08:05:57 +00003109static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3110 Address VAListAddr, QualType Ty) {
3111 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3112 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003113 llvm::Value *overflow_arg_area =
3114 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3115
3116 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3117 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003118 // It isn't stated explicitly in the standard, but in practice we use
3119 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003120 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3121 if (Align > CharUnits::fromQuantity(8)) {
3122 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3123 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003124 }
3125
3126 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003127 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003128 llvm::Value *Res =
3129 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003130 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131
3132 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3133 // l->overflow_arg_area + sizeof(type).
3134 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3135 // an 8 byte boundary.
3136
3137 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003138 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003139 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003140 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3141 "overflow_arg_area.next");
3142 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3143
3144 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003145 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003146}
3147
John McCall7f416cc2015-09-08 08:05:57 +00003148Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3149 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003150 // Assume that va_list type is correct; should be pointer to LLVM type:
3151 // struct {
3152 // i32 gp_offset;
3153 // i32 fp_offset;
3154 // i8* overflow_arg_area;
3155 // i8* reg_save_area;
3156 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003157 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003158
John McCall7f416cc2015-09-08 08:05:57 +00003159 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003160 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003161 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003162
3163 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3164 // in the registers. If not go to step 7.
3165 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003166 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003167
3168 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3169 // general purpose registers needed to pass type and num_fp to hold
3170 // the number of floating point registers needed.
3171
3172 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3173 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3174 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3175 //
3176 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3177 // register save space).
3178
Craig Topper8a13c412014-05-21 05:09:00 +00003179 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003180 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3181 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003182 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003183 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003184 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3185 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003186 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003187 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3188 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003189 }
3190
3191 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003192 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003193 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3194 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003195 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3196 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003197 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3198 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003199 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3200 }
3201
3202 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3203 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3204 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3205 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3206
3207 // Emit code to load the value if it was passed in registers.
3208
3209 CGF.EmitBlock(InRegBlock);
3210
3211 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3212 // an offset of l->gp_offset and/or l->fp_offset. This may require
3213 // copying to a temporary location in case the parameter is passed
3214 // in different register classes or requires an alignment greater
3215 // than 8 for general purpose registers and 16 for XMM registers.
3216 //
3217 // FIXME: This really results in shameful code when we end up needing to
3218 // collect arguments from different places; often what should result in a
3219 // simple assembling of a structure from scattered addresses has many more
3220 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003221 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003222 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3223 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3224 "reg_save_area");
3225
3226 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003227 if (neededInt && neededSSE) {
3228 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003229 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003230 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003231 Address Tmp = CGF.CreateMemTemp(Ty);
3232 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003233 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003234 llvm::Type *TyLo = ST->getElementType(0);
3235 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003236 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003237 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003238 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3239 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003240 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3241 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003242 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3243 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003244
John McCall7f416cc2015-09-08 08:05:57 +00003245 // Copy the first element.
3246 llvm::Value *V =
3247 CGF.Builder.CreateDefaultAlignedLoad(
3248 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3249 CGF.Builder.CreateStore(V,
3250 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3251
3252 // Copy the second element.
3253 V = CGF.Builder.CreateDefaultAlignedLoad(
3254 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3255 CharUnits Offset = CharUnits::fromQuantity(
3256 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3257 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3258
3259 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003260 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003261 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3262 CharUnits::fromQuantity(8));
3263 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003264
3265 // Copy to a temporary if necessary to ensure the appropriate alignment.
3266 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003267 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003268 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003269 CharUnits TyAlign = SizeAlign.second;
3270
3271 // Copy into a temporary if the type is more aligned than the
3272 // register save area.
3273 if (TyAlign.getQuantity() > 8) {
3274 Address Tmp = CGF.CreateMemTemp(Ty);
3275 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003276 RegAddr = Tmp;
3277 }
John McCall7f416cc2015-09-08 08:05:57 +00003278
Chris Lattner0cf24192010-06-28 20:05:43 +00003279 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003280 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3281 CharUnits::fromQuantity(16));
3282 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003283 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003284 assert(neededSSE == 2 && "Invalid number of needed registers!");
3285 // SSE registers are spaced 16 bytes apart in the register save
3286 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003287 // The ABI isn't explicit about this, but it seems reasonable
3288 // to assume that the slots are 16-byte aligned, since the stack is
3289 // naturally 16-byte aligned and the prologue is expected to store
3290 // all the SSE registers to the RSA.
3291 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3292 CharUnits::fromQuantity(16));
3293 Address RegAddrHi =
3294 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3295 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003296 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003297 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003298 llvm::Value *V;
3299 Address Tmp = CGF.CreateMemTemp(Ty);
3300 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3301 V = CGF.Builder.CreateLoad(
3302 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3303 CGF.Builder.CreateStore(V,
3304 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3305 V = CGF.Builder.CreateLoad(
3306 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3307 CGF.Builder.CreateStore(V,
3308 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3309
3310 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003311 }
3312
3313 // AMD64-ABI 3.5.7p5: Step 5. Set:
3314 // l->gp_offset = l->gp_offset + num_gp * 8
3315 // l->fp_offset = l->fp_offset + num_fp * 16.
3316 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003317 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003318 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3319 gp_offset_p);
3320 }
3321 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003322 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003323 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3324 fp_offset_p);
3325 }
3326 CGF.EmitBranch(ContBlock);
3327
3328 // Emit code to load the value if it was passed in memory.
3329
3330 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003331 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003332
3333 // Return the appropriate result.
3334
3335 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003336 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3337 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003338 return ResAddr;
3339}
3340
Charles Davisc7d5c942015-09-17 20:55:33 +00003341Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3342 QualType Ty) const {
3343 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3344 CGF.getContext().getTypeInfoInChars(Ty),
3345 CharUnits::fromQuantity(8),
3346 /*allowHigherAlign*/ false);
3347}
3348
Reid Kleckner80944df2014-10-31 22:00:51 +00003349ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3350 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003351
3352 if (Ty->isVoidType())
3353 return ABIArgInfo::getIgnore();
3354
3355 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3356 Ty = EnumTy->getDecl()->getIntegerType();
3357
Reid Kleckner80944df2014-10-31 22:00:51 +00003358 TypeInfo Info = getContext().getTypeInfo(Ty);
3359 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003360 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003361
Reid Kleckner9005f412014-05-02 00:51:20 +00003362 const RecordType *RT = Ty->getAs<RecordType>();
3363 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003364 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003365 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003366 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003367 }
3368
3369 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003370 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003371
Reid Kleckner9005f412014-05-02 00:51:20 +00003372 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003373
Reid Kleckner80944df2014-10-31 22:00:51 +00003374 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3375 // other targets.
3376 const Type *Base = nullptr;
3377 uint64_t NumElts = 0;
3378 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3379 if (FreeSSERegs >= NumElts) {
3380 FreeSSERegs -= NumElts;
3381 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3382 return ABIArgInfo::getDirect();
3383 return ABIArgInfo::getExpand();
3384 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003385 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003386 }
3387
3388
Reid Klecknerec87fec2014-05-02 01:17:12 +00003389 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003390 // If the member pointer is represented by an LLVM int or ptr, pass it
3391 // directly.
3392 llvm::Type *LLTy = CGT.ConvertType(Ty);
3393 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3394 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003395 }
3396
Michael Kuperstein4f818702015-02-24 09:35:58 +00003397 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003398 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3399 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003400 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003401 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003402
Reid Kleckner9005f412014-05-02 00:51:20 +00003403 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003404 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003405 }
3406
Julien Lerouge10dcff82014-08-27 00:36:55 +00003407 // Bool type is always extended to the ABI, other builtin types are not
3408 // extended.
3409 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3410 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003411 return ABIArgInfo::getExtend();
3412
Reid Kleckner11a17192015-10-28 22:29:52 +00003413 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3414 // passes them indirectly through memory.
3415 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3416 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3417 if (LDF == &llvm::APFloat::x87DoubleExtended)
3418 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3419 }
3420
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003421 return ABIArgInfo::getDirect();
3422}
3423
3424void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003425 bool IsVectorCall =
3426 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003427
Reid Kleckner80944df2014-10-31 22:00:51 +00003428 // We can use up to 4 SSE return registers with vectorcall.
3429 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3430 if (!getCXXABI().classifyReturnType(FI))
3431 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3432
3433 // We can use up to 6 SSE register parameters with vectorcall.
3434 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003435 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003436 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003437}
3438
John McCall7f416cc2015-09-08 08:05:57 +00003439Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3440 QualType Ty) const {
3441 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3442 CGF.getContext().getTypeInfoInChars(Ty),
3443 CharUnits::fromQuantity(8),
3444 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003445}
Chris Lattner0cf24192010-06-28 20:05:43 +00003446
John McCallea8d8bb2010-03-11 00:10:12 +00003447// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003448namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003449/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3450class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003451bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003452public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003453 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3454 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003455
John McCall7f416cc2015-09-08 08:05:57 +00003456 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3457 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003458};
3459
3460class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3461public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003462 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3463 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003464
Craig Topper4f12f102014-03-12 06:41:41 +00003465 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003466 // This is recovered from gcc output.
3467 return 1; // r1 is the dedicated stack pointer
3468 }
3469
3470 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003471 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003472};
3473
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003474}
John McCallea8d8bb2010-03-11 00:10:12 +00003475
John McCall7f416cc2015-09-08 08:05:57 +00003476Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3477 QualType Ty) const {
Roman Divacky8a12d842014-11-03 18:32:54 +00003478 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3479 // TODO: Implement this. For now ignore.
3480 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003481 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003482 }
3483
John McCall7f416cc2015-09-08 08:05:57 +00003484 // struct __va_list_tag {
3485 // unsigned char gpr;
3486 // unsigned char fpr;
3487 // unsigned short reserved;
3488 // void *overflow_arg_area;
3489 // void *reg_save_area;
3490 // };
3491
Roman Divacky8a12d842014-11-03 18:32:54 +00003492 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003493 bool isInt =
3494 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003495 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003496
3497 // All aggregates are passed indirectly? That doesn't seem consistent
3498 // with the argument-lowering code.
3499 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003500
3501 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003502
3503 // The calling convention either uses 1-2 GPRs or 1 FPR.
3504 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003505 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003506 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3507 } else {
3508 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003509 }
John McCall7f416cc2015-09-08 08:05:57 +00003510
3511 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3512
3513 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003514 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003515 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3516 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3517 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003518
Eric Christopher7565e0d2015-05-29 23:09:49 +00003519 llvm::Value *CC =
John McCall7f416cc2015-09-08 08:05:57 +00003520 Builder.CreateICmpULT(NumRegs, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003521
3522 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3523 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3524 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3525
3526 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3527
John McCall7f416cc2015-09-08 08:05:57 +00003528 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3529 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003530
John McCall7f416cc2015-09-08 08:05:57 +00003531 // Case 1: consume registers.
3532 Address RegAddr = Address::invalid();
3533 {
3534 CGF.EmitBlock(UsingRegs);
3535
3536 Address RegSaveAreaPtr =
3537 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3538 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3539 CharUnits::fromQuantity(8));
3540 assert(RegAddr.getElementType() == CGF.Int8Ty);
3541
3542 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003543 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003544 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3545 CharUnits::fromQuantity(32));
3546 }
3547
3548 // Get the address of the saved value by scaling the number of
3549 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003550 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003551 llvm::Value *RegOffset =
3552 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3553 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3554 RegAddr.getPointer(), RegOffset),
3555 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3556 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3557
3558 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003559 NumRegs =
3560 Builder.CreateAdd(NumRegs,
3561 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003562 Builder.CreateStore(NumRegs, NumRegsAddr);
3563
3564 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003565 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003566
John McCall7f416cc2015-09-08 08:05:57 +00003567 // Case 2: consume space in the overflow area.
3568 Address MemAddr = Address::invalid();
3569 {
3570 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003571
John McCall7f416cc2015-09-08 08:05:57 +00003572 // Everything in the overflow area is rounded up to a size of at least 4.
3573 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3574
3575 CharUnits Size;
3576 if (!isIndirect) {
3577 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003578 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003579 } else {
3580 Size = CGF.getPointerSize();
3581 }
3582
3583 Address OverflowAreaAddr =
3584 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003585 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003586 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003587 // Round up address of argument to alignment
3588 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3589 if (Align > OverflowAreaAlign) {
3590 llvm::Value *Ptr = OverflowArea.getPointer();
3591 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3592 Align);
3593 }
3594
John McCall7f416cc2015-09-08 08:05:57 +00003595 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3596
3597 // Increase the overflow area.
3598 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3599 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3600 CGF.EmitBranch(Cont);
3601 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003602
3603 CGF.EmitBlock(Cont);
3604
John McCall7f416cc2015-09-08 08:05:57 +00003605 // Merge the cases with a phi.
3606 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3607 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003608
John McCall7f416cc2015-09-08 08:05:57 +00003609 // Load the pointer if the argument was passed indirectly.
3610 if (isIndirect) {
3611 Result = Address(Builder.CreateLoad(Result, "aggr"),
3612 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003613 }
3614
3615 return Result;
3616}
3617
John McCallea8d8bb2010-03-11 00:10:12 +00003618bool
3619PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3620 llvm::Value *Address) const {
3621 // This is calculated from the LLVM and GCC tables and verified
3622 // against gcc output. AFAIK all ABIs use the same encoding.
3623
3624 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003625
Chris Lattnerece04092012-02-07 00:39:47 +00003626 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003627 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3628 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3629 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3630
3631 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003632 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003633
3634 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003635 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003636
3637 // 64-76 are various 4-byte special-purpose registers:
3638 // 64: mq
3639 // 65: lr
3640 // 66: ctr
3641 // 67: ap
3642 // 68-75 cr0-7
3643 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003644 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003645
3646 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003647 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003648
3649 // 109: vrsave
3650 // 110: vscr
3651 // 111: spe_acc
3652 // 112: spefscr
3653 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003654 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003655
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003656 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003657}
3658
Roman Divackyd966e722012-05-09 18:22:46 +00003659// PowerPC-64
3660
3661namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003662/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3663class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003664public:
3665 enum ABIKind {
3666 ELFv1 = 0,
3667 ELFv2
3668 };
3669
3670private:
3671 static const unsigned GPRBits = 64;
3672 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003673 bool HasQPX;
3674
3675 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3676 // will be passed in a QPX register.
3677 bool IsQPXVectorTy(const Type *Ty) const {
3678 if (!HasQPX)
3679 return false;
3680
3681 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3682 unsigned NumElements = VT->getNumElements();
3683 if (NumElements == 1)
3684 return false;
3685
3686 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3687 if (getContext().getTypeSize(Ty) <= 256)
3688 return true;
3689 } else if (VT->getElementType()->
3690 isSpecificBuiltinType(BuiltinType::Float)) {
3691 if (getContext().getTypeSize(Ty) <= 128)
3692 return true;
3693 }
3694 }
3695
3696 return false;
3697 }
3698
3699 bool IsQPXVectorTy(QualType Ty) const {
3700 return IsQPXVectorTy(Ty.getTypePtr());
3701 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003702
3703public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003704 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3705 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003706
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003707 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003708 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003709
3710 ABIArgInfo classifyReturnType(QualType RetTy) const;
3711 ABIArgInfo classifyArgumentType(QualType Ty) const;
3712
Reid Klecknere9f6a712014-10-31 17:10:41 +00003713 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3714 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3715 uint64_t Members) const override;
3716
Bill Schmidt84d37792012-10-12 19:26:17 +00003717 // TODO: We can add more logic to computeInfo to improve performance.
3718 // Example: For aggregate arguments that fit in a register, we could
3719 // use getDirectInReg (as is done below for structs containing a single
3720 // floating-point value) to avoid pushing them to memory on function
3721 // entry. This would require changing the logic in PPCISelLowering
3722 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003723 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003724 if (!getCXXABI().classifyReturnType(FI))
3725 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003726 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003727 // We rely on the default argument classification for the most part.
3728 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003729 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003730 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003731 if (T) {
3732 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003733 if (IsQPXVectorTy(T) ||
3734 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003735 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003736 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003737 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003738 continue;
3739 }
3740 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003741 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003742 }
3743 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003744
John McCall7f416cc2015-09-08 08:05:57 +00003745 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3746 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003747};
3748
3749class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003750
Bill Schmidt25cb3492012-10-03 19:18:57 +00003751public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003752 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003753 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003754 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003755
Craig Topper4f12f102014-03-12 06:41:41 +00003756 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003757 // This is recovered from gcc output.
3758 return 1; // r1 is the dedicated stack pointer
3759 }
3760
3761 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003762 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003763};
3764
Roman Divackyd966e722012-05-09 18:22:46 +00003765class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3766public:
3767 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3768
Craig Topper4f12f102014-03-12 06:41:41 +00003769 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003770 // This is recovered from gcc output.
3771 return 1; // r1 is the dedicated stack pointer
3772 }
3773
3774 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003775 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003776};
3777
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003778}
Roman Divackyd966e722012-05-09 18:22:46 +00003779
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003780// Return true if the ABI requires Ty to be passed sign- or zero-
3781// extended to 64 bits.
3782bool
3783PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3784 // Treat an enum type as its underlying type.
3785 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3786 Ty = EnumTy->getDecl()->getIntegerType();
3787
3788 // Promotable integer types are required to be promoted by the ABI.
3789 if (Ty->isPromotableIntegerType())
3790 return true;
3791
3792 // In addition to the usual promotable integer types, we also need to
3793 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3794 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3795 switch (BT->getKind()) {
3796 case BuiltinType::Int:
3797 case BuiltinType::UInt:
3798 return true;
3799 default:
3800 break;
3801 }
3802
3803 return false;
3804}
3805
John McCall7f416cc2015-09-08 08:05:57 +00003806/// isAlignedParamType - Determine whether a type requires 16-byte or
3807/// higher alignment in the parameter area. Always returns at least 8.
3808CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003809 // Complex types are passed just like their elements.
3810 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3811 Ty = CTy->getElementType();
3812
3813 // Only vector types of size 16 bytes need alignment (larger types are
3814 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003815 if (IsQPXVectorTy(Ty)) {
3816 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003817 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003818
John McCall7f416cc2015-09-08 08:05:57 +00003819 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003820 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003821 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003822 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003823
3824 // For single-element float/vector structs, we consider the whole type
3825 // to have the same alignment requirements as its single element.
3826 const Type *AlignAsType = nullptr;
3827 const Type *EltType = isSingleElementStruct(Ty, getContext());
3828 if (EltType) {
3829 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003830 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003831 getContext().getTypeSize(EltType) == 128) ||
3832 (BT && BT->isFloatingPoint()))
3833 AlignAsType = EltType;
3834 }
3835
Ulrich Weigandb7122372014-07-21 00:48:09 +00003836 // Likewise for ELFv2 homogeneous aggregates.
3837 const Type *Base = nullptr;
3838 uint64_t Members = 0;
3839 if (!AlignAsType && Kind == ELFv2 &&
3840 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3841 AlignAsType = Base;
3842
Ulrich Weigand581badc2014-07-10 17:20:07 +00003843 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003844 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3845 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003846 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003847
John McCall7f416cc2015-09-08 08:05:57 +00003848 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003849 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003850 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003851 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003852
3853 // Otherwise, we only need alignment for any aggregate type that
3854 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003855 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3856 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003857 return CharUnits::fromQuantity(32);
3858 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003859 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003860
John McCall7f416cc2015-09-08 08:05:57 +00003861 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003862}
3863
Ulrich Weigandb7122372014-07-21 00:48:09 +00003864/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3865/// aggregate. Base is set to the base element type, and Members is set
3866/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003867bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3868 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003869 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3870 uint64_t NElements = AT->getSize().getZExtValue();
3871 if (NElements == 0)
3872 return false;
3873 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3874 return false;
3875 Members *= NElements;
3876 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3877 const RecordDecl *RD = RT->getDecl();
3878 if (RD->hasFlexibleArrayMember())
3879 return false;
3880
3881 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003882
3883 // If this is a C++ record, check the bases first.
3884 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3885 for (const auto &I : CXXRD->bases()) {
3886 // Ignore empty records.
3887 if (isEmptyRecord(getContext(), I.getType(), true))
3888 continue;
3889
3890 uint64_t FldMembers;
3891 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3892 return false;
3893
3894 Members += FldMembers;
3895 }
3896 }
3897
Ulrich Weigandb7122372014-07-21 00:48:09 +00003898 for (const auto *FD : RD->fields()) {
3899 // Ignore (non-zero arrays of) empty records.
3900 QualType FT = FD->getType();
3901 while (const ConstantArrayType *AT =
3902 getContext().getAsConstantArrayType(FT)) {
3903 if (AT->getSize().getZExtValue() == 0)
3904 return false;
3905 FT = AT->getElementType();
3906 }
3907 if (isEmptyRecord(getContext(), FT, true))
3908 continue;
3909
3910 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3911 if (getContext().getLangOpts().CPlusPlus &&
3912 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3913 continue;
3914
3915 uint64_t FldMembers;
3916 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3917 return false;
3918
3919 Members = (RD->isUnion() ?
3920 std::max(Members, FldMembers) : Members + FldMembers);
3921 }
3922
3923 if (!Base)
3924 return false;
3925
3926 // Ensure there is no padding.
3927 if (getContext().getTypeSize(Base) * Members !=
3928 getContext().getTypeSize(Ty))
3929 return false;
3930 } else {
3931 Members = 1;
3932 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3933 Members = 2;
3934 Ty = CT->getElementType();
3935 }
3936
Reid Klecknere9f6a712014-10-31 17:10:41 +00003937 // Most ABIs only support float, double, and some vector type widths.
3938 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003939 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003940
3941 // The base type must be the same for all members. Types that
3942 // agree in both total size and mode (float vs. vector) are
3943 // treated as being equivalent here.
3944 const Type *TyPtr = Ty.getTypePtr();
3945 if (!Base)
3946 Base = TyPtr;
3947
3948 if (Base->isVectorType() != TyPtr->isVectorType() ||
3949 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3950 return false;
3951 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003952 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3953}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003954
Reid Klecknere9f6a712014-10-31 17:10:41 +00003955bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3956 // Homogeneous aggregates for ELFv2 must have base types of float,
3957 // double, long double, or 128-bit vectors.
3958 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3959 if (BT->getKind() == BuiltinType::Float ||
3960 BT->getKind() == BuiltinType::Double ||
3961 BT->getKind() == BuiltinType::LongDouble)
3962 return true;
3963 }
3964 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003965 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003966 return true;
3967 }
3968 return false;
3969}
3970
3971bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3972 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003973 // Vector types require one register, floating point types require one
3974 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003975 uint32_t NumRegs =
3976 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003977
3978 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003979 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003980}
3981
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003982ABIArgInfo
3983PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003984 Ty = useFirstFieldIfTransparentUnion(Ty);
3985
Bill Schmidt90b22c92012-11-27 02:46:43 +00003986 if (Ty->isAnyComplexType())
3987 return ABIArgInfo::getDirect();
3988
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003989 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3990 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003991 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003992 uint64_t Size = getContext().getTypeSize(Ty);
3993 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003994 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003995 else if (Size < 128) {
3996 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3997 return ABIArgInfo::getDirect(CoerceTy);
3998 }
3999 }
4000
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004001 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004002 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004003 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004004
John McCall7f416cc2015-09-08 08:05:57 +00004005 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4006 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004007
4008 // ELFv2 homogeneous aggregates are passed as array types.
4009 const Type *Base = nullptr;
4010 uint64_t Members = 0;
4011 if (Kind == ELFv2 &&
4012 isHomogeneousAggregate(Ty, Base, Members)) {
4013 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4014 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4015 return ABIArgInfo::getDirect(CoerceTy);
4016 }
4017
Ulrich Weigand601957f2014-07-21 00:56:36 +00004018 // If an aggregate may end up fully in registers, we do not
4019 // use the ByVal method, but pass the aggregate as array.
4020 // This is usually beneficial since we avoid forcing the
4021 // back-end to store the argument to memory.
4022 uint64_t Bits = getContext().getTypeSize(Ty);
4023 if (Bits > 0 && Bits <= 8 * GPRBits) {
4024 llvm::Type *CoerceTy;
4025
4026 // Types up to 8 bytes are passed as integer type (which will be
4027 // properly aligned in the argument save area doubleword).
4028 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004029 CoerceTy =
4030 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004031 // Larger types are passed as arrays, with the base type selected
4032 // according to the required alignment in the save area.
4033 else {
4034 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004035 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004036 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4037 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4038 }
4039
4040 return ABIArgInfo::getDirect(CoerceTy);
4041 }
4042
Ulrich Weigandb7122372014-07-21 00:48:09 +00004043 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004044 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4045 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004046 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004047 }
4048
4049 return (isPromotableTypeForABI(Ty) ?
4050 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4051}
4052
4053ABIArgInfo
4054PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4055 if (RetTy->isVoidType())
4056 return ABIArgInfo::getIgnore();
4057
Bill Schmidta3d121c2012-12-17 04:20:17 +00004058 if (RetTy->isAnyComplexType())
4059 return ABIArgInfo::getDirect();
4060
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004061 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4062 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004063 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004064 uint64_t Size = getContext().getTypeSize(RetTy);
4065 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004066 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004067 else if (Size < 128) {
4068 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4069 return ABIArgInfo::getDirect(CoerceTy);
4070 }
4071 }
4072
Ulrich Weigandb7122372014-07-21 00:48:09 +00004073 if (isAggregateTypeForABI(RetTy)) {
4074 // ELFv2 homogeneous aggregates are returned as array types.
4075 const Type *Base = nullptr;
4076 uint64_t Members = 0;
4077 if (Kind == ELFv2 &&
4078 isHomogeneousAggregate(RetTy, Base, Members)) {
4079 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4080 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4081 return ABIArgInfo::getDirect(CoerceTy);
4082 }
4083
4084 // ELFv2 small aggregates are returned in up to two registers.
4085 uint64_t Bits = getContext().getTypeSize(RetTy);
4086 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4087 if (Bits == 0)
4088 return ABIArgInfo::getIgnore();
4089
4090 llvm::Type *CoerceTy;
4091 if (Bits > GPRBits) {
4092 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004093 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004094 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004095 CoerceTy =
4096 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004097 return ABIArgInfo::getDirect(CoerceTy);
4098 }
4099
4100 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004101 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004102 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004103
4104 return (isPromotableTypeForABI(RetTy) ?
4105 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4106}
4107
Bill Schmidt25cb3492012-10-03 19:18:57 +00004108// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004109Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4110 QualType Ty) const {
4111 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4112 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004113
John McCall7f416cc2015-09-08 08:05:57 +00004114 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004115
Bill Schmidt924c4782013-01-14 17:45:36 +00004116 // If we have a complex type and the base type is smaller than 8 bytes,
4117 // the ABI calls for the real and imaginary parts to be right-adjusted
4118 // in separate doublewords. However, Clang expects us to produce a
4119 // pointer to a structure with the two parts packed tightly. So generate
4120 // loads of the real and imaginary parts relative to the va_list pointer,
4121 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004122 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4123 CharUnits EltSize = TypeInfo.first / 2;
4124 if (EltSize < SlotSize) {
4125 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4126 SlotSize * 2, SlotSize,
4127 SlotSize, /*AllowHigher*/ true);
4128
4129 Address RealAddr = Addr;
4130 Address ImagAddr = RealAddr;
4131 if (CGF.CGM.getDataLayout().isBigEndian()) {
4132 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4133 SlotSize - EltSize);
4134 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4135 2 * SlotSize - EltSize);
4136 } else {
4137 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4138 }
4139
4140 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4141 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4142 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4143 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4144 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4145
4146 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4147 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4148 /*init*/ true);
4149 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004150 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004151 }
4152
John McCall7f416cc2015-09-08 08:05:57 +00004153 // Otherwise, just use the general rule.
4154 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4155 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004156}
4157
4158static bool
4159PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4160 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004161 // This is calculated from the LLVM and GCC tables and verified
4162 // against gcc output. AFAIK all ABIs use the same encoding.
4163
4164 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4165
4166 llvm::IntegerType *i8 = CGF.Int8Ty;
4167 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4168 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4169 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4170
4171 // 0-31: r0-31, the 8-byte general-purpose registers
4172 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4173
4174 // 32-63: fp0-31, the 8-byte floating-point registers
4175 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4176
4177 // 64-76 are various 4-byte special-purpose registers:
4178 // 64: mq
4179 // 65: lr
4180 // 66: ctr
4181 // 67: ap
4182 // 68-75 cr0-7
4183 // 76: xer
4184 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4185
4186 // 77-108: v0-31, the 16-byte vector registers
4187 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4188
4189 // 109: vrsave
4190 // 110: vscr
4191 // 111: spe_acc
4192 // 112: spefscr
4193 // 113: sfp
4194 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4195
4196 return false;
4197}
John McCallea8d8bb2010-03-11 00:10:12 +00004198
Bill Schmidt25cb3492012-10-03 19:18:57 +00004199bool
4200PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4201 CodeGen::CodeGenFunction &CGF,
4202 llvm::Value *Address) const {
4203
4204 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4205}
4206
4207bool
4208PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4209 llvm::Value *Address) const {
4210
4211 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4212}
4213
Chris Lattner0cf24192010-06-28 20:05:43 +00004214//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004215// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004216//===----------------------------------------------------------------------===//
4217
4218namespace {
4219
Tim Northover573cbee2014-05-24 12:52:07 +00004220class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004221public:
4222 enum ABIKind {
4223 AAPCS = 0,
4224 DarwinPCS
4225 };
4226
4227private:
4228 ABIKind Kind;
4229
4230public:
Tim Northover573cbee2014-05-24 12:52:07 +00004231 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004232
4233private:
4234 ABIKind getABIKind() const { return Kind; }
4235 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4236
4237 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004238 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004239 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4240 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4241 uint64_t Members) const override;
4242
Tim Northovera2ee4332014-03-29 15:09:45 +00004243 bool isIllegalVectorType(QualType Ty) const;
4244
David Blaikie1cbb9712014-11-14 19:09:44 +00004245 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004246 if (!getCXXABI().classifyReturnType(FI))
4247 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004248
Tim Northoverb047bfa2014-11-27 21:02:49 +00004249 for (auto &it : FI.arguments())
4250 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004251 }
4252
John McCall7f416cc2015-09-08 08:05:57 +00004253 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4254 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004255
John McCall7f416cc2015-09-08 08:05:57 +00004256 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4257 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004258
John McCall7f416cc2015-09-08 08:05:57 +00004259 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4260 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004261 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4262 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4263 }
4264};
4265
Tim Northover573cbee2014-05-24 12:52:07 +00004266class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004267public:
Tim Northover573cbee2014-05-24 12:52:07 +00004268 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4269 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004270
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004271 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004272 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4273 }
4274
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004275 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4276 return 31;
4277 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004278
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004279 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004280};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004281}
Tim Northovera2ee4332014-03-29 15:09:45 +00004282
Tim Northoverb047bfa2014-11-27 21:02:49 +00004283ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004284 Ty = useFirstFieldIfTransparentUnion(Ty);
4285
Tim Northovera2ee4332014-03-29 15:09:45 +00004286 // Handle illegal vector types here.
4287 if (isIllegalVectorType(Ty)) {
4288 uint64_t Size = getContext().getTypeSize(Ty);
4289 if (Size <= 32) {
4290 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004291 return ABIArgInfo::getDirect(ResType);
4292 }
4293 if (Size == 64) {
4294 llvm::Type *ResType =
4295 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004296 return ABIArgInfo::getDirect(ResType);
4297 }
4298 if (Size == 128) {
4299 llvm::Type *ResType =
4300 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004301 return ABIArgInfo::getDirect(ResType);
4302 }
John McCall7f416cc2015-09-08 08:05:57 +00004303 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004304 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004305
4306 if (!isAggregateTypeForABI(Ty)) {
4307 // Treat an enum type as its underlying type.
4308 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4309 Ty = EnumTy->getDecl()->getIntegerType();
4310
Tim Northovera2ee4332014-03-29 15:09:45 +00004311 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4312 ? ABIArgInfo::getExtend()
4313 : ABIArgInfo::getDirect());
4314 }
4315
4316 // Structures with either a non-trivial destructor or a non-trivial
4317 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004318 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004319 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4320 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004321 }
4322
4323 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4324 // elsewhere for GNU compatibility.
4325 if (isEmptyRecord(getContext(), Ty, true)) {
4326 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4327 return ABIArgInfo::getIgnore();
4328
Tim Northovera2ee4332014-03-29 15:09:45 +00004329 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4330 }
4331
4332 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004333 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004334 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004335 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004336 return ABIArgInfo::getDirect(
4337 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004338 }
4339
4340 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4341 uint64_t Size = getContext().getTypeSize(Ty);
4342 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004343 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004344 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004345
Tim Northovera2ee4332014-03-29 15:09:45 +00004346 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4347 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004348 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004349 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4350 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4351 }
4352 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4353 }
4354
John McCall7f416cc2015-09-08 08:05:57 +00004355 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004356}
4357
Tim Northover573cbee2014-05-24 12:52:07 +00004358ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004359 if (RetTy->isVoidType())
4360 return ABIArgInfo::getIgnore();
4361
4362 // Large vector types should be returned via memory.
4363 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004364 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004365
4366 if (!isAggregateTypeForABI(RetTy)) {
4367 // Treat an enum type as its underlying type.
4368 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4369 RetTy = EnumTy->getDecl()->getIntegerType();
4370
Tim Northover4dab6982014-04-18 13:46:08 +00004371 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4372 ? ABIArgInfo::getExtend()
4373 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004374 }
4375
Tim Northovera2ee4332014-03-29 15:09:45 +00004376 if (isEmptyRecord(getContext(), RetTy, true))
4377 return ABIArgInfo::getIgnore();
4378
Craig Topper8a13c412014-05-21 05:09:00 +00004379 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004380 uint64_t Members = 0;
4381 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004382 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4383 return ABIArgInfo::getDirect();
4384
4385 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4386 uint64_t Size = getContext().getTypeSize(RetTy);
4387 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004388 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004389 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004390
4391 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4392 // For aggregates with 16-byte alignment, we use i128.
4393 if (Alignment < 128 && Size == 128) {
4394 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4395 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4396 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004397 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4398 }
4399
John McCall7f416cc2015-09-08 08:05:57 +00004400 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004401}
4402
Tim Northover573cbee2014-05-24 12:52:07 +00004403/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4404bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004405 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4406 // Check whether VT is legal.
4407 unsigned NumElements = VT->getNumElements();
4408 uint64_t Size = getContext().getTypeSize(VT);
4409 // NumElements should be power of 2 between 1 and 16.
4410 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4411 return true;
4412 return Size != 64 && (Size != 128 || NumElements == 1);
4413 }
4414 return false;
4415}
4416
Reid Klecknere9f6a712014-10-31 17:10:41 +00004417bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4418 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4419 // point type or a short-vector type. This is the same as the 32-bit ABI,
4420 // but with the difference that any floating-point type is allowed,
4421 // including __fp16.
4422 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4423 if (BT->isFloatingPoint())
4424 return true;
4425 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4426 unsigned VecSize = getContext().getTypeSize(VT);
4427 if (VecSize == 64 || VecSize == 128)
4428 return true;
4429 }
4430 return false;
4431}
4432
4433bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4434 uint64_t Members) const {
4435 return Members <= 4;
4436}
4437
John McCall7f416cc2015-09-08 08:05:57 +00004438Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004439 QualType Ty,
4440 CodeGenFunction &CGF) const {
4441 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004442 bool IsIndirect = AI.isIndirect();
4443
Tim Northoverb047bfa2014-11-27 21:02:49 +00004444 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4445 if (IsIndirect)
4446 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4447 else if (AI.getCoerceToType())
4448 BaseTy = AI.getCoerceToType();
4449
4450 unsigned NumRegs = 1;
4451 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4452 BaseTy = ArrTy->getElementType();
4453 NumRegs = ArrTy->getNumElements();
4454 }
4455 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4456
Tim Northovera2ee4332014-03-29 15:09:45 +00004457 // The AArch64 va_list type and handling is specified in the Procedure Call
4458 // Standard, section B.4:
4459 //
4460 // struct {
4461 // void *__stack;
4462 // void *__gr_top;
4463 // void *__vr_top;
4464 // int __gr_offs;
4465 // int __vr_offs;
4466 // };
4467
4468 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4469 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4470 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4471 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004472
John McCall7f416cc2015-09-08 08:05:57 +00004473 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4474 CharUnits TyAlign = TyInfo.second;
4475
4476 Address reg_offs_p = Address::invalid();
4477 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004478 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004479 CharUnits reg_top_offset;
4480 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004481 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004482 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004483 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004484 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4485 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004486 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4487 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004488 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004489 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004490 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004491 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004492 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004493 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4494 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004495 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4496 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004497 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004498 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004499 }
4500
4501 //=======================================
4502 // Find out where argument was passed
4503 //=======================================
4504
4505 // If reg_offs >= 0 we're already using the stack for this type of
4506 // argument. We don't want to keep updating reg_offs (in case it overflows,
4507 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4508 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004509 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004510 UsingStack = CGF.Builder.CreateICmpSGE(
4511 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4512
4513 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4514
4515 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004516 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004517 CGF.EmitBlock(MaybeRegBlock);
4518
4519 // Integer arguments may need to correct register alignment (for example a
4520 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4521 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004522 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4523 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004524
4525 reg_offs = CGF.Builder.CreateAdd(
4526 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4527 "align_regoffs");
4528 reg_offs = CGF.Builder.CreateAnd(
4529 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4530 "aligned_regoffs");
4531 }
4532
4533 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004534 // The fact that this is done unconditionally reflects the fact that
4535 // allocating an argument to the stack also uses up all the remaining
4536 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004537 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004538 NewOffset = CGF.Builder.CreateAdd(
4539 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4540 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4541
4542 // Now we're in a position to decide whether this argument really was in
4543 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004544 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004545 InRegs = CGF.Builder.CreateICmpSLE(
4546 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4547
4548 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4549
4550 //=======================================
4551 // Argument was in registers
4552 //=======================================
4553
4554 // Now we emit the code for if the argument was originally passed in
4555 // registers. First start the appropriate block:
4556 CGF.EmitBlock(InRegBlock);
4557
John McCall7f416cc2015-09-08 08:05:57 +00004558 llvm::Value *reg_top = nullptr;
4559 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4560 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004561 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004562 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4563 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4564 Address RegAddr = Address::invalid();
4565 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004566
4567 if (IsIndirect) {
4568 // If it's been passed indirectly (actually a struct), whatever we find from
4569 // stored registers or on the stack will actually be a struct **.
4570 MemTy = llvm::PointerType::getUnqual(MemTy);
4571 }
4572
Craig Topper8a13c412014-05-21 05:09:00 +00004573 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004574 uint64_t NumMembers = 0;
4575 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004576 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004577 // Homogeneous aggregates passed in registers will have their elements split
4578 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4579 // qN+1, ...). We reload and store into a temporary local variable
4580 // contiguously.
4581 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004582 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004583 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4584 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004585 Address Tmp = CGF.CreateTempAlloca(HFATy,
4586 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004587
John McCall7f416cc2015-09-08 08:05:57 +00004588 // On big-endian platforms, the value will be right-aligned in its slot.
4589 int Offset = 0;
4590 if (CGF.CGM.getDataLayout().isBigEndian() &&
4591 BaseTyInfo.first.getQuantity() < 16)
4592 Offset = 16 - BaseTyInfo.first.getQuantity();
4593
Tim Northovera2ee4332014-03-29 15:09:45 +00004594 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004595 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4596 Address LoadAddr =
4597 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4598 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4599
4600 Address StoreAddr =
4601 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004602
4603 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4604 CGF.Builder.CreateStore(Elem, StoreAddr);
4605 }
4606
John McCall7f416cc2015-09-08 08:05:57 +00004607 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004608 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004609 // Otherwise the object is contiguous in memory.
4610
4611 // It might be right-aligned in its slot.
4612 CharUnits SlotSize = BaseAddr.getAlignment();
4613 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004614 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004615 TyInfo.first < SlotSize) {
4616 CharUnits Offset = SlotSize - TyInfo.first;
4617 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004618 }
4619
John McCall7f416cc2015-09-08 08:05:57 +00004620 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004621 }
4622
4623 CGF.EmitBranch(ContBlock);
4624
4625 //=======================================
4626 // Argument was on the stack
4627 //=======================================
4628 CGF.EmitBlock(OnStackBlock);
4629
John McCall7f416cc2015-09-08 08:05:57 +00004630 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4631 CharUnits::Zero(), "stack_p");
4632 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004633
John McCall7f416cc2015-09-08 08:05:57 +00004634 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004635 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004636 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4637 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004638
John McCall7f416cc2015-09-08 08:05:57 +00004639 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004640
John McCall7f416cc2015-09-08 08:05:57 +00004641 OnStackPtr = CGF.Builder.CreateAdd(
4642 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004643 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004644 OnStackPtr = CGF.Builder.CreateAnd(
4645 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004646 "align_stack");
4647
John McCall7f416cc2015-09-08 08:05:57 +00004648 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004649 }
John McCall7f416cc2015-09-08 08:05:57 +00004650 Address OnStackAddr(OnStackPtr,
4651 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004652
John McCall7f416cc2015-09-08 08:05:57 +00004653 // All stack slots are multiples of 8 bytes.
4654 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4655 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004656 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004657 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004658 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004659 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004660
John McCall7f416cc2015-09-08 08:05:57 +00004661 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004662 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004663 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004664
4665 // Write the new value of __stack for the next call to va_arg
4666 CGF.Builder.CreateStore(NewStack, stack_p);
4667
4668 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004669 TyInfo.first < StackSlotSize) {
4670 CharUnits Offset = StackSlotSize - TyInfo.first;
4671 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004672 }
4673
John McCall7f416cc2015-09-08 08:05:57 +00004674 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004675
4676 CGF.EmitBranch(ContBlock);
4677
4678 //=======================================
4679 // Tidy up
4680 //=======================================
4681 CGF.EmitBlock(ContBlock);
4682
John McCall7f416cc2015-09-08 08:05:57 +00004683 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4684 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004685
4686 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004687 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4688 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004689
4690 return ResAddr;
4691}
4692
John McCall7f416cc2015-09-08 08:05:57 +00004693Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4694 CodeGenFunction &CGF) const {
4695 // The backend's lowering doesn't support va_arg for aggregates or
4696 // illegal vector types. Lower VAArg here for these cases and use
4697 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004699 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004700
John McCall7f416cc2015-09-08 08:05:57 +00004701 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004702
John McCall7f416cc2015-09-08 08:05:57 +00004703 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004704 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004705 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4706 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4707 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004708 }
4709
John McCall7f416cc2015-09-08 08:05:57 +00004710 // The size of the actual thing passed, which might end up just
4711 // being a pointer for indirect types.
4712 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4713
4714 // Arguments bigger than 16 bytes which aren't homogeneous
4715 // aggregates should be passed indirectly.
4716 bool IsIndirect = false;
4717 if (TyInfo.first.getQuantity() > 16) {
4718 const Type *Base = nullptr;
4719 uint64_t Members = 0;
4720 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004721 }
4722
John McCall7f416cc2015-09-08 08:05:57 +00004723 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4724 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004725}
4726
4727//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004728// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004729//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004730
4731namespace {
4732
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004733class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004734public:
4735 enum ABIKind {
4736 APCS = 0,
4737 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004738 AAPCS_VFP = 2,
4739 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004740 };
4741
4742private:
4743 ABIKind Kind;
4744
4745public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004746 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004747 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004748 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004749
John McCall3480ef22011-08-30 01:42:09 +00004750 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004751 switch (getTarget().getTriple().getEnvironment()) {
4752 case llvm::Triple::Android:
4753 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004754 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004755 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004756 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004757 return true;
4758 default:
4759 return false;
4760 }
John McCall3480ef22011-08-30 01:42:09 +00004761 }
4762
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004763 bool isEABIHF() const {
4764 switch (getTarget().getTriple().getEnvironment()) {
4765 case llvm::Triple::EABIHF:
4766 case llvm::Triple::GNUEABIHF:
4767 return true;
4768 default:
4769 return false;
4770 }
4771 }
4772
Stephen Hines8267e7d2015-12-04 01:39:30 +00004773 bool isAndroid() const {
4774 return (getTarget().getTriple().getEnvironment() ==
4775 llvm::Triple::Android);
4776 }
4777
Daniel Dunbar020daa92009-09-12 01:00:39 +00004778 ABIKind getABIKind() const { return Kind; }
4779
Tim Northovera484bc02013-10-01 14:34:25 +00004780private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004781 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004782 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004783 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004784
Reid Klecknere9f6a712014-10-31 17:10:41 +00004785 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4786 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4787 uint64_t Members) const override;
4788
Craig Topper4f12f102014-03-12 06:41:41 +00004789 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004790
John McCall7f416cc2015-09-08 08:05:57 +00004791 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4792 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004793
4794 llvm::CallingConv::ID getLLVMDefaultCC() const;
4795 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004796 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004797};
4798
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004799class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4800public:
Chris Lattner2b037972010-07-29 02:01:43 +00004801 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4802 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004803
John McCall3480ef22011-08-30 01:42:09 +00004804 const ARMABIInfo &getABIInfo() const {
4805 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4806 }
4807
Craig Topper4f12f102014-03-12 06:41:41 +00004808 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004809 return 13;
4810 }
Roman Divackyc1617352011-05-18 19:36:54 +00004811
Craig Topper4f12f102014-03-12 06:41:41 +00004812 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004813 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4814 }
4815
Roman Divackyc1617352011-05-18 19:36:54 +00004816 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004817 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004818 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004819
4820 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004821 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004822 return false;
4823 }
John McCall3480ef22011-08-30 01:42:09 +00004824
Craig Topper4f12f102014-03-12 06:41:41 +00004825 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004826 if (getABIInfo().isEABI()) return 88;
4827 return TargetCodeGenInfo::getSizeOfUnwindException();
4828 }
Tim Northovera484bc02013-10-01 14:34:25 +00004829
Eric Christopher162c91c2015-06-05 22:03:00 +00004830 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004831 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00004832 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00004833 if (!FD)
4834 return;
4835
4836 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4837 if (!Attr)
4838 return;
4839
4840 const char *Kind;
4841 switch (Attr->getInterrupt()) {
4842 case ARMInterruptAttr::Generic: Kind = ""; break;
4843 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4844 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4845 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4846 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4847 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4848 }
4849
4850 llvm::Function *Fn = cast<llvm::Function>(GV);
4851
4852 Fn->addFnAttr("interrupt", Kind);
4853
Tim Northover5627d392015-10-30 16:30:45 +00004854 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
4855 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00004856 return;
4857
4858 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4859 // however this is not necessarily true on taking any interrupt. Instruct
4860 // the backend to perform a realignment as part of the function prologue.
4861 llvm::AttrBuilder B;
4862 B.addStackAlignmentAttr(8);
4863 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4864 llvm::AttributeSet::get(CGM.getLLVMContext(),
4865 llvm::AttributeSet::FunctionIndex,
4866 B));
4867 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004868};
4869
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004870class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4871 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4872 CodeGen::CodeGenModule &CGM) const;
4873
4874public:
4875 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4876 : ARMTargetCodeGenInfo(CGT, K) {}
4877
Eric Christopher162c91c2015-06-05 22:03:00 +00004878 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004879 CodeGen::CodeGenModule &CGM) const override;
4880};
4881
4882void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4883 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4884 if (!isa<FunctionDecl>(D))
4885 return;
4886 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4887 return;
4888
4889 llvm::Function *F = cast<llvm::Function>(GV);
4890 F->addFnAttr("stack-probe-size",
4891 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4892}
4893
Eric Christopher162c91c2015-06-05 22:03:00 +00004894void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004895 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004896 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004897 addStackProbeSizeTargetAttribute(D, GV, CGM);
4898}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004899}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004900
Chris Lattner22326a12010-07-29 02:31:05 +00004901void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004902 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004903 FI.getReturnInfo() =
4904 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004905
Tim Northoverbc784d12015-02-24 17:22:40 +00004906 for (auto &I : FI.arguments())
4907 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004908
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004909 // Always honor user-specified calling convention.
4910 if (FI.getCallingConvention() != llvm::CallingConv::C)
4911 return;
4912
John McCall882987f2013-02-28 19:01:20 +00004913 llvm::CallingConv::ID cc = getRuntimeCC();
4914 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004915 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004916}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004917
John McCall882987f2013-02-28 19:01:20 +00004918/// Return the default calling convention that LLVM will use.
4919llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4920 // The default calling convention that LLVM will infer.
Tim Northover5627d392015-10-30 16:30:45 +00004921 if (isEABIHF() || getTarget().getTriple().isWatchOS())
John McCall882987f2013-02-28 19:01:20 +00004922 return llvm::CallingConv::ARM_AAPCS_VFP;
4923 else if (isEABI())
4924 return llvm::CallingConv::ARM_AAPCS;
4925 else
4926 return llvm::CallingConv::ARM_APCS;
4927}
4928
4929/// Return the calling convention that our ABI would like us to use
4930/// as the C calling convention.
4931llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004932 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004933 case APCS: return llvm::CallingConv::ARM_APCS;
4934 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4935 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00004936 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004937 }
John McCall882987f2013-02-28 19:01:20 +00004938 llvm_unreachable("bad ABI kind");
4939}
4940
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004941void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004942 assert(getRuntimeCC() == llvm::CallingConv::C);
4943
4944 // Don't muddy up the IR with a ton of explicit annotations if
4945 // they'd just match what LLVM will infer from the triple.
4946 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4947 if (abiCC != getLLVMDefaultCC())
4948 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004949
Tim Northover5627d392015-10-30 16:30:45 +00004950 // AAPCS apparently requires runtime support functions to be soft-float, but
4951 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
4952 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
4953 switch (getABIKind()) {
4954 case APCS:
4955 case AAPCS16_VFP:
4956 if (abiCC != getLLVMDefaultCC())
4957 BuiltinCC = abiCC;
4958 break;
4959 case AAPCS:
4960 case AAPCS_VFP:
4961 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
4962 break;
4963 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004964}
4965
Tim Northoverbc784d12015-02-24 17:22:40 +00004966ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4967 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004968 // 6.1.2.1 The following argument types are VFP CPRCs:
4969 // A single-precision floating-point type (including promoted
4970 // half-precision types); A double-precision floating-point type;
4971 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4972 // with a Base Type of a single- or double-precision floating-point type,
4973 // 64-bit containerized vectors or 128-bit containerized vectors with one
4974 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004975 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004976
Reid Klecknerb1be6832014-11-15 01:41:41 +00004977 Ty = useFirstFieldIfTransparentUnion(Ty);
4978
Manman Renfef9e312012-10-16 19:18:39 +00004979 // Handle illegal vector types here.
4980 if (isIllegalVectorType(Ty)) {
4981 uint64_t Size = getContext().getTypeSize(Ty);
4982 if (Size <= 32) {
4983 llvm::Type *ResType =
4984 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004985 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004986 }
4987 if (Size == 64) {
4988 llvm::Type *ResType = llvm::VectorType::get(
4989 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004990 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004991 }
4992 if (Size == 128) {
4993 llvm::Type *ResType = llvm::VectorType::get(
4994 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004995 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004996 }
John McCall7f416cc2015-09-08 08:05:57 +00004997 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00004998 }
4999
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005000 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5001 // unspecified. This is not done for OpenCL as it handles the half type
5002 // natively, and does not need to interwork with AAPCS code.
5003 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
5004 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5005 llvm::Type::getFloatTy(getVMContext()) :
5006 llvm::Type::getInt32Ty(getVMContext());
5007 return ABIArgInfo::getDirect(ResType);
5008 }
5009
John McCalla1dee5302010-08-22 10:59:02 +00005010 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005011 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005012 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005013 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005014 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005015
Tim Northover5a1558e2014-11-07 22:30:50 +00005016 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5017 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005018 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005019
Oliver Stannard405bded2014-02-11 09:25:50 +00005020 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005021 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005022 }
Tim Northover1060eae2013-06-21 22:49:34 +00005023
Daniel Dunbar09d33622009-09-14 21:54:03 +00005024 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005025 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005026 return ABIArgInfo::getIgnore();
5027
Tim Northover5a1558e2014-11-07 22:30:50 +00005028 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005029 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5030 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005031 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005032 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005033 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005034 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005035 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005036 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005037 }
Tim Northover5627d392015-10-30 16:30:45 +00005038 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5039 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5040 // this convention even for a variadic function: the backend will use GPRs
5041 // if needed.
5042 const Type *Base = nullptr;
5043 uint64_t Members = 0;
5044 if (isHomogeneousAggregate(Ty, Base, Members)) {
5045 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5046 llvm::Type *Ty =
5047 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5048 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5049 }
5050 }
5051
5052 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5053 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5054 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5055 // bigger than 128-bits, they get placed in space allocated by the caller,
5056 // and a pointer is passed.
5057 return ABIArgInfo::getIndirect(
5058 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005059 }
5060
Manman Ren6c30e132012-08-13 21:23:55 +00005061 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005062 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5063 // most 8-byte. We realign the indirect argument if type alignment is bigger
5064 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005065 uint64_t ABIAlign = 4;
5066 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5067 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005068 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005069 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005070
Manman Ren8cd99812012-11-06 04:58:01 +00005071 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005072 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005073 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5074 /*ByVal=*/true,
5075 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005076 }
5077
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005078 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005079 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005080 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005081 // FIXME: Try to match the types of the arguments more accurately where
5082 // we can.
5083 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005084 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5085 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005086 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005087 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5088 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005089 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005090
Tim Northover5a1558e2014-11-07 22:30:50 +00005091 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005092}
5093
Chris Lattner458b2aa2010-07-29 02:16:43 +00005094static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005095 llvm::LLVMContext &VMContext) {
5096 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5097 // is called integer-like if its size is less than or equal to one word, and
5098 // the offset of each of its addressable sub-fields is zero.
5099
5100 uint64_t Size = Context.getTypeSize(Ty);
5101
5102 // Check that the type fits in a word.
5103 if (Size > 32)
5104 return false;
5105
5106 // FIXME: Handle vector types!
5107 if (Ty->isVectorType())
5108 return false;
5109
Daniel Dunbard53bac72009-09-14 02:20:34 +00005110 // Float types are never treated as "integer like".
5111 if (Ty->isRealFloatingType())
5112 return false;
5113
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005114 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005115 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005116 return true;
5117
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005118 // Small complex integer types are "integer like".
5119 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5120 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005121
5122 // Single element and zero sized arrays should be allowed, by the definition
5123 // above, but they are not.
5124
5125 // Otherwise, it must be a record type.
5126 const RecordType *RT = Ty->getAs<RecordType>();
5127 if (!RT) return false;
5128
5129 // Ignore records with flexible arrays.
5130 const RecordDecl *RD = RT->getDecl();
5131 if (RD->hasFlexibleArrayMember())
5132 return false;
5133
5134 // Check that all sub-fields are at offset 0, and are themselves "integer
5135 // like".
5136 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5137
5138 bool HadField = false;
5139 unsigned idx = 0;
5140 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5141 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005142 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005143
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005144 // Bit-fields are not addressable, we only need to verify they are "integer
5145 // like". We still have to disallow a subsequent non-bitfield, for example:
5146 // struct { int : 0; int x }
5147 // is non-integer like according to gcc.
5148 if (FD->isBitField()) {
5149 if (!RD->isUnion())
5150 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005151
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005152 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5153 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005154
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005155 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005156 }
5157
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005158 // Check if this field is at offset 0.
5159 if (Layout.getFieldOffset(idx) != 0)
5160 return false;
5161
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005162 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5163 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005164
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005165 // Only allow at most one field in a structure. This doesn't match the
5166 // wording above, but follows gcc in situations with a field following an
5167 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005168 if (!RD->isUnion()) {
5169 if (HadField)
5170 return false;
5171
5172 HadField = true;
5173 }
5174 }
5175
5176 return true;
5177}
5178
Oliver Stannard405bded2014-02-11 09:25:50 +00005179ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5180 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005181 bool IsEffectivelyAAPCS_VFP =
5182 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005183
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005184 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005185 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005186
Daniel Dunbar19964db2010-09-23 01:54:32 +00005187 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005188 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005189 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005190 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005191
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005192 // __fp16 gets returned as if it were an int or float, but with the top 16
5193 // bits unspecified. This is not done for OpenCL as it handles the half type
5194 // natively, and does not need to interwork with AAPCS code.
5195 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5196 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5197 llvm::Type::getFloatTy(getVMContext()) :
5198 llvm::Type::getInt32Ty(getVMContext());
5199 return ABIArgInfo::getDirect(ResType);
5200 }
5201
John McCalla1dee5302010-08-22 10:59:02 +00005202 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005203 // Treat an enum type as its underlying type.
5204 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5205 RetTy = EnumTy->getDecl()->getIntegerType();
5206
Tim Northover5a1558e2014-11-07 22:30:50 +00005207 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5208 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005209 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005210
5211 // Are we following APCS?
5212 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005213 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005214 return ABIArgInfo::getIgnore();
5215
Daniel Dunbareedf1512010-02-01 23:31:19 +00005216 // Complex types are all returned as packed integers.
5217 //
5218 // FIXME: Consider using 2 x vector types if the back end handles them
5219 // correctly.
5220 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005221 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5222 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005223
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005224 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005225 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005226 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005227 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005228 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005229 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005230 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005231 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5232 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005233 }
5234
5235 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005236 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005237 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005238
5239 // Otherwise this is an AAPCS variant.
5240
Chris Lattner458b2aa2010-07-29 02:16:43 +00005241 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005242 return ABIArgInfo::getIgnore();
5243
Bob Wilson1d9269a2011-11-02 04:51:36 +00005244 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005245 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005246 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005247 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005248 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005249 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005250 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005251 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005252 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005253 }
5254
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005255 // Aggregates <= 4 bytes are returned in r0; other aggregates
5256 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005257 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005258 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005259 if (getDataLayout().isBigEndian())
5260 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005261 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005262
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005263 // Return in the smallest viable integer type.
5264 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005265 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005266 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005267 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5268 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005269 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5270 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5271 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005272 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005273 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005274 }
5275
John McCall7f416cc2015-09-08 08:05:57 +00005276 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005277}
5278
Manman Renfef9e312012-10-16 19:18:39 +00005279/// isIllegalVector - check whether Ty is an illegal vector type.
5280bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005281 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5282 if (isAndroid()) {
5283 // Android shipped using Clang 3.1, which supported a slightly different
5284 // vector ABI. The primary differences were that 3-element vector types
5285 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5286 // accepts that legacy behavior for Android only.
5287 // Check whether VT is legal.
5288 unsigned NumElements = VT->getNumElements();
5289 // NumElements should be power of 2 or equal to 3.
5290 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5291 return true;
5292 } else {
5293 // Check whether VT is legal.
5294 unsigned NumElements = VT->getNumElements();
5295 uint64_t Size = getContext().getTypeSize(VT);
5296 // NumElements should be power of 2.
5297 if (!llvm::isPowerOf2_32(NumElements))
5298 return true;
5299 // Size should be greater than 32 bits.
5300 return Size <= 32;
5301 }
Manman Renfef9e312012-10-16 19:18:39 +00005302 }
5303 return false;
5304}
5305
Reid Klecknere9f6a712014-10-31 17:10:41 +00005306bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5307 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5308 // double, or 64-bit or 128-bit vectors.
5309 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5310 if (BT->getKind() == BuiltinType::Float ||
5311 BT->getKind() == BuiltinType::Double ||
5312 BT->getKind() == BuiltinType::LongDouble)
5313 return true;
5314 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5315 unsigned VecSize = getContext().getTypeSize(VT);
5316 if (VecSize == 64 || VecSize == 128)
5317 return true;
5318 }
5319 return false;
5320}
5321
5322bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5323 uint64_t Members) const {
5324 return Members <= 4;
5325}
5326
John McCall7f416cc2015-09-08 08:05:57 +00005327Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5328 QualType Ty) const {
5329 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005330
John McCall7f416cc2015-09-08 08:05:57 +00005331 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005332 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005333 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5334 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5335 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005336 }
5337
John McCall7f416cc2015-09-08 08:05:57 +00005338 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5339 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005340
John McCall7f416cc2015-09-08 08:05:57 +00005341 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5342 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005343 const Type *Base = nullptr;
5344 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005345 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5346 IsIndirect = true;
5347
Tim Northover5627d392015-10-30 16:30:45 +00005348 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5349 // allocated by the caller.
5350 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5351 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5352 !isHomogeneousAggregate(Ty, Base, Members)) {
5353 IsIndirect = true;
5354
John McCall7f416cc2015-09-08 08:05:57 +00005355 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005356 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5357 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005358 // Our callers should be prepared to handle an under-aligned address.
5359 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5360 getABIKind() == ARMABIInfo::AAPCS) {
5361 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5362 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005363 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5364 // ARMv7k allows type alignment up to 16 bytes.
5365 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5366 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005367 } else {
5368 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005369 }
John McCall7f416cc2015-09-08 08:05:57 +00005370 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005371
John McCall7f416cc2015-09-08 08:05:57 +00005372 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5373 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005374}
5375
Chris Lattner0cf24192010-06-28 20:05:43 +00005376//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005377// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005378//===----------------------------------------------------------------------===//
5379
5380namespace {
5381
Justin Holewinski83e96682012-05-24 17:43:12 +00005382class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005383public:
Justin Holewinski36837432013-03-30 14:38:24 +00005384 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005385
5386 ABIArgInfo classifyReturnType(QualType RetTy) const;
5387 ABIArgInfo classifyArgumentType(QualType Ty) const;
5388
Craig Topper4f12f102014-03-12 06:41:41 +00005389 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005390 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5391 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005392};
5393
Justin Holewinski83e96682012-05-24 17:43:12 +00005394class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005395public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005396 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5397 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005398
Eric Christopher162c91c2015-06-05 22:03:00 +00005399 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005400 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005401private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005402 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5403 // resulting MDNode to the nvvm.annotations MDNode.
5404 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005405};
5406
Justin Holewinski83e96682012-05-24 17:43:12 +00005407ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005408 if (RetTy->isVoidType())
5409 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005410
5411 // note: this is different from default ABI
5412 if (!RetTy->isScalarType())
5413 return ABIArgInfo::getDirect();
5414
5415 // Treat an enum type as its underlying type.
5416 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5417 RetTy = EnumTy->getDecl()->getIntegerType();
5418
5419 return (RetTy->isPromotableIntegerType() ?
5420 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005421}
5422
Justin Holewinski83e96682012-05-24 17:43:12 +00005423ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005424 // Treat an enum type as its underlying type.
5425 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5426 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005427
Eli Bendersky95338a02014-10-29 13:43:21 +00005428 // Return aggregates type as indirect by value
5429 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005430 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005431
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005432 return (Ty->isPromotableIntegerType() ?
5433 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005434}
5435
Justin Holewinski83e96682012-05-24 17:43:12 +00005436void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005437 if (!getCXXABI().classifyReturnType(FI))
5438 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005439 for (auto &I : FI.arguments())
5440 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005441
5442 // Always honor user-specified calling convention.
5443 if (FI.getCallingConvention() != llvm::CallingConv::C)
5444 return;
5445
John McCall882987f2013-02-28 19:01:20 +00005446 FI.setEffectiveCallingConvention(getRuntimeCC());
5447}
5448
John McCall7f416cc2015-09-08 08:05:57 +00005449Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5450 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005451 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005452}
5453
Justin Holewinski83e96682012-05-24 17:43:12 +00005454void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005455setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005456 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005457 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005458 if (!FD) return;
5459
5460 llvm::Function *F = cast<llvm::Function>(GV);
5461
5462 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005463 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005464 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005465 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005466 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005467 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005468 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5469 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005470 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005471 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005472 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005473 }
Justin Holewinski38031972011-10-05 17:58:44 +00005474
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005475 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005476 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005477 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005478 // __global__ functions cannot be called from the device, we do not
5479 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005480 if (FD->hasAttr<CUDAGlobalAttr>()) {
5481 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5482 addNVVMMetadata(F, "kernel", 1);
5483 }
Artem Belevich7093e402015-04-21 22:55:54 +00005484 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005485 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005486 llvm::APSInt MaxThreads(32);
5487 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5488 if (MaxThreads > 0)
5489 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5490
5491 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5492 // not specified in __launch_bounds__ or if the user specified a 0 value,
5493 // we don't have to add a PTX directive.
5494 if (Attr->getMinBlocks()) {
5495 llvm::APSInt MinBlocks(32);
5496 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5497 if (MinBlocks > 0)
5498 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5499 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005500 }
5501 }
Justin Holewinski38031972011-10-05 17:58:44 +00005502 }
5503}
5504
Eli Benderskye06a2c42014-04-15 16:57:05 +00005505void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5506 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005507 llvm::Module *M = F->getParent();
5508 llvm::LLVMContext &Ctx = M->getContext();
5509
5510 // Get "nvvm.annotations" metadata node
5511 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5512
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005513 llvm::Metadata *MDVals[] = {
5514 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5515 llvm::ConstantAsMetadata::get(
5516 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005517 // Append metadata to nvvm.annotations
5518 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5519}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005520}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005521
5522//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005523// SystemZ ABI Implementation
5524//===----------------------------------------------------------------------===//
5525
5526namespace {
5527
5528class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005529 bool HasVector;
5530
Ulrich Weigand47445072013-05-06 16:26:41 +00005531public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005532 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5533 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005534
5535 bool isPromotableIntegerType(QualType Ty) const;
5536 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005537 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005538 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005539 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005540
5541 ABIArgInfo classifyReturnType(QualType RetTy) const;
5542 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5543
Craig Topper4f12f102014-03-12 06:41:41 +00005544 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005545 if (!getCXXABI().classifyReturnType(FI))
5546 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005547 for (auto &I : FI.arguments())
5548 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005549 }
5550
John McCall7f416cc2015-09-08 08:05:57 +00005551 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5552 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005553};
5554
5555class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5556public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005557 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5558 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005559};
5560
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005561}
Ulrich Weigand47445072013-05-06 16:26:41 +00005562
5563bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5564 // Treat an enum type as its underlying type.
5565 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5566 Ty = EnumTy->getDecl()->getIntegerType();
5567
5568 // Promotable integer types are required to be promoted by the ABI.
5569 if (Ty->isPromotableIntegerType())
5570 return true;
5571
5572 // 32-bit values must also be promoted.
5573 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5574 switch (BT->getKind()) {
5575 case BuiltinType::Int:
5576 case BuiltinType::UInt:
5577 return true;
5578 default:
5579 return false;
5580 }
5581 return false;
5582}
5583
5584bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005585 return (Ty->isAnyComplexType() ||
5586 Ty->isVectorType() ||
5587 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005588}
5589
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005590bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5591 return (HasVector &&
5592 Ty->isVectorType() &&
5593 getContext().getTypeSize(Ty) <= 128);
5594}
5595
Ulrich Weigand47445072013-05-06 16:26:41 +00005596bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5597 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5598 switch (BT->getKind()) {
5599 case BuiltinType::Float:
5600 case BuiltinType::Double:
5601 return true;
5602 default:
5603 return false;
5604 }
5605
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005606 return false;
5607}
5608
5609QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005610 if (const RecordType *RT = Ty->getAsStructureType()) {
5611 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005612 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005613
5614 // If this is a C++ record, check the bases first.
5615 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005616 for (const auto &I : CXXRD->bases()) {
5617 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005618
5619 // Empty bases don't affect things either way.
5620 if (isEmptyRecord(getContext(), Base, true))
5621 continue;
5622
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005623 if (!Found.isNull())
5624 return Ty;
5625 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005626 }
5627
5628 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005629 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005630 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005631 // Unlike isSingleElementStruct(), empty structure and array fields
5632 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005633 if (getContext().getLangOpts().CPlusPlus &&
5634 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5635 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005636
5637 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005638 // Nested structures still do though.
5639 if (!Found.isNull())
5640 return Ty;
5641 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005642 }
5643
5644 // Unlike isSingleElementStruct(), trailing padding is allowed.
5645 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005646 if (!Found.isNull())
5647 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005648 }
5649
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005650 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005651}
5652
John McCall7f416cc2015-09-08 08:05:57 +00005653Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5654 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005655 // Assume that va_list type is correct; should be pointer to LLVM type:
5656 // struct {
5657 // i64 __gpr;
5658 // i64 __fpr;
5659 // i8 *__overflow_arg_area;
5660 // i8 *__reg_save_area;
5661 // };
5662
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005663 // Every non-vector argument occupies 8 bytes and is passed by preference
5664 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5665 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005666 Ty = getContext().getCanonicalType(Ty);
5667 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005668 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005669 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005670 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005671 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005672 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005673 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005674 CharUnits UnpaddedSize;
5675 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005676 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005677 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5678 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005679 } else {
5680 if (AI.getCoerceToType())
5681 ArgTy = AI.getCoerceToType();
5682 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005683 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005684 UnpaddedSize = TyInfo.first;
5685 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005686 }
John McCall7f416cc2015-09-08 08:05:57 +00005687 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5688 if (IsVector && UnpaddedSize > PaddedSize)
5689 PaddedSize = CharUnits::fromQuantity(16);
5690 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005691
John McCall7f416cc2015-09-08 08:05:57 +00005692 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005693
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005694 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005695 llvm::Value *PaddedSizeV =
5696 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005697
5698 if (IsVector) {
5699 // Work out the address of a vector argument on the stack.
5700 // Vector arguments are always passed in the high bits of a
5701 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005702 Address OverflowArgAreaPtr =
5703 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005704 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005705 Address OverflowArgArea =
5706 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5707 TyInfo.second);
5708 Address MemAddr =
5709 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005710
5711 // Update overflow_arg_area_ptr pointer
5712 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005713 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5714 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005715 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5716
5717 return MemAddr;
5718 }
5719
John McCall7f416cc2015-09-08 08:05:57 +00005720 assert(PaddedSize.getQuantity() == 8);
5721
5722 unsigned MaxRegs, RegCountField, RegSaveIndex;
5723 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005724 if (InFPRs) {
5725 MaxRegs = 4; // Maximum of 4 FPR arguments
5726 RegCountField = 1; // __fpr
5727 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005728 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005729 } else {
5730 MaxRegs = 5; // Maximum of 5 GPR arguments
5731 RegCountField = 0; // __gpr
5732 RegSaveIndex = 2; // save offset for r2
5733 RegPadding = Padding; // values are passed in the low bits of a GPR
5734 }
5735
John McCall7f416cc2015-09-08 08:05:57 +00005736 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5737 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5738 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005739 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005740 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5741 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005742 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005743
5744 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5745 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5746 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5747 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5748
5749 // Emit code to load the value if it was passed in registers.
5750 CGF.EmitBlock(InRegBlock);
5751
5752 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005753 llvm::Value *ScaledRegCount =
5754 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5755 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005756 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5757 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005758 llvm::Value *RegOffset =
5759 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005760 Address RegSaveAreaPtr =
5761 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5762 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005763 llvm::Value *RegSaveArea =
5764 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005765 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5766 "raw_reg_addr"),
5767 PaddedSize);
5768 Address RegAddr =
5769 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005770
5771 // Update the register count
5772 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5773 llvm::Value *NewRegCount =
5774 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5775 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5776 CGF.EmitBranch(ContBlock);
5777
5778 // Emit code to load the value if it was passed in memory.
5779 CGF.EmitBlock(InMemBlock);
5780
5781 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005782 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5783 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5784 Address OverflowArgArea =
5785 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5786 PaddedSize);
5787 Address RawMemAddr =
5788 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5789 Address MemAddr =
5790 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005791
5792 // Update overflow_arg_area_ptr pointer
5793 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005794 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5795 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005796 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5797 CGF.EmitBranch(ContBlock);
5798
5799 // Return the appropriate result.
5800 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005801 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5802 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005803
5804 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005805 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5806 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005807
5808 return ResAddr;
5809}
5810
Ulrich Weigand47445072013-05-06 16:26:41 +00005811ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5812 if (RetTy->isVoidType())
5813 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005814 if (isVectorArgumentType(RetTy))
5815 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005816 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005817 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005818 return (isPromotableIntegerType(RetTy) ?
5819 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5820}
5821
5822ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5823 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005824 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005825 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005826
5827 // Integers and enums are extended to full register width.
5828 if (isPromotableIntegerType(Ty))
5829 return ABIArgInfo::getExtend();
5830
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005831 // Handle vector types and vector-like structure types. Note that
5832 // as opposed to float-like structure types, we do not allow any
5833 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005834 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005835 QualType SingleElementTy = GetSingleElementType(Ty);
5836 if (isVectorArgumentType(SingleElementTy) &&
5837 getContext().getTypeSize(SingleElementTy) == Size)
5838 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5839
5840 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005841 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005842 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005843
5844 // Handle small structures.
5845 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5846 // Structures with flexible arrays have variable length, so really
5847 // fail the size test above.
5848 const RecordDecl *RD = RT->getDecl();
5849 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005850 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005851
5852 // The structure is passed as an unextended integer, a float, or a double.
5853 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005854 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005855 assert(Size == 32 || Size == 64);
5856 if (Size == 32)
5857 PassTy = llvm::Type::getFloatTy(getVMContext());
5858 else
5859 PassTy = llvm::Type::getDoubleTy(getVMContext());
5860 } else
5861 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5862 return ABIArgInfo::getDirect(PassTy);
5863 }
5864
5865 // Non-structure compounds are passed indirectly.
5866 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005867 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005868
Craig Topper8a13c412014-05-21 05:09:00 +00005869 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005870}
5871
5872//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005873// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005874//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005875
5876namespace {
5877
5878class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5879public:
Chris Lattner2b037972010-07-29 02:01:43 +00005880 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5881 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005882 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005883 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005884};
5885
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005886}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005887
Eric Christopher162c91c2015-06-05 22:03:00 +00005888void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005889 llvm::GlobalValue *GV,
5890 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005891 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005892 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5893 // Handle 'interrupt' attribute:
5894 llvm::Function *F = cast<llvm::Function>(GV);
5895
5896 // Step 1: Set ISR calling convention.
5897 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5898
5899 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005900 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005901
5902 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005903 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005904 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5905 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005906 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005907 }
5908}
5909
Chris Lattner0cf24192010-06-28 20:05:43 +00005910//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005911// MIPS ABI Implementation. This works for both little-endian and
5912// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005913//===----------------------------------------------------------------------===//
5914
John McCall943fae92010-05-27 06:19:26 +00005915namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005916class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005917 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005918 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5919 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005920 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005921 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005922 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005923 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005924public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005925 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005926 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005927 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005928
5929 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005930 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005931 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005932 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5933 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005934 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005935};
5936
John McCall943fae92010-05-27 06:19:26 +00005937class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005938 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005939public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005940 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5941 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005942 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005943
Craig Topper4f12f102014-03-12 06:41:41 +00005944 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005945 return 29;
5946 }
5947
Eric Christopher162c91c2015-06-05 22:03:00 +00005948 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005949 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005950 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005951 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005952 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005953 if (FD->hasAttr<Mips16Attr>()) {
5954 Fn->addFnAttr("mips16");
5955 }
5956 else if (FD->hasAttr<NoMips16Attr>()) {
5957 Fn->addFnAttr("nomips16");
5958 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005959
5960 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
5961 if (!Attr)
5962 return;
5963
5964 const char *Kind;
5965 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005966 case MipsInterruptAttr::eic: Kind = "eic"; break;
5967 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
5968 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
5969 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
5970 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
5971 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
5972 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
5973 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
5974 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
5975 }
5976
5977 Fn->addFnAttr("interrupt", Kind);
5978
Reed Kotler373feca2013-01-16 17:10:28 +00005979 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005980
John McCall943fae92010-05-27 06:19:26 +00005981 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005982 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005983
Craig Topper4f12f102014-03-12 06:41:41 +00005984 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005985 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005986 }
John McCall943fae92010-05-27 06:19:26 +00005987};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005988}
John McCall943fae92010-05-27 06:19:26 +00005989
Eric Christopher7565e0d2015-05-29 23:09:49 +00005990void MipsABIInfo::CoerceToIntArgs(
5991 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005992 llvm::IntegerType *IntTy =
5993 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005994
5995 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5996 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5997 ArgList.push_back(IntTy);
5998
5999 // If necessary, add one more integer type to ArgList.
6000 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6001
6002 if (R)
6003 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006004}
6005
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006006// In N32/64, an aligned double precision floating point field is passed in
6007// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006008llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006009 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6010
6011 if (IsO32) {
6012 CoerceToIntArgs(TySize, ArgList);
6013 return llvm::StructType::get(getVMContext(), ArgList);
6014 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006015
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006016 if (Ty->isComplexType())
6017 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006018
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006019 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006020
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006021 // Unions/vectors are passed in integer registers.
6022 if (!RT || !RT->isStructureOrClassType()) {
6023 CoerceToIntArgs(TySize, ArgList);
6024 return llvm::StructType::get(getVMContext(), ArgList);
6025 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006026
6027 const RecordDecl *RD = RT->getDecl();
6028 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006029 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006030
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006031 uint64_t LastOffset = 0;
6032 unsigned idx = 0;
6033 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6034
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006035 // Iterate over fields in the struct/class and check if there are any aligned
6036 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006037 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6038 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006039 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006040 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6041
6042 if (!BT || BT->getKind() != BuiltinType::Double)
6043 continue;
6044
6045 uint64_t Offset = Layout.getFieldOffset(idx);
6046 if (Offset % 64) // Ignore doubles that are not aligned.
6047 continue;
6048
6049 // Add ((Offset - LastOffset) / 64) args of type i64.
6050 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6051 ArgList.push_back(I64);
6052
6053 // Add double type.
6054 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6055 LastOffset = Offset + 64;
6056 }
6057
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006058 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6059 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006060
6061 return llvm::StructType::get(getVMContext(), ArgList);
6062}
6063
Akira Hatanakaddd66342013-10-29 18:41:15 +00006064llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6065 uint64_t Offset) const {
6066 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006067 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006068
Akira Hatanakaddd66342013-10-29 18:41:15 +00006069 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006070}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006071
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006072ABIArgInfo
6073MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006074 Ty = useFirstFieldIfTransparentUnion(Ty);
6075
Akira Hatanaka1632af62012-01-09 19:31:25 +00006076 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006077 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006078 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006079
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006080 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6081 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006082 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6083 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006084
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006085 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006086 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006087 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006088 return ABIArgInfo::getIgnore();
6089
Mark Lacey3825e832013-10-06 01:33:34 +00006090 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006091 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006092 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006093 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006094
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006095 // If we have reached here, aggregates are passed directly by coercing to
6096 // another structure type. Padding is inserted if the offset of the
6097 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006098 ABIArgInfo ArgInfo =
6099 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6100 getPaddingType(OrigOffset, CurrOffset));
6101 ArgInfo.setInReg(true);
6102 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006103 }
6104
6105 // Treat an enum type as its underlying type.
6106 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6107 Ty = EnumTy->getDecl()->getIntegerType();
6108
Daniel Sanders5b445b32014-10-24 14:42:42 +00006109 // All integral types are promoted to the GPR width.
6110 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006111 return ABIArgInfo::getExtend();
6112
Akira Hatanakaddd66342013-10-29 18:41:15 +00006113 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006114 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006115}
6116
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006117llvm::Type*
6118MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006119 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006120 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006121
Akira Hatanakab6f74432012-02-09 18:49:26 +00006122 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006123 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006124 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6125 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006126
Akira Hatanakab6f74432012-02-09 18:49:26 +00006127 // N32/64 returns struct/classes in floating point registers if the
6128 // following conditions are met:
6129 // 1. The size of the struct/class is no larger than 128-bit.
6130 // 2. The struct/class has one or two fields all of which are floating
6131 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006132 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006133 //
6134 // Any other composite results are returned in integer registers.
6135 //
6136 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6137 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6138 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006139 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006140
Akira Hatanakab6f74432012-02-09 18:49:26 +00006141 if (!BT || !BT->isFloatingPoint())
6142 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006143
David Blaikie2d7c57e2012-04-30 02:36:29 +00006144 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006145 }
6146
6147 if (b == e)
6148 return llvm::StructType::get(getVMContext(), RTList,
6149 RD->hasAttr<PackedAttr>());
6150
6151 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006152 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006153 }
6154
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006155 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006156 return llvm::StructType::get(getVMContext(), RTList);
6157}
6158
Akira Hatanakab579fe52011-06-02 00:09:17 +00006159ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006160 uint64_t Size = getContext().getTypeSize(RetTy);
6161
Daniel Sandersed39f582014-09-04 13:28:14 +00006162 if (RetTy->isVoidType())
6163 return ABIArgInfo::getIgnore();
6164
6165 // O32 doesn't treat zero-sized structs differently from other structs.
6166 // However, N32/N64 ignores zero sized return values.
6167 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006168 return ABIArgInfo::getIgnore();
6169
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006170 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006171 if (Size <= 128) {
6172 if (RetTy->isAnyComplexType())
6173 return ABIArgInfo::getDirect();
6174
Daniel Sanderse5018b62014-09-04 15:05:39 +00006175 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006176 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006177 if (!IsO32 ||
6178 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6179 ABIArgInfo ArgInfo =
6180 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6181 ArgInfo.setInReg(true);
6182 return ArgInfo;
6183 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006184 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006185
John McCall7f416cc2015-09-08 08:05:57 +00006186 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006187 }
6188
6189 // Treat an enum type as its underlying type.
6190 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6191 RetTy = EnumTy->getDecl()->getIntegerType();
6192
6193 return (RetTy->isPromotableIntegerType() ?
6194 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6195}
6196
6197void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006198 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006199 if (!getCXXABI().classifyReturnType(FI))
6200 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006201
Eric Christopher7565e0d2015-05-29 23:09:49 +00006202 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006203 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006204
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006205 for (auto &I : FI.arguments())
6206 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006207}
6208
John McCall7f416cc2015-09-08 08:05:57 +00006209Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6210 QualType OrigTy) const {
6211 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006212
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006213 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6214 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006215 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006216 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006217 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006218 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006219 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006220 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006221 DidPromote = true;
6222 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6223 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006224 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006225
John McCall7f416cc2015-09-08 08:05:57 +00006226 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006227
John McCall7f416cc2015-09-08 08:05:57 +00006228 // The alignment of things in the argument area is never larger than
6229 // StackAlignInBytes.
6230 TyInfo.second =
6231 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6232
6233 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6234 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6235
6236 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6237 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6238
6239
6240 // If there was a promotion, "unpromote" into a temporary.
6241 // TODO: can we just use a pointer into a subset of the original slot?
6242 if (DidPromote) {
6243 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6244 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6245
6246 // Truncate down to the right width.
6247 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6248 : CGF.IntPtrTy);
6249 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6250 if (OrigTy->isPointerType())
6251 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6252
6253 CGF.Builder.CreateStore(V, Temp);
6254 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006255 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006256
John McCall7f416cc2015-09-08 08:05:57 +00006257 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006258}
6259
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006260bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6261 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006262
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006263 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6264 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6265 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006266
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006267 return false;
6268}
6269
John McCall943fae92010-05-27 06:19:26 +00006270bool
6271MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6272 llvm::Value *Address) const {
6273 // This information comes from gcc's implementation, which seems to
6274 // as canonical as it gets.
6275
John McCall943fae92010-05-27 06:19:26 +00006276 // Everything on MIPS is 4 bytes. Double-precision FP registers
6277 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006278 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006279
6280 // 0-31 are the general purpose registers, $0 - $31.
6281 // 32-63 are the floating-point registers, $f0 - $f31.
6282 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6283 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006284 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006285
6286 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6287 // They are one bit wide and ignored here.
6288
6289 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6290 // (coprocessor 1 is the FP unit)
6291 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6292 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6293 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006294 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006295 return false;
6296}
6297
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006298//===----------------------------------------------------------------------===//
6299// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006300// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006301// handling.
6302//===----------------------------------------------------------------------===//
6303
6304namespace {
6305
6306class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6307public:
6308 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6309 : DefaultTargetCodeGenInfo(CGT) {}
6310
Eric Christopher162c91c2015-06-05 22:03:00 +00006311 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006312 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006313};
6314
Eric Christopher162c91c2015-06-05 22:03:00 +00006315void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006316 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006317 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006318 if (!FD) return;
6319
6320 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006321
David Blaikiebbafb8a2012-03-11 07:00:24 +00006322 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006323 if (FD->hasAttr<OpenCLKernelAttr>()) {
6324 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006325 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006326 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6327 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006328 // Convert the reqd_work_group_size() attributes to metadata.
6329 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006330 llvm::NamedMDNode *OpenCLMetadata =
6331 M.getModule().getOrInsertNamedMetadata(
6332 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006333
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006334 SmallVector<llvm::Metadata *, 5> Operands;
6335 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006336
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006337 Operands.push_back(
6338 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6339 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6340 Operands.push_back(
6341 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6342 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6343 Operands.push_back(
6344 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6345 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006346
Eric Christopher7565e0d2015-05-29 23:09:49 +00006347 // Add a boolean constant operand for "required" (true) or "hint"
6348 // (false) for implementing the work_group_size_hint attr later.
6349 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006350 Operands.push_back(
6351 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006352 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6353 }
6354 }
6355 }
6356}
6357
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006358}
John McCall943fae92010-05-27 06:19:26 +00006359
Tony Linthicum76329bf2011-12-12 21:14:55 +00006360//===----------------------------------------------------------------------===//
6361// Hexagon ABI Implementation
6362//===----------------------------------------------------------------------===//
6363
6364namespace {
6365
6366class HexagonABIInfo : public ABIInfo {
6367
6368
6369public:
6370 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6371
6372private:
6373
6374 ABIArgInfo classifyReturnType(QualType RetTy) const;
6375 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6376
Craig Topper4f12f102014-03-12 06:41:41 +00006377 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006378
John McCall7f416cc2015-09-08 08:05:57 +00006379 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6380 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006381};
6382
6383class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6384public:
6385 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6386 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6387
Craig Topper4f12f102014-03-12 06:41:41 +00006388 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006389 return 29;
6390 }
6391};
6392
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006393}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006394
6395void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006396 if (!getCXXABI().classifyReturnType(FI))
6397 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006398 for (auto &I : FI.arguments())
6399 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006400}
6401
6402ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6403 if (!isAggregateTypeForABI(Ty)) {
6404 // Treat an enum type as its underlying type.
6405 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6406 Ty = EnumTy->getDecl()->getIntegerType();
6407
6408 return (Ty->isPromotableIntegerType() ?
6409 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6410 }
6411
6412 // Ignore empty records.
6413 if (isEmptyRecord(getContext(), Ty, true))
6414 return ABIArgInfo::getIgnore();
6415
Mark Lacey3825e832013-10-06 01:33:34 +00006416 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006417 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006418
6419 uint64_t Size = getContext().getTypeSize(Ty);
6420 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006421 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006422 // Pass in the smallest viable integer type.
6423 else if (Size > 32)
6424 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6425 else if (Size > 16)
6426 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6427 else if (Size > 8)
6428 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6429 else
6430 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6431}
6432
6433ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6434 if (RetTy->isVoidType())
6435 return ABIArgInfo::getIgnore();
6436
6437 // Large vector types should be returned via memory.
6438 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006439 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006440
6441 if (!isAggregateTypeForABI(RetTy)) {
6442 // Treat an enum type as its underlying type.
6443 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6444 RetTy = EnumTy->getDecl()->getIntegerType();
6445
6446 return (RetTy->isPromotableIntegerType() ?
6447 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6448 }
6449
Tony Linthicum76329bf2011-12-12 21:14:55 +00006450 if (isEmptyRecord(getContext(), RetTy, true))
6451 return ABIArgInfo::getIgnore();
6452
6453 // Aggregates <= 8 bytes are returned in r0; other aggregates
6454 // are returned indirectly.
6455 uint64_t Size = getContext().getTypeSize(RetTy);
6456 if (Size <= 64) {
6457 // Return in the smallest viable integer type.
6458 if (Size <= 8)
6459 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6460 if (Size <= 16)
6461 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6462 if (Size <= 32)
6463 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6464 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6465 }
6466
John McCall7f416cc2015-09-08 08:05:57 +00006467 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006468}
6469
John McCall7f416cc2015-09-08 08:05:57 +00006470Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6471 QualType Ty) const {
6472 // FIXME: Someone needs to audit that this handle alignment correctly.
6473 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6474 getContext().getTypeInfoInChars(Ty),
6475 CharUnits::fromQuantity(4),
6476 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006477}
6478
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006479//===----------------------------------------------------------------------===//
6480// AMDGPU ABI Implementation
6481//===----------------------------------------------------------------------===//
6482
6483namespace {
6484
6485class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6486public:
6487 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6488 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006489 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006490 CodeGen::CodeGenModule &M) const override;
6491};
6492
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006493}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006494
Eric Christopher162c91c2015-06-05 22:03:00 +00006495void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006496 const Decl *D,
6497 llvm::GlobalValue *GV,
6498 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006499 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006500 if (!FD)
6501 return;
6502
6503 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6504 llvm::Function *F = cast<llvm::Function>(GV);
6505 uint32_t NumVGPR = Attr->getNumVGPR();
6506 if (NumVGPR != 0)
6507 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6508 }
6509
6510 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6511 llvm::Function *F = cast<llvm::Function>(GV);
6512 unsigned NumSGPR = Attr->getNumSGPR();
6513 if (NumSGPR != 0)
6514 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6515 }
6516}
6517
Tony Linthicum76329bf2011-12-12 21:14:55 +00006518
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006519//===----------------------------------------------------------------------===//
6520// SPARC v9 ABI Implementation.
6521// Based on the SPARC Compliance Definition version 2.4.1.
6522//
6523// Function arguments a mapped to a nominal "parameter array" and promoted to
6524// registers depending on their type. Each argument occupies 8 or 16 bytes in
6525// the array, structs larger than 16 bytes are passed indirectly.
6526//
6527// One case requires special care:
6528//
6529// struct mixed {
6530// int i;
6531// float f;
6532// };
6533//
6534// When a struct mixed is passed by value, it only occupies 8 bytes in the
6535// parameter array, but the int is passed in an integer register, and the float
6536// is passed in a floating point register. This is represented as two arguments
6537// with the LLVM IR inreg attribute:
6538//
6539// declare void f(i32 inreg %i, float inreg %f)
6540//
6541// The code generator will only allocate 4 bytes from the parameter array for
6542// the inreg arguments. All other arguments are allocated a multiple of 8
6543// bytes.
6544//
6545namespace {
6546class SparcV9ABIInfo : public ABIInfo {
6547public:
6548 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6549
6550private:
6551 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006552 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006553 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6554 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006555
6556 // Coercion type builder for structs passed in registers. The coercion type
6557 // serves two purposes:
6558 //
6559 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6560 // in registers.
6561 // 2. Expose aligned floating point elements as first-level elements, so the
6562 // code generator knows to pass them in floating point registers.
6563 //
6564 // We also compute the InReg flag which indicates that the struct contains
6565 // aligned 32-bit floats.
6566 //
6567 struct CoerceBuilder {
6568 llvm::LLVMContext &Context;
6569 const llvm::DataLayout &DL;
6570 SmallVector<llvm::Type*, 8> Elems;
6571 uint64_t Size;
6572 bool InReg;
6573
6574 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6575 : Context(c), DL(dl), Size(0), InReg(false) {}
6576
6577 // Pad Elems with integers until Size is ToSize.
6578 void pad(uint64_t ToSize) {
6579 assert(ToSize >= Size && "Cannot remove elements");
6580 if (ToSize == Size)
6581 return;
6582
6583 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006584 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006585 if (Aligned > Size && Aligned <= ToSize) {
6586 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6587 Size = Aligned;
6588 }
6589
6590 // Add whole 64-bit words.
6591 while (Size + 64 <= ToSize) {
6592 Elems.push_back(llvm::Type::getInt64Ty(Context));
6593 Size += 64;
6594 }
6595
6596 // Final in-word padding.
6597 if (Size < ToSize) {
6598 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6599 Size = ToSize;
6600 }
6601 }
6602
6603 // Add a floating point element at Offset.
6604 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6605 // Unaligned floats are treated as integers.
6606 if (Offset % Bits)
6607 return;
6608 // The InReg flag is only required if there are any floats < 64 bits.
6609 if (Bits < 64)
6610 InReg = true;
6611 pad(Offset);
6612 Elems.push_back(Ty);
6613 Size = Offset + Bits;
6614 }
6615
6616 // Add a struct type to the coercion type, starting at Offset (in bits).
6617 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6618 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6619 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6620 llvm::Type *ElemTy = StrTy->getElementType(i);
6621 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6622 switch (ElemTy->getTypeID()) {
6623 case llvm::Type::StructTyID:
6624 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6625 break;
6626 case llvm::Type::FloatTyID:
6627 addFloat(ElemOffset, ElemTy, 32);
6628 break;
6629 case llvm::Type::DoubleTyID:
6630 addFloat(ElemOffset, ElemTy, 64);
6631 break;
6632 case llvm::Type::FP128TyID:
6633 addFloat(ElemOffset, ElemTy, 128);
6634 break;
6635 case llvm::Type::PointerTyID:
6636 if (ElemOffset % 64 == 0) {
6637 pad(ElemOffset);
6638 Elems.push_back(ElemTy);
6639 Size += 64;
6640 }
6641 break;
6642 default:
6643 break;
6644 }
6645 }
6646 }
6647
6648 // Check if Ty is a usable substitute for the coercion type.
6649 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006650 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006651 }
6652
6653 // Get the coercion type as a literal struct type.
6654 llvm::Type *getType() const {
6655 if (Elems.size() == 1)
6656 return Elems.front();
6657 else
6658 return llvm::StructType::get(Context, Elems);
6659 }
6660 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006661};
6662} // end anonymous namespace
6663
6664ABIArgInfo
6665SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6666 if (Ty->isVoidType())
6667 return ABIArgInfo::getIgnore();
6668
6669 uint64_t Size = getContext().getTypeSize(Ty);
6670
6671 // Anything too big to fit in registers is passed with an explicit indirect
6672 // pointer / sret pointer.
6673 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006674 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006675
6676 // Treat an enum type as its underlying type.
6677 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6678 Ty = EnumTy->getDecl()->getIntegerType();
6679
6680 // Integer types smaller than a register are extended.
6681 if (Size < 64 && Ty->isIntegerType())
6682 return ABIArgInfo::getExtend();
6683
6684 // Other non-aggregates go in registers.
6685 if (!isAggregateTypeForABI(Ty))
6686 return ABIArgInfo::getDirect();
6687
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006688 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6689 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6690 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006691 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006692
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006693 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006694 // Build a coercion type from the LLVM struct type.
6695 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6696 if (!StrTy)
6697 return ABIArgInfo::getDirect();
6698
6699 CoerceBuilder CB(getVMContext(), getDataLayout());
6700 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006701 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006702
6703 // Try to use the original type for coercion.
6704 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6705
6706 if (CB.InReg)
6707 return ABIArgInfo::getDirectInReg(CoerceTy);
6708 else
6709 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006710}
6711
John McCall7f416cc2015-09-08 08:05:57 +00006712Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6713 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006714 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6715 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6716 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6717 AI.setCoerceToType(ArgTy);
6718
John McCall7f416cc2015-09-08 08:05:57 +00006719 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006720
John McCall7f416cc2015-09-08 08:05:57 +00006721 CGBuilderTy &Builder = CGF.Builder;
6722 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6723 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6724
6725 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6726
6727 Address ArgAddr = Address::invalid();
6728 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006729 switch (AI.getKind()) {
6730 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006731 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006732 llvm_unreachable("Unsupported ABI kind for va_arg");
6733
John McCall7f416cc2015-09-08 08:05:57 +00006734 case ABIArgInfo::Extend: {
6735 Stride = SlotSize;
6736 CharUnits Offset = SlotSize - TypeInfo.first;
6737 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006738 break;
John McCall7f416cc2015-09-08 08:05:57 +00006739 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006740
John McCall7f416cc2015-09-08 08:05:57 +00006741 case ABIArgInfo::Direct: {
6742 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00006743 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006744 ArgAddr = Addr;
6745 break;
John McCall7f416cc2015-09-08 08:05:57 +00006746 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006747
6748 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006749 Stride = SlotSize;
6750 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6751 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6752 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006753 break;
6754
6755 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006756 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006757 }
6758
6759 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006760 llvm::Value *NextPtr =
6761 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6762 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006763
John McCall7f416cc2015-09-08 08:05:57 +00006764 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006765}
6766
6767void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6768 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006769 for (auto &I : FI.arguments())
6770 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006771}
6772
6773namespace {
6774class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6775public:
6776 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6777 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006778
Craig Topper4f12f102014-03-12 06:41:41 +00006779 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006780 return 14;
6781 }
6782
6783 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006784 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006785};
6786} // end anonymous namespace
6787
Roman Divackyf02c9942014-02-24 18:46:27 +00006788bool
6789SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6790 llvm::Value *Address) const {
6791 // This is calculated from the LLVM and GCC tables and verified
6792 // against gcc output. AFAIK all ABIs use the same encoding.
6793
6794 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6795
6796 llvm::IntegerType *i8 = CGF.Int8Ty;
6797 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6798 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6799
6800 // 0-31: the 8-byte general-purpose registers
6801 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6802
6803 // 32-63: f0-31, the 4-byte floating-point registers
6804 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6805
6806 // Y = 64
6807 // PSR = 65
6808 // WIM = 66
6809 // TBR = 67
6810 // PC = 68
6811 // NPC = 69
6812 // FSR = 70
6813 // CSR = 71
6814 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006815
Roman Divackyf02c9942014-02-24 18:46:27 +00006816 // 72-87: d0-15, the 8-byte floating-point registers
6817 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6818
6819 return false;
6820}
6821
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006822
Robert Lytton0e076492013-08-13 09:43:10 +00006823//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006824// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006825//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006826
Robert Lytton0e076492013-08-13 09:43:10 +00006827namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006828
6829/// A SmallStringEnc instance is used to build up the TypeString by passing
6830/// it by reference between functions that append to it.
6831typedef llvm::SmallString<128> SmallStringEnc;
6832
6833/// TypeStringCache caches the meta encodings of Types.
6834///
6835/// The reason for caching TypeStrings is two fold:
6836/// 1. To cache a type's encoding for later uses;
6837/// 2. As a means to break recursive member type inclusion.
6838///
6839/// A cache Entry can have a Status of:
6840/// NonRecursive: The type encoding is not recursive;
6841/// Recursive: The type encoding is recursive;
6842/// Incomplete: An incomplete TypeString;
6843/// IncompleteUsed: An incomplete TypeString that has been used in a
6844/// Recursive type encoding.
6845///
6846/// A NonRecursive entry will have all of its sub-members expanded as fully
6847/// as possible. Whilst it may contain types which are recursive, the type
6848/// itself is not recursive and thus its encoding may be safely used whenever
6849/// the type is encountered.
6850///
6851/// A Recursive entry will have all of its sub-members expanded as fully as
6852/// possible. The type itself is recursive and it may contain other types which
6853/// are recursive. The Recursive encoding must not be used during the expansion
6854/// of a recursive type's recursive branch. For simplicity the code uses
6855/// IncompleteCount to reject all usage of Recursive encodings for member types.
6856///
6857/// An Incomplete entry is always a RecordType and only encodes its
6858/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6859/// are placed into the cache during type expansion as a means to identify and
6860/// handle recursive inclusion of types as sub-members. If there is recursion
6861/// the entry becomes IncompleteUsed.
6862///
6863/// During the expansion of a RecordType's members:
6864///
6865/// If the cache contains a NonRecursive encoding for the member type, the
6866/// cached encoding is used;
6867///
6868/// If the cache contains a Recursive encoding for the member type, the
6869/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6870///
6871/// If the member is a RecordType, an Incomplete encoding is placed into the
6872/// cache to break potential recursive inclusion of itself as a sub-member;
6873///
6874/// Once a member RecordType has been expanded, its temporary incomplete
6875/// entry is removed from the cache. If a Recursive encoding was swapped out
6876/// it is swapped back in;
6877///
6878/// If an incomplete entry is used to expand a sub-member, the incomplete
6879/// entry is marked as IncompleteUsed. The cache keeps count of how many
6880/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6881///
6882/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6883/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6884/// Else the member is part of a recursive type and thus the recursion has
6885/// been exited too soon for the encoding to be correct for the member.
6886///
6887class TypeStringCache {
6888 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6889 struct Entry {
6890 std::string Str; // The encoded TypeString for the type.
6891 enum Status State; // Information about the encoding in 'Str'.
6892 std::string Swapped; // A temporary place holder for a Recursive encoding
6893 // during the expansion of RecordType's members.
6894 };
6895 std::map<const IdentifierInfo *, struct Entry> Map;
6896 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6897 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6898public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006899 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006900 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6901 bool removeIncomplete(const IdentifierInfo *ID);
6902 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6903 bool IsRecursive);
6904 StringRef lookupStr(const IdentifierInfo *ID);
6905};
6906
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006907/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006908/// FieldEncoding is a helper for this ordering process.
6909class FieldEncoding {
6910 bool HasName;
6911 std::string Enc;
6912public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006913 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6914 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006915 bool operator<(const FieldEncoding &rhs) const {
6916 if (HasName != rhs.HasName) return HasName;
6917 return Enc < rhs.Enc;
6918 }
6919};
6920
Robert Lytton7d1db152013-08-19 09:46:39 +00006921class XCoreABIInfo : public DefaultABIInfo {
6922public:
6923 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006924 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6925 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006926};
6927
Robert Lyttond21e2d72014-03-03 13:45:29 +00006928class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006929 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006930public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006931 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006932 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006933 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6934 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006935};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006936
Robert Lytton2d196952013-10-11 10:29:34 +00006937} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006938
John McCall7f416cc2015-09-08 08:05:57 +00006939Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6940 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006941 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006942
Robert Lytton2d196952013-10-11 10:29:34 +00006943 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006944 CharUnits SlotSize = CharUnits::fromQuantity(4);
6945 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006946
Robert Lytton2d196952013-10-11 10:29:34 +00006947 // Handle the argument.
6948 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006949 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006950 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6951 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6952 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006953 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006954
6955 Address Val = Address::invalid();
6956 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006957 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006958 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006959 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006960 llvm_unreachable("Unsupported ABI kind for va_arg");
6961 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006962 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6963 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006964 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006965 case ABIArgInfo::Extend:
6966 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006967 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6968 ArgSize = CharUnits::fromQuantity(
6969 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00006970 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006971 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006972 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006973 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6974 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6975 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006976 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006977 }
Robert Lytton2d196952013-10-11 10:29:34 +00006978
6979 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006980 if (!ArgSize.isZero()) {
6981 llvm::Value *APN =
6982 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
6983 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006984 }
John McCall7f416cc2015-09-08 08:05:57 +00006985
Robert Lytton2d196952013-10-11 10:29:34 +00006986 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006987}
Robert Lytton0e076492013-08-13 09:43:10 +00006988
Robert Lytton844aeeb2014-05-02 09:33:20 +00006989/// During the expansion of a RecordType, an incomplete TypeString is placed
6990/// into the cache as a means to identify and break recursion.
6991/// If there is a Recursive encoding in the cache, it is swapped out and will
6992/// be reinserted by removeIncomplete().
6993/// All other types of encoding should have been used rather than arriving here.
6994void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6995 std::string StubEnc) {
6996 if (!ID)
6997 return;
6998 Entry &E = Map[ID];
6999 assert( (E.Str.empty() || E.State == Recursive) &&
7000 "Incorrectly use of addIncomplete");
7001 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7002 E.Swapped.swap(E.Str); // swap out the Recursive
7003 E.Str.swap(StubEnc);
7004 E.State = Incomplete;
7005 ++IncompleteCount;
7006}
7007
7008/// Once the RecordType has been expanded, the temporary incomplete TypeString
7009/// must be removed from the cache.
7010/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7011/// Returns true if the RecordType was defined recursively.
7012bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7013 if (!ID)
7014 return false;
7015 auto I = Map.find(ID);
7016 assert(I != Map.end() && "Entry not present");
7017 Entry &E = I->second;
7018 assert( (E.State == Incomplete ||
7019 E.State == IncompleteUsed) &&
7020 "Entry must be an incomplete type");
7021 bool IsRecursive = false;
7022 if (E.State == IncompleteUsed) {
7023 // We made use of our Incomplete encoding, thus we are recursive.
7024 IsRecursive = true;
7025 --IncompleteUsedCount;
7026 }
7027 if (E.Swapped.empty())
7028 Map.erase(I);
7029 else {
7030 // Swap the Recursive back.
7031 E.Swapped.swap(E.Str);
7032 E.Swapped.clear();
7033 E.State = Recursive;
7034 }
7035 --IncompleteCount;
7036 return IsRecursive;
7037}
7038
7039/// Add the encoded TypeString to the cache only if it is NonRecursive or
7040/// Recursive (viz: all sub-members were expanded as fully as possible).
7041void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7042 bool IsRecursive) {
7043 if (!ID || IncompleteUsedCount)
7044 return; // No key or it is is an incomplete sub-type so don't add.
7045 Entry &E = Map[ID];
7046 if (IsRecursive && !E.Str.empty()) {
7047 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7048 "This is not the same Recursive entry");
7049 // The parent container was not recursive after all, so we could have used
7050 // this Recursive sub-member entry after all, but we assumed the worse when
7051 // we started viz: IncompleteCount!=0.
7052 return;
7053 }
7054 assert(E.Str.empty() && "Entry already present");
7055 E.Str = Str.str();
7056 E.State = IsRecursive? Recursive : NonRecursive;
7057}
7058
7059/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7060/// are recursively expanding a type (IncompleteCount != 0) and the cached
7061/// encoding is Recursive, return an empty StringRef.
7062StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7063 if (!ID)
7064 return StringRef(); // We have no key.
7065 auto I = Map.find(ID);
7066 if (I == Map.end())
7067 return StringRef(); // We have no encoding.
7068 Entry &E = I->second;
7069 if (E.State == Recursive && IncompleteCount)
7070 return StringRef(); // We don't use Recursive encodings for member types.
7071
7072 if (E.State == Incomplete) {
7073 // The incomplete type is being used to break out of recursion.
7074 E.State = IncompleteUsed;
7075 ++IncompleteUsedCount;
7076 }
7077 return E.Str.c_str();
7078}
7079
7080/// The XCore ABI includes a type information section that communicates symbol
7081/// type information to the linker. The linker uses this information to verify
7082/// safety/correctness of things such as array bound and pointers et al.
7083/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7084/// This type information (TypeString) is emitted into meta data for all global
7085/// symbols: definitions, declarations, functions & variables.
7086///
7087/// The TypeString carries type, qualifier, name, size & value details.
7088/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007089/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007090/// The output is tested by test/CodeGen/xcore-stringtype.c.
7091///
7092static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7093 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7094
7095/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7096void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7097 CodeGen::CodeGenModule &CGM) const {
7098 SmallStringEnc Enc;
7099 if (getTypeString(Enc, D, CGM, TSC)) {
7100 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007101 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7102 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007103 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7104 llvm::NamedMDNode *MD =
7105 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7106 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7107 }
7108}
7109
7110static bool appendType(SmallStringEnc &Enc, QualType QType,
7111 const CodeGen::CodeGenModule &CGM,
7112 TypeStringCache &TSC);
7113
7114/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007115/// Builds a SmallVector containing the encoded field types in declaration
7116/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007117static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7118 const RecordDecl *RD,
7119 const CodeGen::CodeGenModule &CGM,
7120 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007121 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007122 SmallStringEnc Enc;
7123 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007124 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007125 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007126 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007127 Enc += "b(";
7128 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007129 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007130 Enc += ':';
7131 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007132 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007133 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007134 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007135 Enc += ')';
7136 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007137 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007138 }
7139 return true;
7140}
7141
7142/// Appends structure and union types to Enc and adds encoding to cache.
7143/// Recursively calls appendType (via extractFieldType) for each field.
7144/// Union types have their fields ordered according to the ABI.
7145static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7146 const CodeGen::CodeGenModule &CGM,
7147 TypeStringCache &TSC, const IdentifierInfo *ID) {
7148 // Append the cached TypeString if we have one.
7149 StringRef TypeString = TSC.lookupStr(ID);
7150 if (!TypeString.empty()) {
7151 Enc += TypeString;
7152 return true;
7153 }
7154
7155 // Start to emit an incomplete TypeString.
7156 size_t Start = Enc.size();
7157 Enc += (RT->isUnionType()? 'u' : 's');
7158 Enc += '(';
7159 if (ID)
7160 Enc += ID->getName();
7161 Enc += "){";
7162
7163 // We collect all encoded fields and order as necessary.
7164 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007165 const RecordDecl *RD = RT->getDecl()->getDefinition();
7166 if (RD && !RD->field_empty()) {
7167 // An incomplete TypeString stub is placed in the cache for this RecordType
7168 // so that recursive calls to this RecordType will use it whilst building a
7169 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007170 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007171 std::string StubEnc(Enc.substr(Start).str());
7172 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7173 TSC.addIncomplete(ID, std::move(StubEnc));
7174 if (!extractFieldType(FE, RD, CGM, TSC)) {
7175 (void) TSC.removeIncomplete(ID);
7176 return false;
7177 }
7178 IsRecursive = TSC.removeIncomplete(ID);
7179 // The ABI requires unions to be sorted but not structures.
7180 // See FieldEncoding::operator< for sort algorithm.
7181 if (RT->isUnionType())
7182 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007183 // We can now complete the TypeString.
7184 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007185 for (unsigned I = 0; I != E; ++I) {
7186 if (I)
7187 Enc += ',';
7188 Enc += FE[I].str();
7189 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007190 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007191 Enc += '}';
7192 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7193 return true;
7194}
7195
7196/// Appends enum types to Enc and adds the encoding to the cache.
7197static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7198 TypeStringCache &TSC,
7199 const IdentifierInfo *ID) {
7200 // Append the cached TypeString if we have one.
7201 StringRef TypeString = TSC.lookupStr(ID);
7202 if (!TypeString.empty()) {
7203 Enc += TypeString;
7204 return true;
7205 }
7206
7207 size_t Start = Enc.size();
7208 Enc += "e(";
7209 if (ID)
7210 Enc += ID->getName();
7211 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007212
7213 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007214 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007215 SmallVector<FieldEncoding, 16> FE;
7216 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7217 ++I) {
7218 SmallStringEnc EnumEnc;
7219 EnumEnc += "m(";
7220 EnumEnc += I->getName();
7221 EnumEnc += "){";
7222 I->getInitVal().toString(EnumEnc);
7223 EnumEnc += '}';
7224 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7225 }
7226 std::sort(FE.begin(), FE.end());
7227 unsigned E = FE.size();
7228 for (unsigned I = 0; I != E; ++I) {
7229 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007230 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007231 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007232 }
7233 }
7234 Enc += '}';
7235 TSC.addIfComplete(ID, Enc.substr(Start), false);
7236 return true;
7237}
7238
7239/// Appends type's qualifier to Enc.
7240/// This is done prior to appending the type's encoding.
7241static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7242 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007243 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007244 int Lookup = 0;
7245 if (QT.isConstQualified())
7246 Lookup += 1<<0;
7247 if (QT.isRestrictQualified())
7248 Lookup += 1<<1;
7249 if (QT.isVolatileQualified())
7250 Lookup += 1<<2;
7251 Enc += Table[Lookup];
7252}
7253
7254/// Appends built-in types to Enc.
7255static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7256 const char *EncType;
7257 switch (BT->getKind()) {
7258 case BuiltinType::Void:
7259 EncType = "0";
7260 break;
7261 case BuiltinType::Bool:
7262 EncType = "b";
7263 break;
7264 case BuiltinType::Char_U:
7265 EncType = "uc";
7266 break;
7267 case BuiltinType::UChar:
7268 EncType = "uc";
7269 break;
7270 case BuiltinType::SChar:
7271 EncType = "sc";
7272 break;
7273 case BuiltinType::UShort:
7274 EncType = "us";
7275 break;
7276 case BuiltinType::Short:
7277 EncType = "ss";
7278 break;
7279 case BuiltinType::UInt:
7280 EncType = "ui";
7281 break;
7282 case BuiltinType::Int:
7283 EncType = "si";
7284 break;
7285 case BuiltinType::ULong:
7286 EncType = "ul";
7287 break;
7288 case BuiltinType::Long:
7289 EncType = "sl";
7290 break;
7291 case BuiltinType::ULongLong:
7292 EncType = "ull";
7293 break;
7294 case BuiltinType::LongLong:
7295 EncType = "sll";
7296 break;
7297 case BuiltinType::Float:
7298 EncType = "ft";
7299 break;
7300 case BuiltinType::Double:
7301 EncType = "d";
7302 break;
7303 case BuiltinType::LongDouble:
7304 EncType = "ld";
7305 break;
7306 default:
7307 return false;
7308 }
7309 Enc += EncType;
7310 return true;
7311}
7312
7313/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7314static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7315 const CodeGen::CodeGenModule &CGM,
7316 TypeStringCache &TSC) {
7317 Enc += "p(";
7318 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7319 return false;
7320 Enc += ')';
7321 return true;
7322}
7323
7324/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007325static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7326 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007327 const CodeGen::CodeGenModule &CGM,
7328 TypeStringCache &TSC, StringRef NoSizeEnc) {
7329 if (AT->getSizeModifier() != ArrayType::Normal)
7330 return false;
7331 Enc += "a(";
7332 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7333 CAT->getSize().toStringUnsigned(Enc);
7334 else
7335 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7336 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007337 // The Qualifiers should be attached to the type rather than the array.
7338 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007339 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7340 return false;
7341 Enc += ')';
7342 return true;
7343}
7344
7345/// Appends a function encoding to Enc, calling appendType for the return type
7346/// and the arguments.
7347static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7348 const CodeGen::CodeGenModule &CGM,
7349 TypeStringCache &TSC) {
7350 Enc += "f{";
7351 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7352 return false;
7353 Enc += "}(";
7354 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7355 // N.B. we are only interested in the adjusted param types.
7356 auto I = FPT->param_type_begin();
7357 auto E = FPT->param_type_end();
7358 if (I != E) {
7359 do {
7360 if (!appendType(Enc, *I, CGM, TSC))
7361 return false;
7362 ++I;
7363 if (I != E)
7364 Enc += ',';
7365 } while (I != E);
7366 if (FPT->isVariadic())
7367 Enc += ",va";
7368 } else {
7369 if (FPT->isVariadic())
7370 Enc += "va";
7371 else
7372 Enc += '0';
7373 }
7374 }
7375 Enc += ')';
7376 return true;
7377}
7378
7379/// Handles the type's qualifier before dispatching a call to handle specific
7380/// type encodings.
7381static bool appendType(SmallStringEnc &Enc, QualType QType,
7382 const CodeGen::CodeGenModule &CGM,
7383 TypeStringCache &TSC) {
7384
7385 QualType QT = QType.getCanonicalType();
7386
Robert Lytton6adb20f2014-06-05 09:06:21 +00007387 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7388 // The Qualifiers should be attached to the type rather than the array.
7389 // Thus we don't call appendQualifier() here.
7390 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7391
Robert Lytton844aeeb2014-05-02 09:33:20 +00007392 appendQualifier(Enc, QT);
7393
7394 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7395 return appendBuiltinType(Enc, BT);
7396
Robert Lytton844aeeb2014-05-02 09:33:20 +00007397 if (const PointerType *PT = QT->getAs<PointerType>())
7398 return appendPointerType(Enc, PT, CGM, TSC);
7399
7400 if (const EnumType *ET = QT->getAs<EnumType>())
7401 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7402
7403 if (const RecordType *RT = QT->getAsStructureType())
7404 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7405
7406 if (const RecordType *RT = QT->getAsUnionType())
7407 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7408
7409 if (const FunctionType *FT = QT->getAs<FunctionType>())
7410 return appendFunctionType(Enc, FT, CGM, TSC);
7411
7412 return false;
7413}
7414
7415static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7416 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7417 if (!D)
7418 return false;
7419
7420 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7421 if (FD->getLanguageLinkage() != CLanguageLinkage)
7422 return false;
7423 return appendType(Enc, FD->getType(), CGM, TSC);
7424 }
7425
7426 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7427 if (VD->getLanguageLinkage() != CLanguageLinkage)
7428 return false;
7429 QualType QT = VD->getType().getCanonicalType();
7430 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7431 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007432 // The Qualifiers should be attached to the type rather than the array.
7433 // Thus we don't call appendQualifier() here.
7434 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007435 }
7436 return appendType(Enc, QT, CGM, TSC);
7437 }
7438 return false;
7439}
7440
7441
Robert Lytton0e076492013-08-13 09:43:10 +00007442//===----------------------------------------------------------------------===//
7443// Driver code
7444//===----------------------------------------------------------------------===//
7445
Rafael Espindola9f834732014-09-19 01:54:22 +00007446const llvm::Triple &CodeGenModule::getTriple() const {
7447 return getTarget().getTriple();
7448}
7449
7450bool CodeGenModule::supportsCOMDAT() const {
7451 return !getTriple().isOSBinFormatMachO();
7452}
7453
Chris Lattner2b037972010-07-29 02:01:43 +00007454const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007455 if (TheTargetCodeGenInfo)
7456 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007457
John McCallc8e01702013-04-16 22:48:15 +00007458 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007459 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007460 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007461 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007462
Derek Schuff09338a22012-09-06 17:37:28 +00007463 case llvm::Triple::le32:
7464 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007465 case llvm::Triple::mips:
7466 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007467 if (Triple.getOS() == llvm::Triple::NaCl)
7468 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007469 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7470
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007471 case llvm::Triple::mips64:
7472 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007473 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7474
Tim Northover25e8a672014-05-24 12:51:25 +00007475 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007476 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007477 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007478 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007479 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007480
Tim Northover573cbee2014-05-24 12:52:07 +00007481 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007482 }
7483
Dan Gohmanc2853072015-09-03 22:51:53 +00007484 case llvm::Triple::wasm32:
7485 case llvm::Triple::wasm64:
7486 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7487
Daniel Dunbard59655c2009-09-12 00:59:49 +00007488 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007489 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007490 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007491 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007492 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007493 if (Triple.getOS() == llvm::Triple::Win32) {
7494 TheTargetCodeGenInfo =
7495 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7496 return *TheTargetCodeGenInfo;
7497 }
7498
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007499 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Tim Northover5627d392015-10-30 16:30:45 +00007500 StringRef ABIStr = getTarget().getABI();
7501 if (ABIStr == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007502 Kind = ARMABIInfo::APCS;
Tim Northover5627d392015-10-30 16:30:45 +00007503 else if (ABIStr == "aapcs16")
7504 Kind = ARMABIInfo::AAPCS16_VFP;
David Tweed8f676532012-10-25 13:33:01 +00007505 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007506 (CodeGenOpts.FloatABI != "soft" &&
7507 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007508 Kind = ARMABIInfo::AAPCS_VFP;
7509
Derek Schuff71658bd2015-01-29 00:47:04 +00007510 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007511 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007512
John McCallea8d8bb2010-03-11 00:10:12 +00007513 case llvm::Triple::ppc:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00007514 return *(TheTargetCodeGenInfo =
7515 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007516 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007517 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007518 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007519 if (getTarget().getABI() == "elfv2")
7520 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007521 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007522
Ulrich Weigandb7122372014-07-21 00:48:09 +00007523 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007524 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007525 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007526 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007527 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007528 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007529 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007530 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007531 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007532 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007533
Ulrich Weigandb7122372014-07-21 00:48:09 +00007534 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007535 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007536 }
John McCallea8d8bb2010-03-11 00:10:12 +00007537
Peter Collingbournec947aae2012-05-20 23:28:41 +00007538 case llvm::Triple::nvptx:
7539 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007540 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007541
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007542 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007543 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007544
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007545 case llvm::Triple::systemz: {
7546 bool HasVector = getTarget().getABI() == "vector";
7547 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7548 HasVector));
7549 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007550
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007551 case llvm::Triple::tce:
7552 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7553
Eli Friedman33465822011-07-08 23:31:17 +00007554 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007555 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007556 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007557 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007558 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007559
John McCall1fe2a8c2013-06-18 02:46:29 +00007560 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007561 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007562 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Eric Christopher7565e0d2015-05-29 23:09:49 +00007563 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007564 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007565 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007566 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00007567 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7568 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007569 }
Eli Friedman33465822011-07-08 23:31:17 +00007570 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007571
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007572 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007573 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007574 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7575 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007576 X86AVXABILevel::None);
7577
Chris Lattner04dc9572010-08-31 16:44:54 +00007578 switch (Triple.getOS()) {
7579 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007580 return *(TheTargetCodeGenInfo =
7581 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007582 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007583 return *(TheTargetCodeGenInfo =
7584 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007585 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007586 return *(TheTargetCodeGenInfo =
7587 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007588 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007589 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007590 case llvm::Triple::hexagon:
7591 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007592 case llvm::Triple::r600:
7593 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007594 case llvm::Triple::amdgcn:
7595 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007596 case llvm::Triple::sparcv9:
7597 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007598 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007599 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007600 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007601}