blob: 7a122772a490488ebaa67c1fb3475d68a930196c [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
Nirav Dave9a8f97e2016-02-22 16:48:42 +0000120bool ABIInfo:: isAndroid() const { return getTarget().getTriple().isAndroid(); }
121
Reid Klecknere9f6a712014-10-31 17:10:41 +0000122bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
123 return false;
124}
125
126bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
127 uint64_t Members) const {
128 return false;
129}
130
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000131bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
132 return false;
133}
134
Yaron Kerencdae9412016-01-29 19:38:18 +0000135LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000136 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000137 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000138 switch (TheKind) {
139 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000140 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000141 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000142 Ty->print(OS);
143 else
144 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000145 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000146 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000147 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000148 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000149 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000150 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000151 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000152 case InAlloca:
153 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
154 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000155 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000156 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000157 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000158 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000159 break;
160 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000161 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000162 break;
163 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000164 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000165}
166
Petar Jovanovic402257b2015-12-04 00:26:47 +0000167// Dynamically round a pointer up to a multiple of the given alignment.
168static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
169 llvm::Value *Ptr,
170 CharUnits Align) {
171 llvm::Value *PtrAsInt = Ptr;
172 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
173 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
174 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
175 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
176 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
177 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
178 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
179 Ptr->getType(),
180 Ptr->getName() + ".aligned");
181 return PtrAsInt;
182}
183
John McCall7f416cc2015-09-08 08:05:57 +0000184/// Emit va_arg for a platform using the common void* representation,
185/// where arguments are simply emitted in an array of slots on the stack.
186///
187/// This version implements the core direct-value passing rules.
188///
189/// \param SlotSize - The size and alignment of a stack slot.
190/// Each argument will be allocated to a multiple of this number of
191/// slots, and all the slots will be aligned to this value.
192/// \param AllowHigherAlign - The slot alignment is not a cap;
193/// an argument type with an alignment greater than the slot size
194/// will be emitted on a higher-alignment address, potentially
195/// leaving one or more empty slots behind as padding. If this
196/// is false, the returned address might be less-aligned than
197/// DirectAlign.
198static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
199 Address VAListAddr,
200 llvm::Type *DirectTy,
201 CharUnits DirectSize,
202 CharUnits DirectAlign,
203 CharUnits SlotSize,
204 bool AllowHigherAlign) {
205 // Cast the element type to i8* if necessary. Some platforms define
206 // va_list as a struct containing an i8* instead of just an i8*.
207 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
208 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
209
210 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
211
212 // If the CC aligns values higher than the slot size, do so if needed.
213 Address Addr = Address::invalid();
214 if (AllowHigherAlign && DirectAlign > SlotSize) {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000215 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
216 DirectAlign);
John McCall7f416cc2015-09-08 08:05:57 +0000217 } else {
Petar Jovanovic402257b2015-12-04 00:26:47 +0000218 Addr = Address(Ptr, SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000219 }
220
221 // Advance the pointer past the argument, then store that back.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000222 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
John McCall7f416cc2015-09-08 08:05:57 +0000223 llvm::Value *NextPtr =
224 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
225 "argp.next");
226 CGF.Builder.CreateStore(NextPtr, VAListAddr);
227
228 // If the argument is smaller than a slot, and this is a big-endian
229 // target, the argument will be right-adjusted in its slot.
230 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
231 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
232 }
233
234 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
235 return Addr;
236}
237
238/// Emit va_arg for a platform using the common void* representation,
239/// where arguments are simply emitted in an array of slots on the stack.
240///
241/// \param IsIndirect - Values of this type are passed indirectly.
242/// \param ValueInfo - The size and alignment of this type, generally
243/// computed with getContext().getTypeInfoInChars(ValueTy).
244/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
245/// Each argument will be allocated to a multiple of this number of
246/// slots, and all the slots will be aligned to this value.
247/// \param AllowHigherAlign - The slot alignment is not a cap;
248/// an argument type with an alignment greater than the slot size
249/// will be emitted on a higher-alignment address, potentially
250/// leaving one or more empty slots behind as padding.
251static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
252 QualType ValueTy, bool IsIndirect,
253 std::pair<CharUnits, CharUnits> ValueInfo,
254 CharUnits SlotSizeAndAlign,
255 bool AllowHigherAlign) {
256 // The size and alignment of the value that was passed directly.
257 CharUnits DirectSize, DirectAlign;
258 if (IsIndirect) {
259 DirectSize = CGF.getPointerSize();
260 DirectAlign = CGF.getPointerAlign();
261 } else {
262 DirectSize = ValueInfo.first;
263 DirectAlign = ValueInfo.second;
264 }
265
266 // Cast the address we've calculated to the right type.
267 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
268 if (IsIndirect)
269 DirectTy = DirectTy->getPointerTo(0);
270
271 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
272 DirectSize, DirectAlign,
273 SlotSizeAndAlign,
274 AllowHigherAlign);
275
276 if (IsIndirect) {
277 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
278 }
279
280 return Addr;
281
282}
283
284static Address emitMergePHI(CodeGenFunction &CGF,
285 Address Addr1, llvm::BasicBlock *Block1,
286 Address Addr2, llvm::BasicBlock *Block2,
287 const llvm::Twine &Name = "") {
288 assert(Addr1.getType() == Addr2.getType());
289 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
290 PHI->addIncoming(Addr1.getPointer(), Block1);
291 PHI->addIncoming(Addr2.getPointer(), Block2);
292 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
293 return Address(PHI, Align);
294}
295
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000296TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
297
John McCall3480ef22011-08-30 01:42:09 +0000298// If someone can figure out a general rule for this, that would be great.
299// It's probably just doomed to be platform-dependent, though.
300unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
301 // Verified for:
302 // x86-64 FreeBSD, Linux, Darwin
303 // x86-32 FreeBSD, Linux, Darwin
304 // PowerPC Linux, Darwin
305 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000306 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000307 return 32;
308}
309
John McCalla729c622012-02-17 03:33:10 +0000310bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
311 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000312 // The following conventions are known to require this to be false:
313 // x86_stdcall
314 // MIPS
315 // For everything else, we just prefer false unless we opt out.
316 return false;
317}
318
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000319void
320TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
321 llvm::SmallString<24> &Opt) const {
322 // This assumes the user is passing a library name like "rt" instead of a
323 // filename like "librt.a/so", and that they don't care whether it's static or
324 // dynamic.
325 Opt = "-l";
326 Opt += Lib;
327}
328
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000329static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000330
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000331/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000332/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000333static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
334 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000335 if (FD->isUnnamedBitfield())
336 return true;
337
338 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000339
Eli Friedman0b3f2012011-11-18 03:47:20 +0000340 // Constant arrays of empty records count as empty, strip them off.
341 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000342 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000343 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
344 if (AT->getSize() == 0)
345 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000346 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000347 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000348
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000349 const RecordType *RT = FT->getAs<RecordType>();
350 if (!RT)
351 return false;
352
353 // C++ record fields are never empty, at least in the Itanium ABI.
354 //
355 // FIXME: We should use a predicate for whether this behavior is true in the
356 // current ABI.
357 if (isa<CXXRecordDecl>(RT->getDecl()))
358 return false;
359
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000360 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000361}
362
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000363/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000364/// fields. Note that a structure with a flexible array member is not
365/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000366static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000367 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000368 if (!RT)
Denis Zobnin380b2242016-02-11 11:26:03 +0000369 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000370 const RecordDecl *RD = RT->getDecl();
371 if (RD->hasFlexibleArrayMember())
372 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000373
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000374 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000375 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000376 for (const auto &I : CXXRD->bases())
377 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000378 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000379
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000380 for (const auto *I : RD->fields())
381 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000382 return false;
383 return true;
384}
385
386/// isSingleElementStruct - Determine if a structure is a "single
387/// element struct", i.e. it has exactly one non-empty field or
388/// exactly one field which is itself a single element
389/// struct. Structures with flexible array members are never
390/// considered single element structs.
391///
392/// \return The field declaration for the single non-empty field, if
393/// it exists.
394static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000395 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000396 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000397 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000398
399 const RecordDecl *RD = RT->getDecl();
400 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000401 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000402
Craig Topper8a13c412014-05-21 05:09:00 +0000403 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000404
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000405 // If this is a C++ record, check the bases first.
406 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000407 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000408 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000409 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000410 continue;
411
412 // If we already found an element then this isn't a single-element struct.
413 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000414 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000415
416 // If this is non-empty and not a single element struct, the composite
417 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000418 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000419 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000420 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000421 }
422 }
423
424 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000425 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000426 QualType FT = FD->getType();
427
428 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000429 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000430 continue;
431
432 // If we already found an element then this isn't a single-element
433 // struct.
434 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000435 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000436
437 // Treat single element arrays as the element.
438 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
439 if (AT->getSize().getZExtValue() != 1)
440 break;
441 FT = AT->getElementType();
442 }
443
John McCalla1dee5302010-08-22 10:59:02 +0000444 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000445 Found = FT.getTypePtr();
446 } else {
447 Found = isSingleElementStruct(FT, Context);
448 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000449 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000450 }
451 }
452
Eli Friedmanee945342011-11-18 01:25:50 +0000453 // We don't consider a struct a single-element struct if it has
454 // padding beyond the element type.
455 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000456 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000457
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000458 return Found;
459}
460
461static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000462 // Treat complex types as the element type.
463 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
464 Ty = CTy->getElementType();
465
466 // Check for a type which we know has a simple scalar argument-passing
467 // convention without any padding. (We're specifically looking for 32
468 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000469 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000470 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000471 return false;
472
473 uint64_t Size = Context.getTypeSize(Ty);
474 return Size == 32 || Size == 64;
475}
476
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000477/// canExpandIndirectArgument - Test whether an argument type which is to be
478/// passed indirectly (on the stack) would have the equivalent layout if it was
479/// expanded into separate arguments. If so, we prefer to do the latter to avoid
480/// inhibiting optimizations.
481///
482// FIXME: This predicate is missing many cases, currently it just follows
483// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
484// should probably make this smarter, or better yet make the LLVM backend
485// capable of handling it.
486static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
487 // We can only expand structure types.
488 const RecordType *RT = Ty->getAs<RecordType>();
489 if (!RT)
490 return false;
491
492 // We can only expand (C) structures.
493 //
494 // FIXME: This needs to be generalized to handle classes as well.
495 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000496 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000497 return false;
498
Manman Ren27382782015-04-03 18:10:29 +0000499 // We try to expand CLike CXXRecordDecl.
500 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
501 if (!CXXRD->isCLike())
502 return false;
503 }
504
Eli Friedmane5c85622011-11-18 01:32:26 +0000505 uint64_t Size = 0;
506
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000507 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000508 if (!is32Or64BitBasicType(FD->getType(), Context))
509 return false;
510
511 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
512 // how to expand them yet, and the predicate for telling if a bitfield still
513 // counts as "basic" is more complicated than what we were doing previously.
514 if (FD->isBitField())
515 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000516
517 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000518 }
519
Eli Friedmane5c85622011-11-18 01:32:26 +0000520 // Make sure there are not any holes in the struct.
521 if (Size != Context.getTypeSize(Ty))
522 return false;
523
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000524 return true;
525}
526
527namespace {
528/// DefaultABIInfo - The default implementation for ABI specific
529/// details. This implementation provides information which results in
530/// self-consistent and sensible LLVM IR generation, but does not
531/// conform to any particular ABI.
532class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000533public:
534 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000535
Chris Lattner458b2aa2010-07-29 02:16:43 +0000536 ABIArgInfo classifyReturnType(QualType RetTy) const;
537 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000538
Craig Topper4f12f102014-03-12 06:41:41 +0000539 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000540 if (!getCXXABI().classifyReturnType(FI))
541 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000542 for (auto &I : FI.arguments())
543 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000544 }
545
John McCall7f416cc2015-09-08 08:05:57 +0000546 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
547 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000548};
549
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000550class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
551public:
Chris Lattner2b037972010-07-29 02:01:43 +0000552 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
553 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000554};
555
John McCall7f416cc2015-09-08 08:05:57 +0000556Address DefaultABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
557 QualType Ty) const {
558 return Address::invalid();
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000559}
560
Chris Lattner458b2aa2010-07-29 02:16:43 +0000561ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000562 Ty = useFirstFieldIfTransparentUnion(Ty);
563
564 if (isAggregateTypeForABI(Ty)) {
565 // Records with non-trivial destructors/copy-constructors should not be
566 // passed by value.
567 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000568 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000569
John McCall7f416cc2015-09-08 08:05:57 +0000570 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000571 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000572
Chris Lattner9723d6c2010-03-11 18:19:55 +0000573 // Treat an enum type as its underlying type.
574 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
575 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000576
Chris Lattner9723d6c2010-03-11 18:19:55 +0000577 return (Ty->isPromotableIntegerType() ?
578 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000579}
580
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000581ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
582 if (RetTy->isVoidType())
583 return ABIArgInfo::getIgnore();
584
585 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000586 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000587
588 // Treat an enum type as its underlying type.
589 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
590 RetTy = EnumTy->getDecl()->getIntegerType();
591
592 return (RetTy->isPromotableIntegerType() ?
593 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
594}
595
Derek Schuff09338a22012-09-06 17:37:28 +0000596//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000597// WebAssembly ABI Implementation
598//
599// This is a very simple ABI that relies a lot on DefaultABIInfo.
600//===----------------------------------------------------------------------===//
601
602class WebAssemblyABIInfo final : public DefaultABIInfo {
603public:
604 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
605 : DefaultABIInfo(CGT) {}
606
607private:
608 ABIArgInfo classifyReturnType(QualType RetTy) const;
609 ABIArgInfo classifyArgumentType(QualType Ty) const;
610
611 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
612 // non-virtual, but computeInfo is virtual, so we overload that.
613 void computeInfo(CGFunctionInfo &FI) const override {
614 if (!getCXXABI().classifyReturnType(FI))
615 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
616 for (auto &Arg : FI.arguments())
617 Arg.info = classifyArgumentType(Arg.type);
618 }
619};
620
621class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
622public:
623 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
624 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
625};
626
627/// \brief Classify argument of given type \p Ty.
628ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
629 Ty = useFirstFieldIfTransparentUnion(Ty);
630
631 if (isAggregateTypeForABI(Ty)) {
632 // Records with non-trivial destructors/copy-constructors should not be
633 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000634 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000635 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000636 // Ignore empty structs/unions.
637 if (isEmptyRecord(getContext(), Ty, true))
638 return ABIArgInfo::getIgnore();
639 // Lower single-element structs to just pass a regular value. TODO: We
640 // could do reasonable-size multiple-element structs too, using getExpand(),
641 // though watch out for things like bitfields.
642 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
643 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000644 }
645
646 // Otherwise just do the default thing.
647 return DefaultABIInfo::classifyArgumentType(Ty);
648}
649
650ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
651 if (isAggregateTypeForABI(RetTy)) {
652 // Records with non-trivial destructors/copy-constructors should not be
653 // returned by value.
654 if (!getRecordArgABI(RetTy, getCXXABI())) {
655 // Ignore empty structs/unions.
656 if (isEmptyRecord(getContext(), RetTy, true))
657 return ABIArgInfo::getIgnore();
658 // Lower single-element structs to just return a regular value. TODO: We
659 // could do reasonable-size multiple-element structs too, using
660 // ABIArgInfo::getDirect().
661 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
662 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
663 }
664 }
665
666 // Otherwise just do the default thing.
667 return DefaultABIInfo::classifyReturnType(RetTy);
668}
669
670//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000671// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000672//
673// This is a simplified version of the x86_32 ABI. Arguments and return values
674// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000675//===----------------------------------------------------------------------===//
676
677class PNaClABIInfo : public ABIInfo {
678 public:
679 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
680
681 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000682 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000683
Craig Topper4f12f102014-03-12 06:41:41 +0000684 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000685 Address EmitVAArg(CodeGenFunction &CGF,
686 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000687};
688
689class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
690 public:
691 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
692 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
693};
694
695void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000696 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000697 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
698
Reid Kleckner40ca9132014-05-13 22:05:45 +0000699 for (auto &I : FI.arguments())
700 I.info = classifyArgumentType(I.type);
701}
Derek Schuff09338a22012-09-06 17:37:28 +0000702
John McCall7f416cc2015-09-08 08:05:57 +0000703Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
704 QualType Ty) const {
705 return Address::invalid();
Derek Schuff09338a22012-09-06 17:37:28 +0000706}
707
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000708/// \brief Classify argument of given type \p Ty.
709ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000710 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000711 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000712 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
713 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000714 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
715 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000716 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000717 } else if (Ty->isFloatingType()) {
718 // Floating-point types don't go inreg.
719 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000720 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000721
722 return (Ty->isPromotableIntegerType() ?
723 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000724}
725
726ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
727 if (RetTy->isVoidType())
728 return ABIArgInfo::getIgnore();
729
Eli Benderskye20dad62013-04-04 22:49:35 +0000730 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000731 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000732 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000733
734 // Treat an enum type as its underlying type.
735 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
736 RetTy = EnumTy->getDecl()->getIntegerType();
737
738 return (RetTy->isPromotableIntegerType() ?
739 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
740}
741
Chad Rosier651c1832013-03-25 21:00:27 +0000742/// IsX86_MMXType - Return true if this is an MMX type.
743bool IsX86_MMXType(llvm::Type *IRType) {
744 // 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 +0000745 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
746 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
747 IRType->getScalarSizeInBits() != 64;
748}
749
Jay Foad7c57be32011-07-11 09:56:20 +0000750static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000751 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000752 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000753 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
754 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
755 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000756 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000757 }
758
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000759 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000760 }
761
762 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000763 return Ty;
764}
765
Reid Kleckner80944df2014-10-31 22:00:51 +0000766/// Returns true if this type can be passed in SSE registers with the
767/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
768static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
769 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
770 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
771 return true;
772 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
773 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
774 // registers specially.
775 unsigned VecSize = Context.getTypeSize(VT);
776 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
777 return true;
778 }
779 return false;
780}
781
782/// Returns true if this aggregate is small enough to be passed in SSE registers
783/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
784static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
785 return NumMembers <= 4;
786}
787
Chris Lattner0cf24192010-06-28 20:05:43 +0000788//===----------------------------------------------------------------------===//
789// X86-32 ABI Implementation
790//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000791
Reid Kleckner661f35b2014-01-18 01:12:41 +0000792/// \brief Similar to llvm::CCState, but for Clang.
793struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000794 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000795
796 unsigned CC;
797 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000798 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000799};
800
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000801/// X86_32ABIInfo - The X86-32 ABI information.
802class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000803 enum Class {
804 Integer,
805 Float
806 };
807
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000808 static const unsigned MinABIStackAlignInBytes = 4;
809
David Chisnallde3a0692009-08-17 23:08:21 +0000810 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000811 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000812 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000813 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000814 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000815 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000816
817 static bool isRegisterSize(unsigned Size) {
818 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
819 }
820
Reid Kleckner80944df2014-10-31 22:00:51 +0000821 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
822 // FIXME: Assumes vectorcall is in use.
823 return isX86VectorTypeForVectorCall(getContext(), Ty);
824 }
825
826 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
827 uint64_t NumMembers) const override {
828 // FIXME: Assumes vectorcall is in use.
829 return isX86VectorCallAggregateSmallEnough(NumMembers);
830 }
831
Reid Kleckner40ca9132014-05-13 22:05:45 +0000832 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000833
Daniel Dunbar557893d2010-04-21 19:10:51 +0000834 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
835 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000836 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
837
John McCall7f416cc2015-09-08 08:05:57 +0000838 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000839
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000840 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000841 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000842
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000843 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000844 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000845 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +0000846 /// \brief Updates the number of available free registers, returns
847 /// true if any registers were allocated.
848 bool updateFreeRegs(QualType Ty, CCState &State) const;
849
850 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
851 bool &NeedsPadding) const;
852 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000853
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000854 /// \brief Rewrite the function info so that all memory arguments use
855 /// inalloca.
856 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
857
858 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000859 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000860 QualType Type) const;
861
Rafael Espindola75419dc2012-07-23 23:30:29 +0000862public:
863
Craig Topper4f12f102014-03-12 06:41:41 +0000864 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000865 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
866 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000867
Michael Kupersteindc745202015-10-19 07:52:25 +0000868 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
869 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000870 unsigned NumRegisterParameters, bool SoftFloatABI)
Michael Kupersteindc745202015-10-19 07:52:25 +0000871 : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
872 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
873 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000874 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000875 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000876 DefaultNumRegisterParameters(NumRegisterParameters) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000877};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000878
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000879class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
880public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000881 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
882 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000883 unsigned NumRegisterParameters, bool SoftFloatABI)
884 : TargetCodeGenInfo(new X86_32ABIInfo(
885 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
886 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000887
John McCall1fe2a8c2013-06-18 02:46:29 +0000888 static bool isStructReturnInRegABI(
889 const llvm::Triple &Triple, const CodeGenOptions &Opts);
890
Eric Christopher162c91c2015-06-05 22:03:00 +0000891 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000892 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000893
Craig Topper4f12f102014-03-12 06:41:41 +0000894 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000895 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000896 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000897 return 4;
898 }
899
900 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000901 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000902
Jay Foad7c57be32011-07-11 09:56:20 +0000903 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000904 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000905 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000906 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
907 }
908
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000909 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
910 std::string &Constraints,
911 std::vector<llvm::Type *> &ResultRegTypes,
912 std::vector<llvm::Type *> &ResultTruncRegTypes,
913 std::vector<LValue> &ResultRegDests,
914 std::string &AsmString,
915 unsigned NumOutputs) const override;
916
Craig Topper4f12f102014-03-12 06:41:41 +0000917 llvm::Constant *
918 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000919 unsigned Sig = (0xeb << 0) | // jmp rel8
920 (0x06 << 8) | // .+0x08
921 ('F' << 16) |
922 ('T' << 24);
923 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
924 }
John McCall01391782016-02-05 21:37:38 +0000925
926 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
927 return "movl\t%ebp, %ebp"
928 "\t\t## marker for objc_retainAutoreleaseReturnValue";
929 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000930};
931
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000932}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000933
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000934/// Rewrite input constraint references after adding some output constraints.
935/// In the case where there is one output and one input and we add one output,
936/// we need to replace all operand references greater than or equal to 1:
937/// mov $0, $1
938/// mov eax, $1
939/// The result will be:
940/// mov $0, $2
941/// mov eax, $2
942static void rewriteInputConstraintReferences(unsigned FirstIn,
943 unsigned NumNewOuts,
944 std::string &AsmString) {
945 std::string Buf;
946 llvm::raw_string_ostream OS(Buf);
947 size_t Pos = 0;
948 while (Pos < AsmString.size()) {
949 size_t DollarStart = AsmString.find('$', Pos);
950 if (DollarStart == std::string::npos)
951 DollarStart = AsmString.size();
952 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
953 if (DollarEnd == std::string::npos)
954 DollarEnd = AsmString.size();
955 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
956 Pos = DollarEnd;
957 size_t NumDollars = DollarEnd - DollarStart;
958 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
959 // We have an operand reference.
960 size_t DigitStart = Pos;
961 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
962 if (DigitEnd == std::string::npos)
963 DigitEnd = AsmString.size();
964 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
965 unsigned OperandIndex;
966 if (!OperandStr.getAsInteger(10, OperandIndex)) {
967 if (OperandIndex >= FirstIn)
968 OperandIndex += NumNewOuts;
969 OS << OperandIndex;
970 } else {
971 OS << OperandStr;
972 }
973 Pos = DigitEnd;
974 }
975 }
976 AsmString = std::move(OS.str());
977}
978
979/// Add output constraints for EAX:EDX because they are return registers.
980void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
981 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
982 std::vector<llvm::Type *> &ResultRegTypes,
983 std::vector<llvm::Type *> &ResultTruncRegTypes,
984 std::vector<LValue> &ResultRegDests, std::string &AsmString,
985 unsigned NumOutputs) const {
986 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
987
988 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
989 // larger.
990 if (!Constraints.empty())
991 Constraints += ',';
992 if (RetWidth <= 32) {
993 Constraints += "={eax}";
994 ResultRegTypes.push_back(CGF.Int32Ty);
995 } else {
996 // Use the 'A' constraint for EAX:EDX.
997 Constraints += "=A";
998 ResultRegTypes.push_back(CGF.Int64Ty);
999 }
1000
1001 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1002 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1003 ResultTruncRegTypes.push_back(CoerceTy);
1004
1005 // Coerce the integer by bitcasting the return slot pointer.
1006 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1007 CoerceTy->getPointerTo()));
1008 ResultRegDests.push_back(ReturnSlot);
1009
1010 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1011}
1012
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001013/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +00001014/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +00001015bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1016 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001017 uint64_t Size = Context.getTypeSize(Ty);
1018
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001019 // For i386, type must be register sized.
1020 // For the MCU ABI, it only needs to be <= 8-byte
1021 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1022 return false;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001023
1024 if (Ty->isVectorType()) {
1025 // 64- and 128- bit vectors inside structures are not returned in
1026 // registers.
1027 if (Size == 64 || Size == 128)
1028 return false;
1029
1030 return true;
1031 }
1032
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001033 // If this is a builtin, pointer, enum, complex type, member pointer, or
1034 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001035 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001036 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001037 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001038 return true;
1039
1040 // Arrays are treated like records.
1041 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001042 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001043
1044 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001045 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001046 if (!RT) return false;
1047
Anders Carlsson40446e82010-01-27 03:25:19 +00001048 // FIXME: Traverse bases here too.
1049
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001050 // Structure types are passed in register if all fields would be
1051 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001052 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001053 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001054 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001055 continue;
1056
1057 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001058 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001059 return false;
1060 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001061 return true;
1062}
1063
John McCall7f416cc2015-09-08 08:05:57 +00001064ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001065 // If the return value is indirect, then the hidden argument is consuming one
1066 // integer register.
1067 if (State.FreeRegs) {
1068 --State.FreeRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001069 if (!IsMCUABI)
1070 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001071 }
John McCall7f416cc2015-09-08 08:05:57 +00001072 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001073}
1074
Eric Christopher7565e0d2015-05-29 23:09:49 +00001075ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1076 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001077 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001078 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001079
Reid Kleckner80944df2014-10-31 22:00:51 +00001080 const Type *Base = nullptr;
1081 uint64_t NumElts = 0;
1082 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1083 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1084 // The LLVM struct type for such an aggregate should lower properly.
1085 return ABIArgInfo::getDirect();
1086 }
1087
Chris Lattner458b2aa2010-07-29 02:16:43 +00001088 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001089 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001090 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001091 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001092
1093 // 128-bit vectors are a special case; they are returned in
1094 // registers and we need to make sure to pick a type the LLVM
1095 // backend will like.
1096 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001097 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001098 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001099
1100 // Always return in register if it fits in a general purpose
1101 // register, or if it is 64 bits and has a single element.
1102 if ((Size == 8 || Size == 16 || Size == 32) ||
1103 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001104 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001105 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001106
John McCall7f416cc2015-09-08 08:05:57 +00001107 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001108 }
1109
1110 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001111 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001112
John McCalla1dee5302010-08-22 10:59:02 +00001113 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001114 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001115 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001116 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001117 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001118 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001119
David Chisnallde3a0692009-08-17 23:08:21 +00001120 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001121 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001122 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001123
Denis Zobnin380b2242016-02-11 11:26:03 +00001124 // Ignore empty structs/unions.
1125 if (isEmptyRecord(getContext(), RetTy, true))
1126 return ABIArgInfo::getIgnore();
1127
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001128 // Small structures which are register sized are generally returned
1129 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001130 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001131 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001132
1133 // As a special-case, if the struct is a "single-element" struct, and
1134 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001135 // floating-point register. (MSVC does not apply this special case.)
1136 // We apply a similar transformation for pointer types to improve the
1137 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001138 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001139 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001140 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001141 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1142
1143 // FIXME: We should be able to narrow this integer in cases with dead
1144 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001145 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001146 }
1147
John McCall7f416cc2015-09-08 08:05:57 +00001148 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001149 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001150
Chris Lattner458b2aa2010-07-29 02:16:43 +00001151 // Treat an enum type as its underlying type.
1152 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1153 RetTy = EnumTy->getDecl()->getIntegerType();
1154
1155 return (RetTy->isPromotableIntegerType() ?
1156 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001157}
1158
Eli Friedman7919bea2012-06-05 19:40:46 +00001159static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1160 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1161}
1162
Daniel Dunbared23de32010-09-16 20:42:00 +00001163static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1164 const RecordType *RT = Ty->getAs<RecordType>();
1165 if (!RT)
1166 return 0;
1167 const RecordDecl *RD = RT->getDecl();
1168
1169 // If this is a C++ record, check the bases first.
1170 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001171 for (const auto &I : CXXRD->bases())
1172 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001173 return false;
1174
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001175 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001176 QualType FT = i->getType();
1177
Eli Friedman7919bea2012-06-05 19:40:46 +00001178 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001179 return true;
1180
1181 if (isRecordWithSSEVectorType(Context, FT))
1182 return true;
1183 }
1184
1185 return false;
1186}
1187
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001188unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1189 unsigned Align) const {
1190 // Otherwise, if the alignment is less than or equal to the minimum ABI
1191 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001192 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001193 return 0; // Use default alignment.
1194
1195 // On non-Darwin, the stack type alignment is always 4.
1196 if (!IsDarwinVectorABI) {
1197 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001198 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001199 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001200
Daniel Dunbared23de32010-09-16 20:42:00 +00001201 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001202 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1203 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001204 return 16;
1205
1206 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001207}
1208
Rafael Espindola703c47f2012-10-19 05:04:37 +00001209ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001210 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001211 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001212 if (State.FreeRegs) {
1213 --State.FreeRegs; // Non-byval indirects just use one pointer.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001214 if (!IsMCUABI)
1215 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001216 }
John McCall7f416cc2015-09-08 08:05:57 +00001217 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001218 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001219
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001220 // Compute the byval alignment.
1221 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1222 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1223 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001224 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001225
1226 // If the stack alignment is less than the type alignment, realign the
1227 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001228 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001229 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1230 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001231}
1232
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001233X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1234 const Type *T = isSingleElementStruct(Ty, getContext());
1235 if (!T)
1236 T = Ty.getTypePtr();
1237
1238 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1239 BuiltinType::Kind K = BT->getKind();
1240 if (K == BuiltinType::Float || K == BuiltinType::Double)
1241 return Float;
1242 }
1243 return Integer;
1244}
1245
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001246bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001247 if (!IsSoftFloatABI) {
1248 Class C = classify(Ty);
1249 if (C == Float)
1250 return false;
1251 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001252
Rafael Espindola077dd592012-10-24 01:58:58 +00001253 unsigned Size = getContext().getTypeSize(Ty);
1254 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001255
1256 if (SizeInRegs == 0)
1257 return false;
1258
Michael Kuperstein68901882015-10-25 08:18:20 +00001259 if (!IsMCUABI) {
1260 if (SizeInRegs > State.FreeRegs) {
1261 State.FreeRegs = 0;
1262 return false;
1263 }
1264 } else {
1265 // The MCU psABI allows passing parameters in-reg even if there are
1266 // earlier parameters that are passed on the stack. Also,
1267 // it does not allow passing >8-byte structs in-register,
1268 // even if there are 3 free registers available.
1269 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1270 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001271 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001272
Reid Kleckner661f35b2014-01-18 01:12:41 +00001273 State.FreeRegs -= SizeInRegs;
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001274 return true;
1275}
1276
1277bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1278 bool &InReg,
1279 bool &NeedsPadding) const {
1280 NeedsPadding = false;
1281 InReg = !IsMCUABI;
1282
1283 if (!updateFreeRegs(Ty, State))
1284 return false;
1285
1286 if (IsMCUABI)
1287 return true;
Rafael Espindola077dd592012-10-24 01:58:58 +00001288
Reid Kleckner80944df2014-10-31 22:00:51 +00001289 if (State.CC == llvm::CallingConv::X86_FastCall ||
1290 State.CC == llvm::CallingConv::X86_VectorCall) {
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001291 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001292 NeedsPadding = true;
1293
Rafael Espindola077dd592012-10-24 01:58:58 +00001294 return false;
1295 }
1296
Rafael Espindola703c47f2012-10-19 05:04:37 +00001297 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001298}
1299
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001300bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1301 if (!updateFreeRegs(Ty, State))
1302 return false;
1303
1304 if (IsMCUABI)
1305 return false;
1306
1307 if (State.CC == llvm::CallingConv::X86_FastCall ||
1308 State.CC == llvm::CallingConv::X86_VectorCall) {
1309 if (getContext().getTypeSize(Ty) > 32)
1310 return false;
1311
1312 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1313 Ty->isReferenceType());
1314 }
1315
1316 return true;
1317}
1318
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001319ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1320 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001321 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001322
Reid Klecknerb1be6832014-11-15 01:41:41 +00001323 Ty = useFirstFieldIfTransparentUnion(Ty);
1324
Reid Kleckner80944df2014-10-31 22:00:51 +00001325 // Check with the C++ ABI first.
1326 const RecordType *RT = Ty->getAs<RecordType>();
1327 if (RT) {
1328 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1329 if (RAA == CGCXXABI::RAA_Indirect) {
1330 return getIndirectResult(Ty, false, State);
1331 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1332 // The field index doesn't matter, we'll fix it up later.
1333 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1334 }
1335 }
1336
1337 // vectorcall adds the concept of a homogenous vector aggregate, similar
1338 // to other targets.
1339 const Type *Base = nullptr;
1340 uint64_t NumElts = 0;
1341 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1342 isHomogeneousAggregate(Ty, Base, NumElts)) {
1343 if (State.FreeSSERegs >= NumElts) {
1344 State.FreeSSERegs -= NumElts;
1345 if (Ty->isBuiltinType() || Ty->isVectorType())
1346 return ABIArgInfo::getDirect();
1347 return ABIArgInfo::getExpand();
1348 }
1349 return getIndirectResult(Ty, /*ByVal=*/false, State);
1350 }
1351
1352 if (isAggregateTypeForABI(Ty)) {
1353 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001354 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001355 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001356 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001357
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001358 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001359 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001360 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001361 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001362
Eli Friedman9f061a32011-11-18 00:28:11 +00001363 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001364 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001365 return ABIArgInfo::getIgnore();
1366
Rafael Espindolafad28de2012-10-24 01:59:00 +00001367 llvm::LLVMContext &LLVMContext = getVMContext();
1368 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001369 bool NeedsPadding, InReg;
1370 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001371 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001372 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001373 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001374 if (InReg)
1375 return ABIArgInfo::getDirectInReg(Result);
1376 else
1377 return ABIArgInfo::getDirect(Result);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001378 }
Craig Topper8a13c412014-05-21 05:09:00 +00001379 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001380
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001381 // Expand small (<= 128-bit) record types when we know that the stack layout
1382 // of those arguments will match the struct. This is important because the
1383 // LLVM backend isn't smart enough to remove byval, which inhibits many
1384 // optimizations.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001385 // Don't do this for the MCU if there are still free integer registers
1386 // (see X86_64 ABI for full explanation).
Chris Lattner458b2aa2010-07-29 02:16:43 +00001387 if (getContext().getTypeSize(Ty) <= 4*32 &&
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001388 canExpandIndirectArgument(Ty, getContext()) &&
1389 (!IsMCUABI || State.FreeRegs == 0))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001390 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001391 State.CC == llvm::CallingConv::X86_FastCall ||
1392 State.CC == llvm::CallingConv::X86_VectorCall,
1393 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001394
Reid Kleckner661f35b2014-01-18 01:12:41 +00001395 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001396 }
1397
Chris Lattnerd774ae92010-08-26 20:05:13 +00001398 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001399 // On Darwin, some vectors are passed in memory, we handle this by passing
1400 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001401 if (IsDarwinVectorABI) {
1402 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001403 if ((Size == 8 || Size == 16 || Size == 32) ||
1404 (Size == 64 && VT->getNumElements() == 1))
1405 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1406 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001407 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001408
Chad Rosier651c1832013-03-25 21:00:27 +00001409 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1410 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001411
Chris Lattnerd774ae92010-08-26 20:05:13 +00001412 return ABIArgInfo::getDirect();
1413 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001414
1415
Chris Lattner458b2aa2010-07-29 02:16:43 +00001416 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1417 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001418
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001419 bool InReg = shouldPrimitiveUseInReg(Ty, State);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001420
1421 if (Ty->isPromotableIntegerType()) {
1422 if (InReg)
1423 return ABIArgInfo::getExtendInReg();
1424 return ABIArgInfo::getExtend();
1425 }
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001426
Rafael Espindola703c47f2012-10-19 05:04:37 +00001427 if (InReg)
1428 return ABIArgInfo::getDirectInReg();
1429 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001430}
1431
Rafael Espindolaa6472962012-07-24 00:01:07 +00001432void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001433 CCState State(FI.getCallingConvention());
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001434 if (IsMCUABI)
1435 State.FreeRegs = 3;
1436 else if (State.CC == llvm::CallingConv::X86_FastCall)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001437 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001438 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1439 State.FreeRegs = 2;
1440 State.FreeSSERegs = 6;
1441 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001442 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001443 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001444 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001445
Reid Kleckner677539d2014-07-10 01:58:55 +00001446 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001447 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001448 } else if (FI.getReturnInfo().isIndirect()) {
1449 // The C++ ABI is not aware of register usage, so we have to check if the
1450 // return value was sret and put it in a register ourselves if appropriate.
1451 if (State.FreeRegs) {
1452 --State.FreeRegs; // The sret parameter consumes a register.
Michael Kupersteinf3163dc2015-12-28 14:39:54 +00001453 if (!IsMCUABI)
1454 FI.getReturnInfo().setInReg(true);
Reid Kleckner677539d2014-07-10 01:58:55 +00001455 }
1456 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001457
Peter Collingbournef7706832014-12-12 23:41:25 +00001458 // The chain argument effectively gives us another free register.
1459 if (FI.isChainCall())
1460 ++State.FreeRegs;
1461
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001462 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001463 for (auto &I : FI.arguments()) {
1464 I.info = classifyArgumentType(I.type, State);
1465 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001466 }
1467
1468 // If we needed to use inalloca for any argument, do a second pass and rewrite
1469 // all the memory arguments to use inalloca.
1470 if (UsedInAlloca)
1471 rewriteWithInAlloca(FI);
1472}
1473
1474void
1475X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001476 CharUnits &StackOffset, ABIArgInfo &Info,
1477 QualType Type) const {
1478 // Arguments are always 4-byte-aligned.
1479 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1480
1481 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001482 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1483 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001484 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001485
John McCall7f416cc2015-09-08 08:05:57 +00001486 // Insert padding bytes to respect alignment.
1487 CharUnits FieldEnd = StackOffset;
Rui Ueyama83aa9792016-01-14 21:00:27 +00001488 StackOffset = FieldEnd.alignTo(FieldAlign);
John McCall7f416cc2015-09-08 08:05:57 +00001489 if (StackOffset != FieldEnd) {
1490 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001491 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001492 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001493 FrameFields.push_back(Ty);
1494 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001495}
1496
Reid Kleckner852361d2014-07-26 00:12:26 +00001497static bool isArgInAlloca(const ABIArgInfo &Info) {
1498 // Leave ignored and inreg arguments alone.
1499 switch (Info.getKind()) {
1500 case ABIArgInfo::InAlloca:
1501 return true;
1502 case ABIArgInfo::Indirect:
1503 assert(Info.getIndirectByVal());
1504 return true;
1505 case ABIArgInfo::Ignore:
1506 return false;
1507 case ABIArgInfo::Direct:
1508 case ABIArgInfo::Extend:
1509 case ABIArgInfo::Expand:
1510 if (Info.getInReg())
1511 return false;
1512 return true;
1513 }
1514 llvm_unreachable("invalid enum");
1515}
1516
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001517void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1518 assert(IsWin32StructABI && "inalloca only supported on win32");
1519
1520 // Build a packed struct type for all of the arguments in memory.
1521 SmallVector<llvm::Type *, 6> FrameFields;
1522
John McCall7f416cc2015-09-08 08:05:57 +00001523 // The stack alignment is always 4.
1524 CharUnits StackAlign = CharUnits::fromQuantity(4);
1525
1526 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001527 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1528
1529 // Put 'this' into the struct before 'sret', if necessary.
1530 bool IsThisCall =
1531 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1532 ABIArgInfo &Ret = FI.getReturnInfo();
1533 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1534 isArgInAlloca(I->info)) {
1535 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1536 ++I;
1537 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001538
1539 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001540 if (Ret.isIndirect() && !Ret.getInReg()) {
1541 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1542 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001543 // On Windows, the hidden sret parameter is always returned in eax.
1544 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001545 }
1546
1547 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001548 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001549 ++I;
1550
1551 // Put arguments passed in memory into the struct.
1552 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001553 if (isArgInAlloca(I->info))
1554 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001555 }
1556
1557 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001558 /*isPacked=*/true),
1559 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001560}
1561
John McCall7f416cc2015-09-08 08:05:57 +00001562Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1563 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001564
John McCall7f416cc2015-09-08 08:05:57 +00001565 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001566
John McCall7f416cc2015-09-08 08:05:57 +00001567 // x86-32 changes the alignment of certain arguments on the stack.
1568 //
1569 // Just messing with TypeInfo like this works because we never pass
1570 // anything indirectly.
1571 TypeInfo.second = CharUnits::fromQuantity(
1572 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001573
John McCall7f416cc2015-09-08 08:05:57 +00001574 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1575 TypeInfo, CharUnits::fromQuantity(4),
1576 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001577}
1578
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001579bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1580 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1581 assert(Triple.getArch() == llvm::Triple::x86);
1582
1583 switch (Opts.getStructReturnConvention()) {
1584 case CodeGenOptions::SRCK_Default:
1585 break;
1586 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1587 return false;
1588 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1589 return true;
1590 }
1591
Michael Kupersteind749f232015-10-27 07:46:22 +00001592 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001593 return true;
1594
1595 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001596 case llvm::Triple::DragonFly:
1597 case llvm::Triple::FreeBSD:
1598 case llvm::Triple::OpenBSD:
1599 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001600 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001601 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001602 default:
1603 return false;
1604 }
1605}
1606
Eric Christopher162c91c2015-06-05 22:03:00 +00001607void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001608 llvm::GlobalValue *GV,
1609 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001610 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001611 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1612 // Get the LLVM function.
1613 llvm::Function *Fn = cast<llvm::Function>(GV);
1614
1615 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001616 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001617 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001618 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1619 llvm::AttributeSet::get(CGM.getLLVMContext(),
1620 llvm::AttributeSet::FunctionIndex,
1621 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001622 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001623 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1624 llvm::Function *Fn = cast<llvm::Function>(GV);
1625 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1626 }
Charles Davis4ea31ab2010-02-13 15:54:06 +00001627 }
1628}
1629
John McCallbeec5a02010-03-06 00:35:14 +00001630bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1631 CodeGen::CodeGenFunction &CGF,
1632 llvm::Value *Address) const {
1633 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001634
Chris Lattnerece04092012-02-07 00:39:47 +00001635 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001636
John McCallbeec5a02010-03-06 00:35:14 +00001637 // 0-7 are the eight integer registers; the order is different
1638 // on Darwin (for EH), but the range is the same.
1639 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001640 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001641
John McCallc8e01702013-04-16 22:48:15 +00001642 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001643 // 12-16 are st(0..4). Not sure why we stop at 4.
1644 // These have size 16, which is sizeof(long double) on
1645 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001646 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001647 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001648
John McCallbeec5a02010-03-06 00:35:14 +00001649 } else {
1650 // 9 is %eflags, which doesn't get a size on Darwin for some
1651 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001652 Builder.CreateAlignedStore(
1653 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1654 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001655
1656 // 11-16 are st(0..5). Not sure why we stop at 5.
1657 // These have size 12, which is sizeof(long double) on
1658 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001659 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001660 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1661 }
John McCallbeec5a02010-03-06 00:35:14 +00001662
1663 return false;
1664}
1665
Chris Lattner0cf24192010-06-28 20:05:43 +00001666//===----------------------------------------------------------------------===//
1667// X86-64 ABI Implementation
1668//===----------------------------------------------------------------------===//
1669
1670
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001671namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001672/// The AVX ABI level for X86 targets.
1673enum class X86AVXABILevel {
1674 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001675 AVX,
1676 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001677};
1678
1679/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1680static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1681 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001682 case X86AVXABILevel::AVX512:
1683 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001684 case X86AVXABILevel::AVX:
1685 return 256;
1686 case X86AVXABILevel::None:
1687 return 128;
1688 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001689 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001690}
1691
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001692/// X86_64ABIInfo - The X86_64 ABI information.
1693class X86_64ABIInfo : public ABIInfo {
1694 enum Class {
1695 Integer = 0,
1696 SSE,
1697 SSEUp,
1698 X87,
1699 X87Up,
1700 ComplexX87,
1701 NoClass,
1702 Memory
1703 };
1704
1705 /// merge - Implement the X86_64 ABI merging algorithm.
1706 ///
1707 /// Merge an accumulating classification \arg Accum with a field
1708 /// classification \arg Field.
1709 ///
1710 /// \param Accum - The accumulating classification. This should
1711 /// always be either NoClass or the result of a previous merge
1712 /// call. In addition, this should never be Memory (the caller
1713 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001714 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001715
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001716 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1717 ///
1718 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1719 /// final MEMORY or SSE classes when necessary.
1720 ///
1721 /// \param AggregateSize - The size of the current aggregate in
1722 /// the classification process.
1723 ///
1724 /// \param Lo - The classification for the parts of the type
1725 /// residing in the low word of the containing object.
1726 ///
1727 /// \param Hi - The classification for the parts of the type
1728 /// residing in the higher words of the containing object.
1729 ///
1730 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1731
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001732 /// classify - Determine the x86_64 register classes in which the
1733 /// given type T should be passed.
1734 ///
1735 /// \param Lo - The classification for the parts of the type
1736 /// residing in the low word of the containing object.
1737 ///
1738 /// \param Hi - The classification for the parts of the type
1739 /// residing in the high word of the containing object.
1740 ///
1741 /// \param OffsetBase - The bit offset of this type in the
1742 /// containing object. Some parameters are classified different
1743 /// depending on whether they straddle an eightbyte boundary.
1744 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001745 /// \param isNamedArg - Whether the argument in question is a "named"
1746 /// argument, as used in AMD64-ABI 3.5.7.
1747 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001748 /// If a word is unused its result will be NoClass; if a type should
1749 /// be passed in Memory then at least the classification of \arg Lo
1750 /// will be Memory.
1751 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001752 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001753 ///
1754 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1755 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001756 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1757 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001758
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001759 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001760 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1761 unsigned IROffset, QualType SourceTy,
1762 unsigned SourceOffset) const;
1763 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1764 unsigned IROffset, QualType SourceTy,
1765 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001766
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001767 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001768 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001769 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001770
1771 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001772 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001773 ///
1774 /// \param freeIntRegs - The number of free integer registers remaining
1775 /// available.
1776 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001777
Chris Lattner458b2aa2010-07-29 02:16:43 +00001778 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001779
Bill Wendling5cd41c42010-10-18 03:41:31 +00001780 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001781 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001782 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001783 unsigned &neededSSE,
1784 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001785
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001786 bool IsIllegalVectorType(QualType Ty) const;
1787
John McCalle0fda732011-04-21 01:20:55 +00001788 /// The 0.98 ABI revision clarified a lot of ambiguities,
1789 /// unfortunately in ways that were not always consistent with
1790 /// certain previous compilers. In particular, platforms which
1791 /// required strict binary compatibility with older versions of GCC
1792 /// may need to exempt themselves.
1793 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001794 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001795 }
1796
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001797 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001798 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1799 // 64-bit hardware.
1800 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001801
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001802public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001803 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1804 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001805 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001806 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001807
John McCalla729c622012-02-17 03:33:10 +00001808 bool isPassedUsingAVXType(QualType type) const {
1809 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001810 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001811 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1812 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001813 if (info.isDirect()) {
1814 llvm::Type *ty = info.getCoerceToType();
1815 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1816 return (vectorTy->getBitWidth() > 128);
1817 }
1818 return false;
1819 }
1820
Craig Topper4f12f102014-03-12 06:41:41 +00001821 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001822
John McCall7f416cc2015-09-08 08:05:57 +00001823 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1824 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001825 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1826 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001827
1828 bool has64BitPointers() const {
1829 return Has64BitPointers;
1830 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001831};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001832
Chris Lattner04dc9572010-08-31 16:44:54 +00001833/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001834class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001835public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001836 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1837 : ABIInfo(CGT),
1838 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001839
Craig Topper4f12f102014-03-12 06:41:41 +00001840 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001841
John McCall7f416cc2015-09-08 08:05:57 +00001842 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1843 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001844
1845 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1846 // FIXME: Assumes vectorcall is in use.
1847 return isX86VectorTypeForVectorCall(getContext(), Ty);
1848 }
1849
1850 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1851 uint64_t NumMembers) const override {
1852 // FIXME: Assumes vectorcall is in use.
1853 return isX86VectorCallAggregateSmallEnough(NumMembers);
1854 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001855
1856private:
1857 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1858 bool IsReturnType) const;
1859
1860 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00001861};
1862
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001863class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1864public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001865 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001866 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001867
John McCalla729c622012-02-17 03:33:10 +00001868 const X86_64ABIInfo &getABIInfo() const {
1869 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1870 }
1871
Craig Topper4f12f102014-03-12 06:41:41 +00001872 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001873 return 7;
1874 }
1875
1876 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001877 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001878 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001879
John McCall943fae92010-05-27 06:19:26 +00001880 // 0-15 are the 16 integer registers.
1881 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001882 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001883 return false;
1884 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001885
Jay Foad7c57be32011-07-11 09:56:20 +00001886 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001887 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001888 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001889 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1890 }
1891
John McCalla729c622012-02-17 03:33:10 +00001892 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001893 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001894 // The default CC on x86-64 sets %al to the number of SSA
1895 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001896 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001897 // that when AVX types are involved: the ABI explicitly states it is
1898 // undefined, and it doesn't work in practice because of how the ABI
1899 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001900 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001901 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001902 for (CallArgList::const_iterator
1903 it = args.begin(), ie = args.end(); it != ie; ++it) {
1904 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1905 HasAVXType = true;
1906 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001907 }
1908 }
John McCalla729c622012-02-17 03:33:10 +00001909
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001910 if (!HasAVXType)
1911 return true;
1912 }
John McCallcbc038a2011-09-21 08:08:30 +00001913
John McCalla729c622012-02-17 03:33:10 +00001914 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001915 }
1916
Craig Topper4f12f102014-03-12 06:41:41 +00001917 llvm::Constant *
1918 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001919 unsigned Sig;
1920 if (getABIInfo().has64BitPointers())
1921 Sig = (0xeb << 0) | // jmp rel8
1922 (0x0a << 8) | // .+0x0c
1923 ('F' << 16) |
1924 ('T' << 24);
1925 else
1926 Sig = (0xeb << 0) | // jmp rel8
1927 (0x06 << 8) | // .+0x08
1928 ('F' << 16) |
1929 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001930 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1931 }
Alexey Bataevd51e9932016-01-15 04:06:31 +00001932
1933 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1934 CodeGen::CodeGenModule &CGM) const override {
1935 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1936 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1937 llvm::Function *Fn = cast<llvm::Function>(GV);
1938 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1939 }
1940 }
1941 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001942};
1943
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001944class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1945public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001946 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1947 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001948
1949 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001950 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001951 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001952 // If the argument contains a space, enclose it in quotes.
1953 if (Lib.find(" ") != StringRef::npos)
1954 Opt += "\"" + Lib.str() + "\"";
1955 else
1956 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001957 }
1958};
1959
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001960static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001961 // If the argument does not end in .lib, automatically add the suffix.
1962 // If the argument contains a space, enclose it in quotes.
1963 // This matches the behavior of MSVC.
1964 bool Quote = (Lib.find(" ") != StringRef::npos);
1965 std::string ArgStr = Quote ? "\"" : "";
1966 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001967 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001968 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001969 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001970 return ArgStr;
1971}
1972
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001973class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1974public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001975 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00001976 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1977 unsigned NumRegisterParameters)
1978 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001979 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001980
Eric Christopher162c91c2015-06-05 22:03:00 +00001981 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001982 CodeGen::CodeGenModule &CGM) const override;
1983
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001984 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001985 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001986 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001987 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001988 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001989
1990 void getDetectMismatchOption(llvm::StringRef Name,
1991 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001992 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001993 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001994 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001995};
1996
Hans Wennborg77dc2362015-01-20 19:45:50 +00001997static void addStackProbeSizeTargetAttribute(const Decl *D,
1998 llvm::GlobalValue *GV,
1999 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00002000 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00002001 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
2002 llvm::Function *Fn = cast<llvm::Function>(GV);
2003
Eric Christopher7565e0d2015-05-29 23:09:49 +00002004 Fn->addFnAttr("stack-probe-size",
2005 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00002006 }
2007 }
2008}
2009
Eric Christopher162c91c2015-06-05 22:03:00 +00002010void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002011 llvm::GlobalValue *GV,
2012 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002013 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002014
2015 addStackProbeSizeTargetAttribute(D, GV, CGM);
2016}
2017
Chris Lattner04dc9572010-08-31 16:44:54 +00002018class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2019public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002020 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2021 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00002022 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00002023
Eric Christopher162c91c2015-06-05 22:03:00 +00002024 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002025 CodeGen::CodeGenModule &CGM) const override;
2026
Craig Topper4f12f102014-03-12 06:41:41 +00002027 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00002028 return 7;
2029 }
2030
2031 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00002032 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00002033 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002034
Chris Lattner04dc9572010-08-31 16:44:54 +00002035 // 0-15 are the 16 integer registers.
2036 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00002037 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00002038 return false;
2039 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002040
2041 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00002042 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002043 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00002044 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00002045 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00002046
2047 void getDetectMismatchOption(llvm::StringRef Name,
2048 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00002049 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00002050 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00002051 }
Chris Lattner04dc9572010-08-31 16:44:54 +00002052};
2053
Eric Christopher162c91c2015-06-05 22:03:00 +00002054void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00002055 llvm::GlobalValue *GV,
2056 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00002057 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00002058
Alexey Bataevd51e9932016-01-15 04:06:31 +00002059 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2060 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2061 llvm::Function *Fn = cast<llvm::Function>(GV);
2062 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2063 }
2064 }
2065
Hans Wennborg77dc2362015-01-20 19:45:50 +00002066 addStackProbeSizeTargetAttribute(D, GV, CGM);
2067}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002068}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002069
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002070void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2071 Class &Hi) const {
2072 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2073 //
2074 // (a) If one of the classes is Memory, the whole argument is passed in
2075 // memory.
2076 //
2077 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2078 // memory.
2079 //
2080 // (c) If the size of the aggregate exceeds two eightbytes and the first
2081 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2082 // argument is passed in memory. NOTE: This is necessary to keep the
2083 // ABI working for processors that don't support the __m256 type.
2084 //
2085 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2086 //
2087 // Some of these are enforced by the merging logic. Others can arise
2088 // only with unions; for example:
2089 // union { _Complex double; unsigned; }
2090 //
2091 // Note that clauses (b) and (c) were added in 0.98.
2092 //
2093 if (Hi == Memory)
2094 Lo = Memory;
2095 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2096 Lo = Memory;
2097 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2098 Lo = Memory;
2099 if (Hi == SSEUp && Lo != SSE)
2100 Hi = SSE;
2101}
2102
Chris Lattnerd776fb12010-06-28 21:43:59 +00002103X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002104 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2105 // classified recursively so that always two fields are
2106 // considered. The resulting class is calculated according to
2107 // the classes of the fields in the eightbyte:
2108 //
2109 // (a) If both classes are equal, this is the resulting class.
2110 //
2111 // (b) If one of the classes is NO_CLASS, the resulting class is
2112 // the other class.
2113 //
2114 // (c) If one of the classes is MEMORY, the result is the MEMORY
2115 // class.
2116 //
2117 // (d) If one of the classes is INTEGER, the result is the
2118 // INTEGER.
2119 //
2120 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2121 // MEMORY is used as class.
2122 //
2123 // (f) Otherwise class SSE is used.
2124
2125 // Accum should never be memory (we should have returned) or
2126 // ComplexX87 (because this cannot be passed in a structure).
2127 assert((Accum != Memory && Accum != ComplexX87) &&
2128 "Invalid accumulated classification during merge.");
2129 if (Accum == Field || Field == NoClass)
2130 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002131 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002132 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002133 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002134 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002135 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002136 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002137 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2138 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002139 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002140 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002141}
2142
Chris Lattner5c740f12010-06-30 19:14:05 +00002143void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002144 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002145 // FIXME: This code can be simplified by introducing a simple value class for
2146 // Class pairs with appropriate constructor methods for the various
2147 // situations.
2148
2149 // FIXME: Some of the split computations are wrong; unaligned vectors
2150 // shouldn't be passed in registers for example, so there is no chance they
2151 // can straddle an eightbyte. Verify & simplify.
2152
2153 Lo = Hi = NoClass;
2154
2155 Class &Current = OffsetBase < 64 ? Lo : Hi;
2156 Current = Memory;
2157
John McCall9dd450b2009-09-21 23:43:11 +00002158 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002159 BuiltinType::Kind k = BT->getKind();
2160
2161 if (k == BuiltinType::Void) {
2162 Current = NoClass;
2163 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2164 Lo = Integer;
2165 Hi = Integer;
2166 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2167 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002168 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002169 Current = SSE;
2170 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002171 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2172 if (LDF == &llvm::APFloat::IEEEquad) {
2173 Lo = SSE;
2174 Hi = SSEUp;
2175 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2176 Lo = X87;
2177 Hi = X87Up;
2178 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2179 Current = SSE;
2180 } else
2181 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002182 }
2183 // FIXME: _Decimal32 and _Decimal64 are SSE.
2184 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002185 return;
2186 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002187
Chris Lattnerd776fb12010-06-28 21:43:59 +00002188 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002189 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002190 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002191 return;
2192 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002193
Chris Lattnerd776fb12010-06-28 21:43:59 +00002194 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002195 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002196 return;
2197 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002198
Chris Lattnerd776fb12010-06-28 21:43:59 +00002199 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002200 if (Ty->isMemberFunctionPointerType()) {
2201 if (Has64BitPointers) {
2202 // If Has64BitPointers, this is an {i64, i64}, so classify both
2203 // Lo and Hi now.
2204 Lo = Hi = Integer;
2205 } else {
2206 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2207 // straddles an eightbyte boundary, Hi should be classified as well.
2208 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2209 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2210 if (EB_FuncPtr != EB_ThisAdj) {
2211 Lo = Hi = Integer;
2212 } else {
2213 Current = Integer;
2214 }
2215 }
2216 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002217 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002218 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002219 return;
2220 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002221
Chris Lattnerd776fb12010-06-28 21:43:59 +00002222 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002223 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002224 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2225 // gcc passes the following as integer:
2226 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2227 // 2 bytes - <2 x char>, <1 x short>
2228 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002229 Current = Integer;
2230
2231 // If this type crosses an eightbyte boundary, it should be
2232 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002233 uint64_t EB_Lo = (OffsetBase) / 64;
2234 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2235 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002236 Hi = Lo;
2237 } else if (Size == 64) {
2238 // gcc passes <1 x double> in memory. :(
2239 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2240 return;
2241
2242 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002243 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002244 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2245 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2246 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002247 Current = Integer;
2248 else
2249 Current = SSE;
2250
2251 // If this type crosses an eightbyte boundary, it should be
2252 // split.
2253 if (OffsetBase && OffsetBase != 64)
2254 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002255 } else if (Size == 128 ||
2256 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002257 // Arguments of 256-bits are split into four eightbyte chunks. The
2258 // least significant one belongs to class SSE and all the others to class
2259 // SSEUP. The original Lo and Hi design considers that types can't be
2260 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2261 // This design isn't correct for 256-bits, but since there're no cases
2262 // where the upper parts would need to be inspected, avoid adding
2263 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002264 //
2265 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2266 // registers if they are "named", i.e. not part of the "..." of a
2267 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002268 //
2269 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2270 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002271 Lo = SSE;
2272 Hi = SSEUp;
2273 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002274 return;
2275 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002276
Chris Lattnerd776fb12010-06-28 21:43:59 +00002277 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002278 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002279
Chris Lattner2b037972010-07-29 02:01:43 +00002280 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002281 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002282 if (Size <= 64)
2283 Current = Integer;
2284 else if (Size <= 128)
2285 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002286 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002287 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002288 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002289 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002290 } else if (ET == getContext().LongDoubleTy) {
2291 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2292 if (LDF == &llvm::APFloat::IEEEquad)
2293 Current = Memory;
2294 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2295 Current = ComplexX87;
2296 else if (LDF == &llvm::APFloat::IEEEdouble)
2297 Lo = Hi = SSE;
2298 else
2299 llvm_unreachable("unexpected long double representation!");
2300 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002301
2302 // If this complex type crosses an eightbyte boundary then it
2303 // should be split.
2304 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002305 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002306 if (Hi == NoClass && EB_Real != EB_Imag)
2307 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002308
Chris Lattnerd776fb12010-06-28 21:43:59 +00002309 return;
2310 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002311
Chris Lattner2b037972010-07-29 02:01:43 +00002312 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002313 // Arrays are treated like structures.
2314
Chris Lattner2b037972010-07-29 02:01:43 +00002315 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002316
2317 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002318 // than four eightbytes, ..., it has class MEMORY.
2319 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002320 return;
2321
2322 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2323 // fields, it has class MEMORY.
2324 //
2325 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002326 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002327 return;
2328
2329 // Otherwise implement simplified merge. We could be smarter about
2330 // this, but it isn't worth it and would be harder to verify.
2331 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002332 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002333 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002334
2335 // The only case a 256-bit wide vector could be used is when the array
2336 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2337 // to work for sizes wider than 128, early check and fallback to memory.
2338 if (Size > 128 && EltSize != 256)
2339 return;
2340
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002341 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2342 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002343 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002344 Lo = merge(Lo, FieldLo);
2345 Hi = merge(Hi, FieldHi);
2346 if (Lo == Memory || Hi == Memory)
2347 break;
2348 }
2349
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002350 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002351 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002352 return;
2353 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002354
Chris Lattnerd776fb12010-06-28 21:43:59 +00002355 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002356 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002357
2358 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002359 // than four eightbytes, ..., it has class MEMORY.
2360 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002361 return;
2362
Anders Carlsson20759ad2009-09-16 15:53:40 +00002363 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2364 // copy constructor or a non-trivial destructor, it is passed by invisible
2365 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002366 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002367 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002368
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002369 const RecordDecl *RD = RT->getDecl();
2370
2371 // Assume variable sized types are passed in memory.
2372 if (RD->hasFlexibleArrayMember())
2373 return;
2374
Chris Lattner2b037972010-07-29 02:01:43 +00002375 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002376
2377 // Reset Lo class, this will be recomputed.
2378 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002379
2380 // If this is a C++ record, classify the bases first.
2381 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002382 for (const auto &I : CXXRD->bases()) {
2383 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002384 "Unexpected base class!");
2385 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002386 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002387
2388 // Classify this field.
2389 //
2390 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2391 // single eightbyte, each is classified separately. Each eightbyte gets
2392 // initialized to class NO_CLASS.
2393 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002394 uint64_t Offset =
2395 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002396 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002397 Lo = merge(Lo, FieldLo);
2398 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002399 if (Lo == Memory || Hi == Memory) {
2400 postMerge(Size, Lo, Hi);
2401 return;
2402 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002403 }
2404 }
2405
2406 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002407 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002408 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002409 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002410 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2411 bool BitField = i->isBitField();
2412
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002413 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2414 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002415 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002416 // The only case a 256-bit wide vector could be used is when the struct
2417 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2418 // to work for sizes wider than 128, early check and fallback to memory.
2419 //
2420 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2421 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002422 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002423 return;
2424 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002425 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002426 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002427 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002428 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002429 return;
2430 }
2431
2432 // Classify this field.
2433 //
2434 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2435 // exceeds a single eightbyte, each is classified
2436 // separately. Each eightbyte gets initialized to class
2437 // NO_CLASS.
2438 Class FieldLo, FieldHi;
2439
2440 // Bit-fields require special handling, they do not force the
2441 // structure to be passed in memory even if unaligned, and
2442 // therefore they can straddle an eightbyte.
2443 if (BitField) {
2444 // Ignore padding bit-fields.
2445 if (i->isUnnamedBitfield())
2446 continue;
2447
2448 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002449 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002450
2451 uint64_t EB_Lo = Offset / 64;
2452 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002453
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002454 if (EB_Lo) {
2455 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2456 FieldLo = NoClass;
2457 FieldHi = Integer;
2458 } else {
2459 FieldLo = Integer;
2460 FieldHi = EB_Hi ? Integer : NoClass;
2461 }
2462 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002463 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002464 Lo = merge(Lo, FieldLo);
2465 Hi = merge(Hi, FieldHi);
2466 if (Lo == Memory || Hi == Memory)
2467 break;
2468 }
2469
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002470 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002471 }
2472}
2473
Chris Lattner22a931e2010-06-29 06:01:59 +00002474ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002475 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2476 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002477 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002478 // Treat an enum type as its underlying type.
2479 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2480 Ty = EnumTy->getDecl()->getIntegerType();
2481
2482 return (Ty->isPromotableIntegerType() ?
2483 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2484 }
2485
John McCall7f416cc2015-09-08 08:05:57 +00002486 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002487}
2488
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002489bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2490 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2491 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002492 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002493 if (Size <= 64 || Size > LargestVector)
2494 return true;
2495 }
2496
2497 return false;
2498}
2499
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002500ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2501 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002502 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2503 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002504 //
2505 // This assumption is optimistic, as there could be free registers available
2506 // when we need to pass this argument in memory, and LLVM could try to pass
2507 // the argument in the free register. This does not seem to happen currently,
2508 // but this code would be much safer if we could mark the argument with
2509 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002510 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002511 // Treat an enum type as its underlying type.
2512 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2513 Ty = EnumTy->getDecl()->getIntegerType();
2514
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002515 return (Ty->isPromotableIntegerType() ?
2516 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002517 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002518
Mark Lacey3825e832013-10-06 01:33:34 +00002519 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002520 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002521
Chris Lattner44c2b902011-05-22 23:21:23 +00002522 // Compute the byval alignment. We specify the alignment of the byval in all
2523 // cases so that the mid-level optimizer knows the alignment of the byval.
2524 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002525
2526 // Attempt to avoid passing indirect results using byval when possible. This
2527 // is important for good codegen.
2528 //
2529 // We do this by coercing the value into a scalar type which the backend can
2530 // handle naturally (i.e., without using byval).
2531 //
2532 // For simplicity, we currently only do this when we have exhausted all of the
2533 // free integer registers. Doing this when there are free integer registers
2534 // would require more care, as we would have to ensure that the coerced value
2535 // did not claim the unused register. That would require either reording the
2536 // arguments to the function (so that any subsequent inreg values came first),
2537 // or only doing this optimization when there were no following arguments that
2538 // might be inreg.
2539 //
2540 // We currently expect it to be rare (particularly in well written code) for
2541 // arguments to be passed on the stack when there are still free integer
2542 // registers available (this would typically imply large structs being passed
2543 // by value), so this seems like a fair tradeoff for now.
2544 //
2545 // We can revisit this if the backend grows support for 'onstack' parameter
2546 // attributes. See PR12193.
2547 if (freeIntRegs == 0) {
2548 uint64_t Size = getContext().getTypeSize(Ty);
2549
2550 // If this type fits in an eightbyte, coerce it into the matching integral
2551 // type, which will end up on the stack (with alignment 8).
2552 if (Align == 8 && Size <= 64)
2553 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2554 Size));
2555 }
2556
John McCall7f416cc2015-09-08 08:05:57 +00002557 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002558}
2559
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002560/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2561/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002562llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002563 // Wrapper structs/arrays that only contain vectors are passed just like
2564 // vectors; strip them off if present.
2565 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2566 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002567
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002568 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002569 if (isa<llvm::VectorType>(IRType) ||
2570 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002571 return IRType;
2572
2573 // We couldn't find the preferred IR vector type for 'Ty'.
2574 uint64_t Size = getContext().getTypeSize(Ty);
2575 assert((Size == 128 || Size == 256) && "Invalid type found!");
2576
2577 // Return a LLVM IR vector type based on the size of 'Ty'.
2578 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2579 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002580}
2581
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002582/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2583/// is known to either be off the end of the specified type or being in
2584/// alignment padding. The user type specified is known to be at most 128 bits
2585/// in size, and have passed through X86_64ABIInfo::classify with a successful
2586/// classification that put one of the two halves in the INTEGER class.
2587///
2588/// It is conservatively correct to return false.
2589static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2590 unsigned EndBit, ASTContext &Context) {
2591 // If the bytes being queried are off the end of the type, there is no user
2592 // data hiding here. This handles analysis of builtins, vectors and other
2593 // types that don't contain interesting padding.
2594 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2595 if (TySize <= StartBit)
2596 return true;
2597
Chris Lattner98076a22010-07-29 07:43:55 +00002598 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2599 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2600 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2601
2602 // Check each element to see if the element overlaps with the queried range.
2603 for (unsigned i = 0; i != NumElts; ++i) {
2604 // If the element is after the span we care about, then we're done..
2605 unsigned EltOffset = i*EltSize;
2606 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002607
Chris Lattner98076a22010-07-29 07:43:55 +00002608 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2609 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2610 EndBit-EltOffset, Context))
2611 return false;
2612 }
2613 // If it overlaps no elements, then it is safe to process as padding.
2614 return true;
2615 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002616
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002617 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2618 const RecordDecl *RD = RT->getDecl();
2619 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002620
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002621 // If this is a C++ record, check the bases first.
2622 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002623 for (const auto &I : CXXRD->bases()) {
2624 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002625 "Unexpected base class!");
2626 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002627 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002628
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002629 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002630 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002631 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002632
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002633 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002634 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002635 EndBit-BaseOffset, Context))
2636 return false;
2637 }
2638 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002639
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002640 // Verify that no field has data that overlaps the region of interest. Yes
2641 // this could be sped up a lot by being smarter about queried fields,
2642 // however we're only looking at structs up to 16 bytes, so we don't care
2643 // much.
2644 unsigned idx = 0;
2645 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2646 i != e; ++i, ++idx) {
2647 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002648
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002649 // If we found a field after the region we care about, then we're done.
2650 if (FieldOffset >= EndBit) break;
2651
2652 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2653 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2654 Context))
2655 return false;
2656 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002657
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002658 // If nothing in this record overlapped the area of interest, then we're
2659 // clean.
2660 return true;
2661 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002662
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002663 return false;
2664}
2665
Chris Lattnere556a712010-07-29 18:39:32 +00002666/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2667/// float member at the specified offset. For example, {int,{float}} has a
2668/// float at offset 4. It is conservatively correct for this routine to return
2669/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002670static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002671 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002672 // Base case if we find a float.
2673 if (IROffset == 0 && IRType->isFloatTy())
2674 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002675
Chris Lattnere556a712010-07-29 18:39:32 +00002676 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002677 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002678 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2679 unsigned Elt = SL->getElementContainingOffset(IROffset);
2680 IROffset -= SL->getElementOffset(Elt);
2681 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2682 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002683
Chris Lattnere556a712010-07-29 18:39:32 +00002684 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002685 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2686 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002687 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2688 IROffset -= IROffset/EltSize*EltSize;
2689 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2690 }
2691
2692 return false;
2693}
2694
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002695
2696/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2697/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002698llvm::Type *X86_64ABIInfo::
2699GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002700 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002701 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002702 // pass as float if the last 4 bytes is just padding. This happens for
2703 // structs that contain 3 floats.
2704 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2705 SourceOffset*8+64, getContext()))
2706 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002707
Chris Lattnere556a712010-07-29 18:39:32 +00002708 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2709 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2710 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002711 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2712 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002713 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002714
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002715 return llvm::Type::getDoubleTy(getVMContext());
2716}
2717
2718
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002719/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2720/// an 8-byte GPR. This means that we either have a scalar or we are talking
2721/// about the high or low part of an up-to-16-byte struct. This routine picks
2722/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002723/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2724/// etc).
2725///
2726/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2727/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2728/// the 8-byte value references. PrefType may be null.
2729///
Alp Toker9907f082014-07-09 14:06:35 +00002730/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002731/// an offset into this that we're processing (which is always either 0 or 8).
2732///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002733llvm::Type *X86_64ABIInfo::
2734GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002735 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002736 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2737 // returning an 8-byte unit starting with it. See if we can safely use it.
2738 if (IROffset == 0) {
2739 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002740 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2741 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002742 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002743
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002744 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2745 // goodness in the source type is just tail padding. This is allowed to
2746 // kick in for struct {double,int} on the int, but not on
2747 // struct{double,int,int} because we wouldn't return the second int. We
2748 // have to do this analysis on the source type because we can't depend on
2749 // unions being lowered a specific way etc.
2750 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002751 IRType->isIntegerTy(32) ||
2752 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2753 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2754 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002755
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002756 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2757 SourceOffset*8+64, getContext()))
2758 return IRType;
2759 }
2760 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002761
Chris Lattner2192fe52011-07-18 04:24:23 +00002762 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002763 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002764 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002765 if (IROffset < SL->getSizeInBytes()) {
2766 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2767 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002768
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002769 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2770 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002771 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002772 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002773
Chris Lattner2192fe52011-07-18 04:24:23 +00002774 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002775 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002776 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002777 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002778 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2779 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002780 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002781
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002782 // Okay, we don't have any better idea of what to pass, so we pass this in an
2783 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002784 unsigned TySizeInBytes =
2785 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002786
Chris Lattner3f763422010-07-29 17:34:39 +00002787 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002788
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002789 // It is always safe to classify this as an integer type up to i64 that
2790 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002791 return llvm::IntegerType::get(getVMContext(),
2792 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002793}
2794
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002795
2796/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2797/// be used as elements of a two register pair to pass or return, return a
2798/// first class aggregate to represent them. For example, if the low part of
2799/// a by-value argument should be passed as i32* and the high part as float,
2800/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002801static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002802GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002803 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002804 // In order to correctly satisfy the ABI, we need to the high part to start
2805 // at offset 8. If the high and low parts we inferred are both 4-byte types
2806 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2807 // the second element at offset 8. Check for this:
2808 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2809 unsigned HiAlign = TD.getABITypeAlignment(Hi);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002810 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002811 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002812
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002813 // To handle this, we have to increase the size of the low part so that the
2814 // second element will start at an 8 byte offset. We can't increase the size
2815 // of the second element because it might make us access off the end of the
2816 // struct.
2817 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002818 // There are usually two sorts of types the ABI generation code can produce
2819 // for the low part of a pair that aren't 8 bytes in size: float or
2820 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2821 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002822 // Promote these to a larger type.
2823 if (Lo->isFloatTy())
2824 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2825 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002826 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2827 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002828 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2829 }
2830 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002831
Reid Kleckneree7cf842014-12-01 22:02:27 +00002832 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002833
2834
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002835 // Verify that the second element is at an 8-byte offset.
2836 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2837 "Invalid x86-64 argument pair!");
2838 return Result;
2839}
2840
Chris Lattner31faff52010-07-28 23:06:14 +00002841ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002842classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002843 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2844 // classification algorithm.
2845 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002846 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002847
2848 // Check some invariants.
2849 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002850 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2851
Craig Topper8a13c412014-05-21 05:09:00 +00002852 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002853 switch (Lo) {
2854 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002855 if (Hi == NoClass)
2856 return ABIArgInfo::getIgnore();
2857 // If the low part is just padding, it takes no register, leave ResType
2858 // null.
2859 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2860 "Unknown missing lo part");
2861 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002862
2863 case SSEUp:
2864 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002865 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002866
2867 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2868 // hidden argument.
2869 case Memory:
2870 return getIndirectReturnResult(RetTy);
2871
2872 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2873 // available register of the sequence %rax, %rdx is used.
2874 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002875 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002876
Chris Lattner1f3a0632010-07-29 21:42:50 +00002877 // If we have a sign or zero extended integer, make sure to return Extend
2878 // so that the parameter gets the right LLVM IR attributes.
2879 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2880 // Treat an enum type as its underlying type.
2881 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2882 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002883
Chris Lattner1f3a0632010-07-29 21:42:50 +00002884 if (RetTy->isIntegralOrEnumerationType() &&
2885 RetTy->isPromotableIntegerType())
2886 return ABIArgInfo::getExtend();
2887 }
Chris Lattner31faff52010-07-28 23:06:14 +00002888 break;
2889
2890 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2891 // available SSE register of the sequence %xmm0, %xmm1 is used.
2892 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002893 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002894 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002895
2896 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2897 // returned on the X87 stack in %st0 as 80-bit x87 number.
2898 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002899 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002900 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002901
2902 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2903 // part of the value is returned in %st0 and the imaginary part in
2904 // %st1.
2905 case ComplexX87:
2906 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002907 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002908 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002909 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002910 break;
2911 }
2912
Craig Topper8a13c412014-05-21 05:09:00 +00002913 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002914 switch (Hi) {
2915 // Memory was handled previously and X87 should
2916 // never occur as a hi class.
2917 case Memory:
2918 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002919 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002920
2921 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002922 case NoClass:
2923 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002924
Chris Lattner52b3c132010-09-01 00:20:33 +00002925 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002926 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002927 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2928 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002929 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002930 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002931 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002932 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2933 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002934 break;
2935
2936 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002937 // is passed in the next available eightbyte chunk if the last used
2938 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002939 //
Chris Lattner57540c52011-04-15 05:22:18 +00002940 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002941 case SSEUp:
2942 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002943 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002944 break;
2945
2946 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2947 // returned together with the previous X87 value in %st0.
2948 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002949 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002950 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002951 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002952 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002953 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002954 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002955 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2956 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002957 }
Chris Lattner31faff52010-07-28 23:06:14 +00002958 break;
2959 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002960
Chris Lattner52b3c132010-09-01 00:20:33 +00002961 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002962 // known to pass in the high eightbyte of the result. We do this by forming a
2963 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002964 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002965 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002966
Chris Lattner1f3a0632010-07-29 21:42:50 +00002967 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002968}
2969
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002970ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002971 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2972 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002973 const
2974{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002975 Ty = useFirstFieldIfTransparentUnion(Ty);
2976
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002977 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002978 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002979
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002980 // Check some invariants.
2981 // FIXME: Enforce these by construction.
2982 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002983 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2984
2985 neededInt = 0;
2986 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002987 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002988 switch (Lo) {
2989 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002990 if (Hi == NoClass)
2991 return ABIArgInfo::getIgnore();
2992 // If the low part is just padding, it takes no register, leave ResType
2993 // null.
2994 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2995 "Unknown missing lo part");
2996 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002997
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002998 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2999 // on the stack.
3000 case Memory:
3001
3002 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3003 // COMPLEX_X87, it is passed in memory.
3004 case X87:
3005 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00003006 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00003007 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003008 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003009
3010 case SSEUp:
3011 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00003012 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003013
3014 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3015 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3016 // and %r9 is used.
3017 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00003018 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003019
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003020 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003021 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00003022
3023 // If we have a sign or zero extended integer, make sure to return Extend
3024 // so that the parameter gets the right LLVM IR attributes.
3025 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3026 // Treat an enum type as its underlying type.
3027 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3028 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003029
Chris Lattner1f3a0632010-07-29 21:42:50 +00003030 if (Ty->isIntegralOrEnumerationType() &&
3031 Ty->isPromotableIntegerType())
3032 return ABIArgInfo::getExtend();
3033 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003034
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003035 break;
3036
3037 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3038 // available SSE register is used, the registers are taken in the
3039 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00003040 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00003041 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00003042 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00003043 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003044 break;
3045 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00003046 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003047
Craig Topper8a13c412014-05-21 05:09:00 +00003048 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003049 switch (Hi) {
3050 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00003051 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003052 // which is passed in memory.
3053 case Memory:
3054 case X87:
3055 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00003056 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003057
3058 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003059
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003060 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003061 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00003062 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00003063 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003064
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003065 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3066 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003067 break;
3068
3069 // X87Up generally doesn't occur here (long double is passed in
3070 // memory), except in situations involving unions.
3071 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003072 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00003073 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003074
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003075 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3076 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003077
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003078 ++neededSSE;
3079 break;
3080
3081 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3082 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003083 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003084 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003085 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003086 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003087 break;
3088 }
3089
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003090 // If a high part was specified, merge it together with the low part. It is
3091 // known to pass in the high eightbyte of the result. We do this by forming a
3092 // first class struct aggregate with the high and low part: {low, high}
3093 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003094 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003095
Chris Lattner1f3a0632010-07-29 21:42:50 +00003096 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003097}
3098
Chris Lattner22326a12010-07-29 02:31:05 +00003099void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003100
Reid Kleckner40ca9132014-05-13 22:05:45 +00003101 if (!getCXXABI().classifyReturnType(FI))
3102 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003103
3104 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003105 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003106
3107 // If the return value is indirect, then the hidden argument is consuming one
3108 // integer register.
3109 if (FI.getReturnInfo().isIndirect())
3110 --freeIntRegs;
3111
Peter Collingbournef7706832014-12-12 23:41:25 +00003112 // The chain argument effectively gives us another free register.
3113 if (FI.isChainCall())
3114 ++freeIntRegs;
3115
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003116 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003117 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3118 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003119 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003120 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003121 it != ie; ++it, ++ArgNo) {
3122 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003123
Bill Wendling9987c0e2010-10-18 23:51:38 +00003124 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003125 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003126 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003127
3128 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3129 // eightbyte of an argument, the whole argument is passed on the
3130 // stack. If registers have already been assigned for some
3131 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003132 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003133 freeIntRegs -= neededInt;
3134 freeSSERegs -= neededSSE;
3135 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003136 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003137 }
3138 }
3139}
3140
John McCall7f416cc2015-09-08 08:05:57 +00003141static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3142 Address VAListAddr, QualType Ty) {
3143 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3144 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003145 llvm::Value *overflow_arg_area =
3146 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3147
3148 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3149 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003150 // It isn't stated explicitly in the standard, but in practice we use
3151 // alignment greater than 16 where necessary.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003152 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3153 if (Align > CharUnits::fromQuantity(8)) {
3154 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3155 Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003156 }
3157
3158 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003159 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003160 llvm::Value *Res =
3161 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003162 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003163
3164 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3165 // l->overflow_arg_area + sizeof(type).
3166 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3167 // an 8 byte boundary.
3168
3169 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003170 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003171 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003172 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3173 "overflow_arg_area.next");
3174 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3175
3176 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
Petar Jovanovic402257b2015-12-04 00:26:47 +00003177 return Address(Res, Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003178}
3179
John McCall7f416cc2015-09-08 08:05:57 +00003180Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3181 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003182 // Assume that va_list type is correct; should be pointer to LLVM type:
3183 // struct {
3184 // i32 gp_offset;
3185 // i32 fp_offset;
3186 // i8* overflow_arg_area;
3187 // i8* reg_save_area;
3188 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003189 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003190
John McCall7f416cc2015-09-08 08:05:57 +00003191 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003192 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003193 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003194
3195 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3196 // in the registers. If not go to step 7.
3197 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003198 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003199
3200 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3201 // general purpose registers needed to pass type and num_fp to hold
3202 // the number of floating point registers needed.
3203
3204 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3205 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3206 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3207 //
3208 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3209 // register save space).
3210
Craig Topper8a13c412014-05-21 05:09:00 +00003211 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003212 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3213 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003214 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003215 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003216 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3217 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003218 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003219 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3220 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003221 }
3222
3223 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003224 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003225 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3226 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003227 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3228 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003229 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3230 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003231 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3232 }
3233
3234 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3235 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3236 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3237 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3238
3239 // Emit code to load the value if it was passed in registers.
3240
3241 CGF.EmitBlock(InRegBlock);
3242
3243 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3244 // an offset of l->gp_offset and/or l->fp_offset. This may require
3245 // copying to a temporary location in case the parameter is passed
3246 // in different register classes or requires an alignment greater
3247 // than 8 for general purpose registers and 16 for XMM registers.
3248 //
3249 // FIXME: This really results in shameful code when we end up needing to
3250 // collect arguments from different places; often what should result in a
3251 // simple assembling of a structure from scattered addresses has many more
3252 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003253 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003254 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3255 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3256 "reg_save_area");
3257
3258 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003259 if (neededInt && neededSSE) {
3260 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003261 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003262 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003263 Address Tmp = CGF.CreateMemTemp(Ty);
3264 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003265 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003266 llvm::Type *TyLo = ST->getElementType(0);
3267 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003268 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003269 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003270 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3271 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003272 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3273 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003274 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3275 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003276
John McCall7f416cc2015-09-08 08:05:57 +00003277 // Copy the first element.
3278 llvm::Value *V =
3279 CGF.Builder.CreateDefaultAlignedLoad(
3280 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3281 CGF.Builder.CreateStore(V,
3282 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3283
3284 // Copy the second element.
3285 V = CGF.Builder.CreateDefaultAlignedLoad(
3286 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3287 CharUnits Offset = CharUnits::fromQuantity(
3288 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3289 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3290
3291 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003292 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003293 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3294 CharUnits::fromQuantity(8));
3295 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003296
3297 // Copy to a temporary if necessary to ensure the appropriate alignment.
3298 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003299 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003300 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003301 CharUnits TyAlign = SizeAlign.second;
3302
3303 // Copy into a temporary if the type is more aligned than the
3304 // register save area.
3305 if (TyAlign.getQuantity() > 8) {
3306 Address Tmp = CGF.CreateMemTemp(Ty);
3307 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003308 RegAddr = Tmp;
3309 }
John McCall7f416cc2015-09-08 08:05:57 +00003310
Chris Lattner0cf24192010-06-28 20:05:43 +00003311 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003312 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3313 CharUnits::fromQuantity(16));
3314 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003315 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003316 assert(neededSSE == 2 && "Invalid number of needed registers!");
3317 // SSE registers are spaced 16 bytes apart in the register save
3318 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003319 // The ABI isn't explicit about this, but it seems reasonable
3320 // to assume that the slots are 16-byte aligned, since the stack is
3321 // naturally 16-byte aligned and the prologue is expected to store
3322 // all the SSE registers to the RSA.
3323 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3324 CharUnits::fromQuantity(16));
3325 Address RegAddrHi =
3326 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3327 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003328 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003329 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003330 llvm::Value *V;
3331 Address Tmp = CGF.CreateMemTemp(Ty);
3332 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3333 V = CGF.Builder.CreateLoad(
3334 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3335 CGF.Builder.CreateStore(V,
3336 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3337 V = CGF.Builder.CreateLoad(
3338 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3339 CGF.Builder.CreateStore(V,
3340 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3341
3342 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003343 }
3344
3345 // AMD64-ABI 3.5.7p5: Step 5. Set:
3346 // l->gp_offset = l->gp_offset + num_gp * 8
3347 // l->fp_offset = l->fp_offset + num_fp * 16.
3348 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003349 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003350 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3351 gp_offset_p);
3352 }
3353 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003354 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003355 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3356 fp_offset_p);
3357 }
3358 CGF.EmitBranch(ContBlock);
3359
3360 // Emit code to load the value if it was passed in memory.
3361
3362 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003363 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003364
3365 // Return the appropriate result.
3366
3367 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003368 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3369 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003370 return ResAddr;
3371}
3372
Charles Davisc7d5c942015-09-17 20:55:33 +00003373Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3374 QualType Ty) const {
3375 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3376 CGF.getContext().getTypeInfoInChars(Ty),
3377 CharUnits::fromQuantity(8),
3378 /*allowHigherAlign*/ false);
3379}
3380
Reid Kleckner80944df2014-10-31 22:00:51 +00003381ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3382 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003383
3384 if (Ty->isVoidType())
3385 return ABIArgInfo::getIgnore();
3386
3387 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3388 Ty = EnumTy->getDecl()->getIntegerType();
3389
Reid Kleckner80944df2014-10-31 22:00:51 +00003390 TypeInfo Info = getContext().getTypeInfo(Ty);
3391 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003392 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003393
Reid Kleckner9005f412014-05-02 00:51:20 +00003394 const RecordType *RT = Ty->getAs<RecordType>();
3395 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003396 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003397 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003398 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003399 }
3400
3401 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003402 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003403
Reid Kleckner9005f412014-05-02 00:51:20 +00003404 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003405
Reid Kleckner80944df2014-10-31 22:00:51 +00003406 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3407 // other targets.
3408 const Type *Base = nullptr;
3409 uint64_t NumElts = 0;
3410 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3411 if (FreeSSERegs >= NumElts) {
3412 FreeSSERegs -= NumElts;
3413 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3414 return ABIArgInfo::getDirect();
3415 return ABIArgInfo::getExpand();
3416 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003417 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003418 }
3419
3420
Reid Klecknerec87fec2014-05-02 01:17:12 +00003421 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003422 // If the member pointer is represented by an LLVM int or ptr, pass it
3423 // directly.
3424 llvm::Type *LLTy = CGT.ConvertType(Ty);
3425 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3426 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003427 }
3428
Michael Kuperstein4f818702015-02-24 09:35:58 +00003429 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003430 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3431 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003432 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003433 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003434
Reid Kleckner9005f412014-05-02 00:51:20 +00003435 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003436 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003437 }
3438
Julien Lerouge10dcff82014-08-27 00:36:55 +00003439 // Bool type is always extended to the ABI, other builtin types are not
3440 // extended.
3441 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3442 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003443 return ABIArgInfo::getExtend();
3444
Reid Kleckner11a17192015-10-28 22:29:52 +00003445 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3446 // passes them indirectly through memory.
3447 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3448 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3449 if (LDF == &llvm::APFloat::x87DoubleExtended)
3450 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3451 }
3452
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003453 return ABIArgInfo::getDirect();
3454}
3455
3456void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003457 bool IsVectorCall =
3458 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003459
Reid Kleckner80944df2014-10-31 22:00:51 +00003460 // We can use up to 4 SSE return registers with vectorcall.
3461 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3462 if (!getCXXABI().classifyReturnType(FI))
3463 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3464
3465 // We can use up to 6 SSE register parameters with vectorcall.
3466 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003467 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003468 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003469}
3470
John McCall7f416cc2015-09-08 08:05:57 +00003471Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3472 QualType Ty) const {
3473 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3474 CGF.getContext().getTypeInfoInChars(Ty),
3475 CharUnits::fromQuantity(8),
3476 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003477}
Chris Lattner0cf24192010-06-28 20:05:43 +00003478
John McCallea8d8bb2010-03-11 00:10:12 +00003479// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003480namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003481/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3482class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003483bool IsSoftFloatABI;
John McCallea8d8bb2010-03-11 00:10:12 +00003484public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003485 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
3486 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
Roman Divacky8a12d842014-11-03 18:32:54 +00003487
John McCall7f416cc2015-09-08 08:05:57 +00003488 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3489 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003490};
3491
3492class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3493public:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003494 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
3495 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003496
Craig Topper4f12f102014-03-12 06:41:41 +00003497 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003498 // This is recovered from gcc output.
3499 return 1; // r1 is the dedicated stack pointer
3500 }
3501
3502 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003503 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003504};
3505
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003506}
John McCallea8d8bb2010-03-11 00:10:12 +00003507
John McCall7f416cc2015-09-08 08:05:57 +00003508Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3509 QualType Ty) const {
Roman Divacky039b9702016-02-20 08:31:24 +00003510 const unsigned OverflowLimit = 8;
Roman Divacky8a12d842014-11-03 18:32:54 +00003511 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3512 // TODO: Implement this. For now ignore.
3513 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003514 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003515 }
3516
John McCall7f416cc2015-09-08 08:05:57 +00003517 // struct __va_list_tag {
3518 // unsigned char gpr;
3519 // unsigned char fpr;
3520 // unsigned short reserved;
3521 // void *overflow_arg_area;
3522 // void *reg_save_area;
3523 // };
3524
Roman Divacky8a12d842014-11-03 18:32:54 +00003525 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003526 bool isInt =
3527 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003528 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
John McCall7f416cc2015-09-08 08:05:57 +00003529
3530 // All aggregates are passed indirectly? That doesn't seem consistent
3531 // with the argument-lowering code.
3532 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003533
3534 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003535
3536 // The calling convention either uses 1-2 GPRs or 1 FPR.
3537 Address NumRegsAddr = Address::invalid();
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003538 if (isInt || IsSoftFloatABI) {
John McCall7f416cc2015-09-08 08:05:57 +00003539 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3540 } else {
3541 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003542 }
John McCall7f416cc2015-09-08 08:05:57 +00003543
3544 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3545
3546 // "Align" the register count when TY is i64.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003547 if (isI64 || (isF64 && IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003548 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3549 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3550 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003551
Eric Christopher7565e0d2015-05-29 23:09:49 +00003552 llvm::Value *CC =
Roman Divacky039b9702016-02-20 08:31:24 +00003553 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003554
3555 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3556 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3557 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3558
3559 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3560
John McCall7f416cc2015-09-08 08:05:57 +00003561 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3562 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003563
John McCall7f416cc2015-09-08 08:05:57 +00003564 // Case 1: consume registers.
3565 Address RegAddr = Address::invalid();
3566 {
3567 CGF.EmitBlock(UsingRegs);
3568
3569 Address RegSaveAreaPtr =
3570 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3571 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3572 CharUnits::fromQuantity(8));
3573 assert(RegAddr.getElementType() == CGF.Int8Ty);
3574
3575 // Floating-point registers start after the general-purpose registers.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003576 if (!(isInt || IsSoftFloatABI)) {
John McCall7f416cc2015-09-08 08:05:57 +00003577 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3578 CharUnits::fromQuantity(32));
3579 }
3580
3581 // Get the address of the saved value by scaling the number of
3582 // registers we've used by the number of
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003583 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
John McCall7f416cc2015-09-08 08:05:57 +00003584 llvm::Value *RegOffset =
3585 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3586 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3587 RegAddr.getPointer(), RegOffset),
3588 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3589 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3590
3591 // Increase the used-register count.
Petar Jovanovic88a328f2015-12-14 17:51:50 +00003592 NumRegs =
3593 Builder.CreateAdd(NumRegs,
3594 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
John McCall7f416cc2015-09-08 08:05:57 +00003595 Builder.CreateStore(NumRegs, NumRegsAddr);
3596
3597 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003598 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003599
John McCall7f416cc2015-09-08 08:05:57 +00003600 // Case 2: consume space in the overflow area.
3601 Address MemAddr = Address::invalid();
3602 {
3603 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003604
Roman Divacky039b9702016-02-20 08:31:24 +00003605 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
3606
John McCall7f416cc2015-09-08 08:05:57 +00003607 // Everything in the overflow area is rounded up to a size of at least 4.
3608 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3609
3610 CharUnits Size;
3611 if (!isIndirect) {
3612 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
Rui Ueyama83aa9792016-01-14 21:00:27 +00003613 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
John McCall7f416cc2015-09-08 08:05:57 +00003614 } else {
3615 Size = CGF.getPointerSize();
3616 }
3617
3618 Address OverflowAreaAddr =
3619 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
Petar Jovanovic402257b2015-12-04 00:26:47 +00003620 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
John McCall7f416cc2015-09-08 08:05:57 +00003621 OverflowAreaAlign);
Petar Jovanovic402257b2015-12-04 00:26:47 +00003622 // Round up address of argument to alignment
3623 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3624 if (Align > OverflowAreaAlign) {
3625 llvm::Value *Ptr = OverflowArea.getPointer();
3626 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
3627 Align);
3628 }
3629
John McCall7f416cc2015-09-08 08:05:57 +00003630 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3631
3632 // Increase the overflow area.
3633 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3634 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3635 CGF.EmitBranch(Cont);
3636 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003637
3638 CGF.EmitBlock(Cont);
3639
John McCall7f416cc2015-09-08 08:05:57 +00003640 // Merge the cases with a phi.
3641 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3642 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003643
John McCall7f416cc2015-09-08 08:05:57 +00003644 // Load the pointer if the argument was passed indirectly.
3645 if (isIndirect) {
3646 Result = Address(Builder.CreateLoad(Result, "aggr"),
3647 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003648 }
3649
3650 return Result;
3651}
3652
John McCallea8d8bb2010-03-11 00:10:12 +00003653bool
3654PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3655 llvm::Value *Address) const {
3656 // This is calculated from the LLVM and GCC tables and verified
3657 // against gcc output. AFAIK all ABIs use the same encoding.
3658
3659 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003660
Chris Lattnerece04092012-02-07 00:39:47 +00003661 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003662 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3663 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3664 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3665
3666 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003667 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003668
3669 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003670 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003671
3672 // 64-76 are various 4-byte special-purpose registers:
3673 // 64: mq
3674 // 65: lr
3675 // 66: ctr
3676 // 67: ap
3677 // 68-75 cr0-7
3678 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003679 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003680
3681 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003682 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003683
3684 // 109: vrsave
3685 // 110: vscr
3686 // 111: spe_acc
3687 // 112: spefscr
3688 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003689 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003690
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003691 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003692}
3693
Roman Divackyd966e722012-05-09 18:22:46 +00003694// PowerPC-64
3695
3696namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003697/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3698class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003699public:
3700 enum ABIKind {
3701 ELFv1 = 0,
3702 ELFv2
3703 };
3704
3705private:
3706 static const unsigned GPRBits = 64;
3707 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003708 bool HasQPX;
3709
3710 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3711 // will be passed in a QPX register.
3712 bool IsQPXVectorTy(const Type *Ty) const {
3713 if (!HasQPX)
3714 return false;
3715
3716 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3717 unsigned NumElements = VT->getNumElements();
3718 if (NumElements == 1)
3719 return false;
3720
3721 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3722 if (getContext().getTypeSize(Ty) <= 256)
3723 return true;
3724 } else if (VT->getElementType()->
3725 isSpecificBuiltinType(BuiltinType::Float)) {
3726 if (getContext().getTypeSize(Ty) <= 128)
3727 return true;
3728 }
3729 }
3730
3731 return false;
3732 }
3733
3734 bool IsQPXVectorTy(QualType Ty) const {
3735 return IsQPXVectorTy(Ty.getTypePtr());
3736 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003737
3738public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003739 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3740 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003741
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003742 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003743 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003744
3745 ABIArgInfo classifyReturnType(QualType RetTy) const;
3746 ABIArgInfo classifyArgumentType(QualType Ty) const;
3747
Reid Klecknere9f6a712014-10-31 17:10:41 +00003748 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3749 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3750 uint64_t Members) const override;
3751
Bill Schmidt84d37792012-10-12 19:26:17 +00003752 // TODO: We can add more logic to computeInfo to improve performance.
3753 // Example: For aggregate arguments that fit in a register, we could
3754 // use getDirectInReg (as is done below for structs containing a single
3755 // floating-point value) to avoid pushing them to memory on function
3756 // entry. This would require changing the logic in PPCISelLowering
3757 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003758 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003759 if (!getCXXABI().classifyReturnType(FI))
3760 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003761 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003762 // We rely on the default argument classification for the most part.
3763 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003764 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003765 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003766 if (T) {
3767 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003768 if (IsQPXVectorTy(T) ||
3769 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003770 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003771 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003772 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003773 continue;
3774 }
3775 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003776 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003777 }
3778 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003779
John McCall7f416cc2015-09-08 08:05:57 +00003780 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3781 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003782};
3783
3784class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003785
Bill Schmidt25cb3492012-10-03 19:18:57 +00003786public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003787 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003788 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003789 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003790
Craig Topper4f12f102014-03-12 06:41:41 +00003791 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003792 // This is recovered from gcc output.
3793 return 1; // r1 is the dedicated stack pointer
3794 }
3795
3796 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003797 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003798};
3799
Roman Divackyd966e722012-05-09 18:22:46 +00003800class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3801public:
3802 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3803
Craig Topper4f12f102014-03-12 06:41:41 +00003804 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003805 // This is recovered from gcc output.
3806 return 1; // r1 is the dedicated stack pointer
3807 }
3808
3809 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003810 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003811};
3812
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003813}
Roman Divackyd966e722012-05-09 18:22:46 +00003814
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003815// Return true if the ABI requires Ty to be passed sign- or zero-
3816// extended to 64 bits.
3817bool
3818PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3819 // Treat an enum type as its underlying type.
3820 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3821 Ty = EnumTy->getDecl()->getIntegerType();
3822
3823 // Promotable integer types are required to be promoted by the ABI.
3824 if (Ty->isPromotableIntegerType())
3825 return true;
3826
3827 // In addition to the usual promotable integer types, we also need to
3828 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3829 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3830 switch (BT->getKind()) {
3831 case BuiltinType::Int:
3832 case BuiltinType::UInt:
3833 return true;
3834 default:
3835 break;
3836 }
3837
3838 return false;
3839}
3840
John McCall7f416cc2015-09-08 08:05:57 +00003841/// isAlignedParamType - Determine whether a type requires 16-byte or
3842/// higher alignment in the parameter area. Always returns at least 8.
3843CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003844 // Complex types are passed just like their elements.
3845 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3846 Ty = CTy->getElementType();
3847
3848 // Only vector types of size 16 bytes need alignment (larger types are
3849 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003850 if (IsQPXVectorTy(Ty)) {
3851 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003852 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003853
John McCall7f416cc2015-09-08 08:05:57 +00003854 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003855 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003856 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003857 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003858
3859 // For single-element float/vector structs, we consider the whole type
3860 // to have the same alignment requirements as its single element.
3861 const Type *AlignAsType = nullptr;
3862 const Type *EltType = isSingleElementStruct(Ty, getContext());
3863 if (EltType) {
3864 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003865 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003866 getContext().getTypeSize(EltType) == 128) ||
3867 (BT && BT->isFloatingPoint()))
3868 AlignAsType = EltType;
3869 }
3870
Ulrich Weigandb7122372014-07-21 00:48:09 +00003871 // Likewise for ELFv2 homogeneous aggregates.
3872 const Type *Base = nullptr;
3873 uint64_t Members = 0;
3874 if (!AlignAsType && Kind == ELFv2 &&
3875 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3876 AlignAsType = Base;
3877
Ulrich Weigand581badc2014-07-10 17:20:07 +00003878 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003879 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3880 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003881 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003882
John McCall7f416cc2015-09-08 08:05:57 +00003883 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003884 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003885 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003886 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003887
3888 // Otherwise, we only need alignment for any aggregate type that
3889 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003890 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3891 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003892 return CharUnits::fromQuantity(32);
3893 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003894 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003895
John McCall7f416cc2015-09-08 08:05:57 +00003896 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003897}
3898
Ulrich Weigandb7122372014-07-21 00:48:09 +00003899/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3900/// aggregate. Base is set to the base element type, and Members is set
3901/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003902bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3903 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003904 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3905 uint64_t NElements = AT->getSize().getZExtValue();
3906 if (NElements == 0)
3907 return false;
3908 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3909 return false;
3910 Members *= NElements;
3911 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3912 const RecordDecl *RD = RT->getDecl();
3913 if (RD->hasFlexibleArrayMember())
3914 return false;
3915
3916 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003917
3918 // If this is a C++ record, check the bases first.
3919 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3920 for (const auto &I : CXXRD->bases()) {
3921 // Ignore empty records.
3922 if (isEmptyRecord(getContext(), I.getType(), true))
3923 continue;
3924
3925 uint64_t FldMembers;
3926 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3927 return false;
3928
3929 Members += FldMembers;
3930 }
3931 }
3932
Ulrich Weigandb7122372014-07-21 00:48:09 +00003933 for (const auto *FD : RD->fields()) {
3934 // Ignore (non-zero arrays of) empty records.
3935 QualType FT = FD->getType();
3936 while (const ConstantArrayType *AT =
3937 getContext().getAsConstantArrayType(FT)) {
3938 if (AT->getSize().getZExtValue() == 0)
3939 return false;
3940 FT = AT->getElementType();
3941 }
3942 if (isEmptyRecord(getContext(), FT, true))
3943 continue;
3944
3945 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3946 if (getContext().getLangOpts().CPlusPlus &&
3947 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3948 continue;
3949
3950 uint64_t FldMembers;
3951 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3952 return false;
3953
3954 Members = (RD->isUnion() ?
3955 std::max(Members, FldMembers) : Members + FldMembers);
3956 }
3957
3958 if (!Base)
3959 return false;
3960
3961 // Ensure there is no padding.
3962 if (getContext().getTypeSize(Base) * Members !=
3963 getContext().getTypeSize(Ty))
3964 return false;
3965 } else {
3966 Members = 1;
3967 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3968 Members = 2;
3969 Ty = CT->getElementType();
3970 }
3971
Reid Klecknere9f6a712014-10-31 17:10:41 +00003972 // Most ABIs only support float, double, and some vector type widths.
3973 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003974 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003975
3976 // The base type must be the same for all members. Types that
3977 // agree in both total size and mode (float vs. vector) are
3978 // treated as being equivalent here.
3979 const Type *TyPtr = Ty.getTypePtr();
3980 if (!Base)
3981 Base = TyPtr;
3982
3983 if (Base->isVectorType() != TyPtr->isVectorType() ||
3984 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3985 return false;
3986 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003987 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3988}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003989
Reid Klecknere9f6a712014-10-31 17:10:41 +00003990bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3991 // Homogeneous aggregates for ELFv2 must have base types of float,
3992 // double, long double, or 128-bit vectors.
3993 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3994 if (BT->getKind() == BuiltinType::Float ||
3995 BT->getKind() == BuiltinType::Double ||
3996 BT->getKind() == BuiltinType::LongDouble)
3997 return true;
3998 }
3999 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004000 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00004001 return true;
4002 }
4003 return false;
4004}
4005
4006bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4007 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00004008 // Vector types require one register, floating point types require one
4009 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004010 uint32_t NumRegs =
4011 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004012
4013 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00004014 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00004015}
4016
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004017ABIArgInfo
4018PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004019 Ty = useFirstFieldIfTransparentUnion(Ty);
4020
Bill Schmidt90b22c92012-11-27 02:46:43 +00004021 if (Ty->isAnyComplexType())
4022 return ABIArgInfo::getDirect();
4023
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004024 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4025 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004026 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004027 uint64_t Size = getContext().getTypeSize(Ty);
4028 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004029 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004030 else if (Size < 128) {
4031 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4032 return ABIArgInfo::getDirect(CoerceTy);
4033 }
4034 }
4035
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004036 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00004037 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00004038 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004039
John McCall7f416cc2015-09-08 08:05:57 +00004040 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4041 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00004042
4043 // ELFv2 homogeneous aggregates are passed as array types.
4044 const Type *Base = nullptr;
4045 uint64_t Members = 0;
4046 if (Kind == ELFv2 &&
4047 isHomogeneousAggregate(Ty, Base, Members)) {
4048 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4049 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4050 return ABIArgInfo::getDirect(CoerceTy);
4051 }
4052
Ulrich Weigand601957f2014-07-21 00:56:36 +00004053 // If an aggregate may end up fully in registers, we do not
4054 // use the ByVal method, but pass the aggregate as array.
4055 // This is usually beneficial since we avoid forcing the
4056 // back-end to store the argument to memory.
4057 uint64_t Bits = getContext().getTypeSize(Ty);
4058 if (Bits > 0 && Bits <= 8 * GPRBits) {
4059 llvm::Type *CoerceTy;
4060
4061 // Types up to 8 bytes are passed as integer type (which will be
4062 // properly aligned in the argument save area doubleword).
4063 if (Bits <= GPRBits)
Rui Ueyama83aa9792016-01-14 21:00:27 +00004064 CoerceTy =
4065 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigand601957f2014-07-21 00:56:36 +00004066 // Larger types are passed as arrays, with the base type selected
4067 // according to the required alignment in the save area.
4068 else {
4069 uint64_t RegBits = ABIAlign * 8;
Rui Ueyama83aa9792016-01-14 21:00:27 +00004070 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
Ulrich Weigand601957f2014-07-21 00:56:36 +00004071 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4072 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4073 }
4074
4075 return ABIArgInfo::getDirect(CoerceTy);
4076 }
4077
Ulrich Weigandb7122372014-07-21 00:48:09 +00004078 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004079 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4080 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004081 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004082 }
4083
4084 return (isPromotableTypeForABI(Ty) ?
4085 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4086}
4087
4088ABIArgInfo
4089PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4090 if (RetTy->isVoidType())
4091 return ABIArgInfo::getIgnore();
4092
Bill Schmidta3d121c2012-12-17 04:20:17 +00004093 if (RetTy->isAnyComplexType())
4094 return ABIArgInfo::getDirect();
4095
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004096 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4097 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004098 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004099 uint64_t Size = getContext().getTypeSize(RetTy);
4100 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004101 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004102 else if (Size < 128) {
4103 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4104 return ABIArgInfo::getDirect(CoerceTy);
4105 }
4106 }
4107
Ulrich Weigandb7122372014-07-21 00:48:09 +00004108 if (isAggregateTypeForABI(RetTy)) {
4109 // ELFv2 homogeneous aggregates are returned as array types.
4110 const Type *Base = nullptr;
4111 uint64_t Members = 0;
4112 if (Kind == ELFv2 &&
4113 isHomogeneousAggregate(RetTy, Base, Members)) {
4114 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4115 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4116 return ABIArgInfo::getDirect(CoerceTy);
4117 }
4118
4119 // ELFv2 small aggregates are returned in up to two registers.
4120 uint64_t Bits = getContext().getTypeSize(RetTy);
4121 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4122 if (Bits == 0)
4123 return ABIArgInfo::getIgnore();
4124
4125 llvm::Type *CoerceTy;
4126 if (Bits > GPRBits) {
4127 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004128 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004129 } else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004130 CoerceTy =
4131 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
Ulrich Weigandb7122372014-07-21 00:48:09 +00004132 return ABIArgInfo::getDirect(CoerceTy);
4133 }
4134
4135 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004136 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004137 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004138
4139 return (isPromotableTypeForABI(RetTy) ?
4140 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4141}
4142
Bill Schmidt25cb3492012-10-03 19:18:57 +00004143// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004144Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4145 QualType Ty) const {
4146 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4147 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004148
John McCall7f416cc2015-09-08 08:05:57 +00004149 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004150
Bill Schmidt924c4782013-01-14 17:45:36 +00004151 // If we have a complex type and the base type is smaller than 8 bytes,
4152 // the ABI calls for the real and imaginary parts to be right-adjusted
4153 // in separate doublewords. However, Clang expects us to produce a
4154 // pointer to a structure with the two parts packed tightly. So generate
4155 // loads of the real and imaginary parts relative to the va_list pointer,
4156 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004157 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4158 CharUnits EltSize = TypeInfo.first / 2;
4159 if (EltSize < SlotSize) {
4160 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4161 SlotSize * 2, SlotSize,
4162 SlotSize, /*AllowHigher*/ true);
4163
4164 Address RealAddr = Addr;
4165 Address ImagAddr = RealAddr;
4166 if (CGF.CGM.getDataLayout().isBigEndian()) {
4167 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4168 SlotSize - EltSize);
4169 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4170 2 * SlotSize - EltSize);
4171 } else {
4172 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4173 }
4174
4175 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4176 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4177 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4178 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4179 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4180
4181 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4182 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4183 /*init*/ true);
4184 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004185 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004186 }
4187
John McCall7f416cc2015-09-08 08:05:57 +00004188 // Otherwise, just use the general rule.
4189 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4190 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004191}
4192
4193static bool
4194PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4195 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004196 // This is calculated from the LLVM and GCC tables and verified
4197 // against gcc output. AFAIK all ABIs use the same encoding.
4198
4199 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4200
4201 llvm::IntegerType *i8 = CGF.Int8Ty;
4202 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4203 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4204 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4205
4206 // 0-31: r0-31, the 8-byte general-purpose registers
4207 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4208
4209 // 32-63: fp0-31, the 8-byte floating-point registers
4210 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4211
4212 // 64-76 are various 4-byte special-purpose registers:
4213 // 64: mq
4214 // 65: lr
4215 // 66: ctr
4216 // 67: ap
4217 // 68-75 cr0-7
4218 // 76: xer
4219 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4220
4221 // 77-108: v0-31, the 16-byte vector registers
4222 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4223
4224 // 109: vrsave
4225 // 110: vscr
4226 // 111: spe_acc
4227 // 112: spefscr
4228 // 113: sfp
4229 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4230
4231 return false;
4232}
John McCallea8d8bb2010-03-11 00:10:12 +00004233
Bill Schmidt25cb3492012-10-03 19:18:57 +00004234bool
4235PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4236 CodeGen::CodeGenFunction &CGF,
4237 llvm::Value *Address) const {
4238
4239 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4240}
4241
4242bool
4243PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4244 llvm::Value *Address) const {
4245
4246 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4247}
4248
Chris Lattner0cf24192010-06-28 20:05:43 +00004249//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004250// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004251//===----------------------------------------------------------------------===//
4252
4253namespace {
4254
Tim Northover573cbee2014-05-24 12:52:07 +00004255class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004256public:
4257 enum ABIKind {
4258 AAPCS = 0,
4259 DarwinPCS
4260 };
4261
4262private:
4263 ABIKind Kind;
4264
4265public:
Tim Northover573cbee2014-05-24 12:52:07 +00004266 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004267
4268private:
4269 ABIKind getABIKind() const { return Kind; }
4270 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4271
4272 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004273 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004274 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4275 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4276 uint64_t Members) const override;
4277
Tim Northovera2ee4332014-03-29 15:09:45 +00004278 bool isIllegalVectorType(QualType Ty) const;
4279
David Blaikie1cbb9712014-11-14 19:09:44 +00004280 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004281 if (!getCXXABI().classifyReturnType(FI))
4282 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004283
Tim Northoverb047bfa2014-11-27 21:02:49 +00004284 for (auto &it : FI.arguments())
4285 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004286 }
4287
John McCall7f416cc2015-09-08 08:05:57 +00004288 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4289 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004290
John McCall7f416cc2015-09-08 08:05:57 +00004291 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4292 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004293
John McCall7f416cc2015-09-08 08:05:57 +00004294 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4295 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004296 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4297 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4298 }
4299};
4300
Tim Northover573cbee2014-05-24 12:52:07 +00004301class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004302public:
Tim Northover573cbee2014-05-24 12:52:07 +00004303 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4304 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004305
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004306 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004307 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4308 }
4309
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004310 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4311 return 31;
4312 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004313
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004314 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004315};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004316}
Tim Northovera2ee4332014-03-29 15:09:45 +00004317
Tim Northoverb047bfa2014-11-27 21:02:49 +00004318ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004319 Ty = useFirstFieldIfTransparentUnion(Ty);
4320
Tim Northovera2ee4332014-03-29 15:09:45 +00004321 // Handle illegal vector types here.
4322 if (isIllegalVectorType(Ty)) {
4323 uint64_t Size = getContext().getTypeSize(Ty);
Nirav Dave9a8f97e2016-02-22 16:48:42 +00004324 // Android promotes <2 x i8> to i16, not i32
4325 if(isAndroid() && (Size <= 16)) {
4326 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
4327 return ABIArgInfo::getDirect(ResType);
4328 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004329 if (Size <= 32) {
4330 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004331 return ABIArgInfo::getDirect(ResType);
4332 }
4333 if (Size == 64) {
4334 llvm::Type *ResType =
4335 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004336 return ABIArgInfo::getDirect(ResType);
4337 }
4338 if (Size == 128) {
4339 llvm::Type *ResType =
4340 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004341 return ABIArgInfo::getDirect(ResType);
4342 }
John McCall7f416cc2015-09-08 08:05:57 +00004343 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004344 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004345
4346 if (!isAggregateTypeForABI(Ty)) {
4347 // Treat an enum type as its underlying type.
4348 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4349 Ty = EnumTy->getDecl()->getIntegerType();
4350
Tim Northovera2ee4332014-03-29 15:09:45 +00004351 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4352 ? ABIArgInfo::getExtend()
4353 : ABIArgInfo::getDirect());
4354 }
4355
4356 // Structures with either a non-trivial destructor or a non-trivial
4357 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004358 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004359 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4360 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004361 }
4362
4363 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4364 // elsewhere for GNU compatibility.
4365 if (isEmptyRecord(getContext(), Ty, true)) {
4366 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4367 return ABIArgInfo::getIgnore();
4368
Tim Northovera2ee4332014-03-29 15:09:45 +00004369 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4370 }
4371
4372 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004373 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004374 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004375 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004376 return ABIArgInfo::getDirect(
4377 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004378 }
4379
4380 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4381 uint64_t Size = getContext().getTypeSize(Ty);
4382 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004383 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004384 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004385
Tim Northovera2ee4332014-03-29 15:09:45 +00004386 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4387 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004388 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004389 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4390 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4391 }
4392 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4393 }
4394
John McCall7f416cc2015-09-08 08:05:57 +00004395 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004396}
4397
Tim Northover573cbee2014-05-24 12:52:07 +00004398ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004399 if (RetTy->isVoidType())
4400 return ABIArgInfo::getIgnore();
4401
4402 // Large vector types should be returned via memory.
4403 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004404 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004405
4406 if (!isAggregateTypeForABI(RetTy)) {
4407 // Treat an enum type as its underlying type.
4408 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4409 RetTy = EnumTy->getDecl()->getIntegerType();
4410
Tim Northover4dab6982014-04-18 13:46:08 +00004411 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4412 ? ABIArgInfo::getExtend()
4413 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004414 }
4415
Tim Northovera2ee4332014-03-29 15:09:45 +00004416 if (isEmptyRecord(getContext(), RetTy, true))
4417 return ABIArgInfo::getIgnore();
4418
Craig Topper8a13c412014-05-21 05:09:00 +00004419 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004420 uint64_t Members = 0;
4421 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004422 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4423 return ABIArgInfo::getDirect();
4424
4425 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4426 uint64_t Size = getContext().getTypeSize(RetTy);
4427 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004428 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004429 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004430
4431 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4432 // For aggregates with 16-byte alignment, we use i128.
4433 if (Alignment < 128 && Size == 128) {
4434 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4435 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4436 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004437 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4438 }
4439
John McCall7f416cc2015-09-08 08:05:57 +00004440 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004441}
4442
Tim Northover573cbee2014-05-24 12:52:07 +00004443/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4444bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004445 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4446 // Check whether VT is legal.
4447 unsigned NumElements = VT->getNumElements();
4448 uint64_t Size = getContext().getTypeSize(VT);
4449 // NumElements should be power of 2 between 1 and 16.
4450 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4451 return true;
4452 return Size != 64 && (Size != 128 || NumElements == 1);
4453 }
4454 return false;
4455}
4456
Reid Klecknere9f6a712014-10-31 17:10:41 +00004457bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4458 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4459 // point type or a short-vector type. This is the same as the 32-bit ABI,
4460 // but with the difference that any floating-point type is allowed,
4461 // including __fp16.
4462 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4463 if (BT->isFloatingPoint())
4464 return true;
4465 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4466 unsigned VecSize = getContext().getTypeSize(VT);
4467 if (VecSize == 64 || VecSize == 128)
4468 return true;
4469 }
4470 return false;
4471}
4472
4473bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4474 uint64_t Members) const {
4475 return Members <= 4;
4476}
4477
John McCall7f416cc2015-09-08 08:05:57 +00004478Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004479 QualType Ty,
4480 CodeGenFunction &CGF) const {
4481 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004482 bool IsIndirect = AI.isIndirect();
4483
Tim Northoverb047bfa2014-11-27 21:02:49 +00004484 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4485 if (IsIndirect)
4486 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4487 else if (AI.getCoerceToType())
4488 BaseTy = AI.getCoerceToType();
4489
4490 unsigned NumRegs = 1;
4491 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4492 BaseTy = ArrTy->getElementType();
4493 NumRegs = ArrTy->getNumElements();
4494 }
4495 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4496
Tim Northovera2ee4332014-03-29 15:09:45 +00004497 // The AArch64 va_list type and handling is specified in the Procedure Call
4498 // Standard, section B.4:
4499 //
4500 // struct {
4501 // void *__stack;
4502 // void *__gr_top;
4503 // void *__vr_top;
4504 // int __gr_offs;
4505 // int __vr_offs;
4506 // };
4507
4508 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4509 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4510 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4511 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004512
John McCall7f416cc2015-09-08 08:05:57 +00004513 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4514 CharUnits TyAlign = TyInfo.second;
4515
4516 Address reg_offs_p = Address::invalid();
4517 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004518 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004519 CharUnits reg_top_offset;
4520 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004521 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004522 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004523 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004524 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4525 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004526 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4527 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004528 reg_top_offset = CharUnits::fromQuantity(8);
Rui Ueyama83aa9792016-01-14 21:00:27 +00004529 RegSize = llvm::alignTo(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004530 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004531 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004532 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004533 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4534 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004535 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4536 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004537 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004538 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004539 }
4540
4541 //=======================================
4542 // Find out where argument was passed
4543 //=======================================
4544
4545 // If reg_offs >= 0 we're already using the stack for this type of
4546 // argument. We don't want to keep updating reg_offs (in case it overflows,
4547 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4548 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004549 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004550 UsingStack = CGF.Builder.CreateICmpSGE(
4551 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4552
4553 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4554
4555 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004556 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004557 CGF.EmitBlock(MaybeRegBlock);
4558
4559 // Integer arguments may need to correct register alignment (for example a
4560 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4561 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004562 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4563 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004564
4565 reg_offs = CGF.Builder.CreateAdd(
4566 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4567 "align_regoffs");
4568 reg_offs = CGF.Builder.CreateAnd(
4569 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4570 "aligned_regoffs");
4571 }
4572
4573 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004574 // The fact that this is done unconditionally reflects the fact that
4575 // allocating an argument to the stack also uses up all the remaining
4576 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004577 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004578 NewOffset = CGF.Builder.CreateAdd(
4579 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4580 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4581
4582 // Now we're in a position to decide whether this argument really was in
4583 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004584 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004585 InRegs = CGF.Builder.CreateICmpSLE(
4586 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4587
4588 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4589
4590 //=======================================
4591 // Argument was in registers
4592 //=======================================
4593
4594 // Now we emit the code for if the argument was originally passed in
4595 // registers. First start the appropriate block:
4596 CGF.EmitBlock(InRegBlock);
4597
John McCall7f416cc2015-09-08 08:05:57 +00004598 llvm::Value *reg_top = nullptr;
4599 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4600 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004601 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004602 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4603 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4604 Address RegAddr = Address::invalid();
4605 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004606
4607 if (IsIndirect) {
4608 // If it's been passed indirectly (actually a struct), whatever we find from
4609 // stored registers or on the stack will actually be a struct **.
4610 MemTy = llvm::PointerType::getUnqual(MemTy);
4611 }
4612
Craig Topper8a13c412014-05-21 05:09:00 +00004613 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004614 uint64_t NumMembers = 0;
4615 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004616 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004617 // Homogeneous aggregates passed in registers will have their elements split
4618 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4619 // qN+1, ...). We reload and store into a temporary local variable
4620 // contiguously.
4621 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004622 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004623 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4624 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004625 Address Tmp = CGF.CreateTempAlloca(HFATy,
4626 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004627
John McCall7f416cc2015-09-08 08:05:57 +00004628 // On big-endian platforms, the value will be right-aligned in its slot.
4629 int Offset = 0;
4630 if (CGF.CGM.getDataLayout().isBigEndian() &&
4631 BaseTyInfo.first.getQuantity() < 16)
4632 Offset = 16 - BaseTyInfo.first.getQuantity();
4633
Tim Northovera2ee4332014-03-29 15:09:45 +00004634 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004635 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4636 Address LoadAddr =
4637 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4638 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4639
4640 Address StoreAddr =
4641 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004642
4643 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4644 CGF.Builder.CreateStore(Elem, StoreAddr);
4645 }
4646
John McCall7f416cc2015-09-08 08:05:57 +00004647 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004648 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004649 // Otherwise the object is contiguous in memory.
4650
4651 // It might be right-aligned in its slot.
4652 CharUnits SlotSize = BaseAddr.getAlignment();
4653 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004654 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004655 TyInfo.first < SlotSize) {
4656 CharUnits Offset = SlotSize - TyInfo.first;
4657 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004658 }
4659
John McCall7f416cc2015-09-08 08:05:57 +00004660 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004661 }
4662
4663 CGF.EmitBranch(ContBlock);
4664
4665 //=======================================
4666 // Argument was on the stack
4667 //=======================================
4668 CGF.EmitBlock(OnStackBlock);
4669
John McCall7f416cc2015-09-08 08:05:57 +00004670 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4671 CharUnits::Zero(), "stack_p");
4672 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004673
John McCall7f416cc2015-09-08 08:05:57 +00004674 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004675 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004676 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4677 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004678
John McCall7f416cc2015-09-08 08:05:57 +00004679 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004680
John McCall7f416cc2015-09-08 08:05:57 +00004681 OnStackPtr = CGF.Builder.CreateAdd(
4682 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004683 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004684 OnStackPtr = CGF.Builder.CreateAnd(
4685 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004686 "align_stack");
4687
John McCall7f416cc2015-09-08 08:05:57 +00004688 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004689 }
John McCall7f416cc2015-09-08 08:05:57 +00004690 Address OnStackAddr(OnStackPtr,
4691 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004692
John McCall7f416cc2015-09-08 08:05:57 +00004693 // All stack slots are multiples of 8 bytes.
4694 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4695 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004696 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004697 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004698 else
Rui Ueyama83aa9792016-01-14 21:00:27 +00004699 StackSize = TyInfo.first.alignTo(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004700
John McCall7f416cc2015-09-08 08:05:57 +00004701 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004702 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004703 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004704
4705 // Write the new value of __stack for the next call to va_arg
4706 CGF.Builder.CreateStore(NewStack, stack_p);
4707
4708 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004709 TyInfo.first < StackSlotSize) {
4710 CharUnits Offset = StackSlotSize - TyInfo.first;
4711 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004712 }
4713
John McCall7f416cc2015-09-08 08:05:57 +00004714 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004715
4716 CGF.EmitBranch(ContBlock);
4717
4718 //=======================================
4719 // Tidy up
4720 //=======================================
4721 CGF.EmitBlock(ContBlock);
4722
John McCall7f416cc2015-09-08 08:05:57 +00004723 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4724 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004725
4726 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004727 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4728 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004729
4730 return ResAddr;
4731}
4732
John McCall7f416cc2015-09-08 08:05:57 +00004733Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4734 CodeGenFunction &CGF) const {
4735 // The backend's lowering doesn't support va_arg for aggregates or
4736 // illegal vector types. Lower VAArg here for these cases and use
4737 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004738 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004739 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004740
John McCall7f416cc2015-09-08 08:05:57 +00004741 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004742
John McCall7f416cc2015-09-08 08:05:57 +00004743 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004744 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004745 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4746 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4747 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004748 }
4749
John McCall7f416cc2015-09-08 08:05:57 +00004750 // The size of the actual thing passed, which might end up just
4751 // being a pointer for indirect types.
4752 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4753
4754 // Arguments bigger than 16 bytes which aren't homogeneous
4755 // aggregates should be passed indirectly.
4756 bool IsIndirect = false;
4757 if (TyInfo.first.getQuantity() > 16) {
4758 const Type *Base = nullptr;
4759 uint64_t Members = 0;
4760 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004761 }
4762
John McCall7f416cc2015-09-08 08:05:57 +00004763 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4764 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004765}
4766
4767//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004768// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004769//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004770
4771namespace {
4772
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004773class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004774public:
4775 enum ABIKind {
4776 APCS = 0,
4777 AAPCS = 1,
Tim Northover5627d392015-10-30 16:30:45 +00004778 AAPCS_VFP = 2,
4779 AAPCS16_VFP = 3,
Daniel Dunbar020daa92009-09-12 01:00:39 +00004780 };
4781
4782private:
4783 ABIKind Kind;
4784
4785public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004786 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004787 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004788 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004789
John McCall3480ef22011-08-30 01:42:09 +00004790 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004791 switch (getTarget().getTriple().getEnvironment()) {
4792 case llvm::Triple::Android:
4793 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004794 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004795 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004796 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004797 return true;
4798 default:
4799 return false;
4800 }
John McCall3480ef22011-08-30 01:42:09 +00004801 }
4802
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004803 bool isEABIHF() const {
4804 switch (getTarget().getTriple().getEnvironment()) {
4805 case llvm::Triple::EABIHF:
4806 case llvm::Triple::GNUEABIHF:
4807 return true;
4808 default:
4809 return false;
4810 }
4811 }
4812
Daniel Dunbar020daa92009-09-12 01:00:39 +00004813 ABIKind getABIKind() const { return Kind; }
4814
Tim Northovera484bc02013-10-01 14:34:25 +00004815private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004816 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004817 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004818 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004819
Reid Klecknere9f6a712014-10-31 17:10:41 +00004820 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4821 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4822 uint64_t Members) const override;
4823
Craig Topper4f12f102014-03-12 06:41:41 +00004824 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004825
John McCall7f416cc2015-09-08 08:05:57 +00004826 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4827 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004828
4829 llvm::CallingConv::ID getLLVMDefaultCC() const;
4830 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004831 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004832};
4833
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004834class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4835public:
Chris Lattner2b037972010-07-29 02:01:43 +00004836 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4837 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004838
John McCall3480ef22011-08-30 01:42:09 +00004839 const ARMABIInfo &getABIInfo() const {
4840 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4841 }
4842
Craig Topper4f12f102014-03-12 06:41:41 +00004843 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004844 return 13;
4845 }
Roman Divackyc1617352011-05-18 19:36:54 +00004846
Craig Topper4f12f102014-03-12 06:41:41 +00004847 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004848 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4849 }
4850
Roman Divackyc1617352011-05-18 19:36:54 +00004851 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004852 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004853 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004854
4855 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004856 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004857 return false;
4858 }
John McCall3480ef22011-08-30 01:42:09 +00004859
Craig Topper4f12f102014-03-12 06:41:41 +00004860 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004861 if (getABIInfo().isEABI()) return 88;
4862 return TargetCodeGenInfo::getSizeOfUnwindException();
4863 }
Tim Northovera484bc02013-10-01 14:34:25 +00004864
Eric Christopher162c91c2015-06-05 22:03:00 +00004865 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004866 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00004867 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00004868 if (!FD)
4869 return;
4870
4871 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4872 if (!Attr)
4873 return;
4874
4875 const char *Kind;
4876 switch (Attr->getInterrupt()) {
4877 case ARMInterruptAttr::Generic: Kind = ""; break;
4878 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4879 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4880 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4881 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4882 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4883 }
4884
4885 llvm::Function *Fn = cast<llvm::Function>(GV);
4886
4887 Fn->addFnAttr("interrupt", Kind);
4888
Tim Northover5627d392015-10-30 16:30:45 +00004889 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
4890 if (ABI == ARMABIInfo::APCS)
Tim Northovera484bc02013-10-01 14:34:25 +00004891 return;
4892
4893 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4894 // however this is not necessarily true on taking any interrupt. Instruct
4895 // the backend to perform a realignment as part of the function prologue.
4896 llvm::AttrBuilder B;
4897 B.addStackAlignmentAttr(8);
4898 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4899 llvm::AttributeSet::get(CGM.getLLVMContext(),
4900 llvm::AttributeSet::FunctionIndex,
4901 B));
4902 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004903};
4904
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004905class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004906public:
4907 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4908 : ARMTargetCodeGenInfo(CGT, K) {}
4909
Eric Christopher162c91c2015-06-05 22:03:00 +00004910 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004911 CodeGen::CodeGenModule &CGM) const override;
4912};
4913
Eric Christopher162c91c2015-06-05 22:03:00 +00004914void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004915 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004916 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004917 addStackProbeSizeTargetAttribute(D, GV, CGM);
4918}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004919}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004920
Chris Lattner22326a12010-07-29 02:31:05 +00004921void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004922 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004923 FI.getReturnInfo() =
4924 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004925
Tim Northoverbc784d12015-02-24 17:22:40 +00004926 for (auto &I : FI.arguments())
4927 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004928
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004929 // Always honor user-specified calling convention.
4930 if (FI.getCallingConvention() != llvm::CallingConv::C)
4931 return;
4932
John McCall882987f2013-02-28 19:01:20 +00004933 llvm::CallingConv::ID cc = getRuntimeCC();
4934 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004935 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004936}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004937
John McCall882987f2013-02-28 19:01:20 +00004938/// Return the default calling convention that LLVM will use.
4939llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4940 // The default calling convention that LLVM will infer.
Tim Northoverd88ecb32016-01-27 19:32:40 +00004941 if (isEABIHF() || getTarget().getTriple().isWatchABI())
John McCall882987f2013-02-28 19:01:20 +00004942 return llvm::CallingConv::ARM_AAPCS_VFP;
4943 else if (isEABI())
4944 return llvm::CallingConv::ARM_AAPCS;
4945 else
4946 return llvm::CallingConv::ARM_APCS;
4947}
4948
4949/// Return the calling convention that our ABI would like us to use
4950/// as the C calling convention.
4951llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004952 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004953 case APCS: return llvm::CallingConv::ARM_APCS;
4954 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4955 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Tim Northover5627d392015-10-30 16:30:45 +00004956 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004957 }
John McCall882987f2013-02-28 19:01:20 +00004958 llvm_unreachable("bad ABI kind");
4959}
4960
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004961void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004962 assert(getRuntimeCC() == llvm::CallingConv::C);
4963
4964 // Don't muddy up the IR with a ton of explicit annotations if
4965 // they'd just match what LLVM will infer from the triple.
4966 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4967 if (abiCC != getLLVMDefaultCC())
4968 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004969
Tim Northover5627d392015-10-30 16:30:45 +00004970 // AAPCS apparently requires runtime support functions to be soft-float, but
4971 // that's almost certainly for historic reasons (Thumb1 not supporting VFP
4972 // most likely). It's more convenient for AAPCS16_VFP to be hard-float.
4973 switch (getABIKind()) {
4974 case APCS:
4975 case AAPCS16_VFP:
4976 if (abiCC != getLLVMDefaultCC())
4977 BuiltinCC = abiCC;
4978 break;
4979 case AAPCS:
4980 case AAPCS_VFP:
4981 BuiltinCC = llvm::CallingConv::ARM_AAPCS;
4982 break;
4983 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004984}
4985
Tim Northoverbc784d12015-02-24 17:22:40 +00004986ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4987 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004988 // 6.1.2.1 The following argument types are VFP CPRCs:
4989 // A single-precision floating-point type (including promoted
4990 // half-precision types); A double-precision floating-point type;
4991 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4992 // with a Base Type of a single- or double-precision floating-point type,
4993 // 64-bit containerized vectors or 128-bit containerized vectors with one
4994 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004995 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004996
Reid Klecknerb1be6832014-11-15 01:41:41 +00004997 Ty = useFirstFieldIfTransparentUnion(Ty);
4998
Manman Renfef9e312012-10-16 19:18:39 +00004999 // Handle illegal vector types here.
5000 if (isIllegalVectorType(Ty)) {
5001 uint64_t Size = getContext().getTypeSize(Ty);
5002 if (Size <= 32) {
5003 llvm::Type *ResType =
5004 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00005005 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005006 }
5007 if (Size == 64) {
5008 llvm::Type *ResType = llvm::VectorType::get(
5009 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00005010 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005011 }
5012 if (Size == 128) {
5013 llvm::Type *ResType = llvm::VectorType::get(
5014 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00005015 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00005016 }
John McCall7f416cc2015-09-08 08:05:57 +00005017 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00005018 }
5019
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005020 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
5021 // unspecified. This is not done for OpenCL as it handles the half type
5022 // natively, and does not need to interwork with AAPCS code.
5023 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
5024 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5025 llvm::Type::getFloatTy(getVMContext()) :
5026 llvm::Type::getInt32Ty(getVMContext());
5027 return ABIArgInfo::getDirect(ResType);
5028 }
5029
John McCalla1dee5302010-08-22 10:59:02 +00005030 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005031 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00005032 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005033 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00005034 }
Douglas Gregora71cc152010-02-02 20:10:50 +00005035
Tim Northover5a1558e2014-11-07 22:30:50 +00005036 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5037 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00005038 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005039
Oliver Stannard405bded2014-02-11 09:25:50 +00005040 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00005041 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00005042 }
Tim Northover1060eae2013-06-21 22:49:34 +00005043
Daniel Dunbar09d33622009-09-14 21:54:03 +00005044 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005045 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00005046 return ABIArgInfo::getIgnore();
5047
Tim Northover5a1558e2014-11-07 22:30:50 +00005048 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00005049 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5050 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00005051 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00005052 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005053 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005054 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00005055 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00005056 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005057 }
Tim Northover5627d392015-10-30 16:30:45 +00005058 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5059 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5060 // this convention even for a variadic function: the backend will use GPRs
5061 // if needed.
5062 const Type *Base = nullptr;
5063 uint64_t Members = 0;
5064 if (isHomogeneousAggregate(Ty, Base, Members)) {
5065 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5066 llvm::Type *Ty =
5067 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5068 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5069 }
5070 }
5071
5072 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5073 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5074 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5075 // bigger than 128-bits, they get placed in space allocated by the caller,
5076 // and a pointer is passed.
5077 return ABIArgInfo::getIndirect(
5078 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
Bob Wilsone826a2a2011-08-03 05:58:22 +00005079 }
5080
Manman Ren6c30e132012-08-13 21:23:55 +00005081 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00005082 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5083 // most 8-byte. We realign the indirect argument if type alignment is bigger
5084 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00005085 uint64_t ABIAlign = 4;
5086 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5087 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00005088 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00005089 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00005090
Manman Ren8cd99812012-11-06 04:58:01 +00005091 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
Tim Northover5627d392015-10-30 16:30:45 +00005092 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
John McCall7f416cc2015-09-08 08:05:57 +00005093 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5094 /*ByVal=*/true,
5095 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00005096 }
5097
Daniel Dunbarb34b0802010-09-23 01:54:28 +00005098 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00005099 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005100 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00005101 // FIXME: Try to match the types of the arguments more accurately where
5102 // we can.
5103 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005104 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5105 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005106 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005107 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5108 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005109 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005110
Tim Northover5a1558e2014-11-07 22:30:50 +00005111 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005112}
5113
Chris Lattner458b2aa2010-07-29 02:16:43 +00005114static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005115 llvm::LLVMContext &VMContext) {
5116 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5117 // is called integer-like if its size is less than or equal to one word, and
5118 // the offset of each of its addressable sub-fields is zero.
5119
5120 uint64_t Size = Context.getTypeSize(Ty);
5121
5122 // Check that the type fits in a word.
5123 if (Size > 32)
5124 return false;
5125
5126 // FIXME: Handle vector types!
5127 if (Ty->isVectorType())
5128 return false;
5129
Daniel Dunbard53bac72009-09-14 02:20:34 +00005130 // Float types are never treated as "integer like".
5131 if (Ty->isRealFloatingType())
5132 return false;
5133
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005134 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005135 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005136 return true;
5137
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005138 // Small complex integer types are "integer like".
5139 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5140 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005141
5142 // Single element and zero sized arrays should be allowed, by the definition
5143 // above, but they are not.
5144
5145 // Otherwise, it must be a record type.
5146 const RecordType *RT = Ty->getAs<RecordType>();
5147 if (!RT) return false;
5148
5149 // Ignore records with flexible arrays.
5150 const RecordDecl *RD = RT->getDecl();
5151 if (RD->hasFlexibleArrayMember())
5152 return false;
5153
5154 // Check that all sub-fields are at offset 0, and are themselves "integer
5155 // like".
5156 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5157
5158 bool HadField = false;
5159 unsigned idx = 0;
5160 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5161 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005162 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005163
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005164 // Bit-fields are not addressable, we only need to verify they are "integer
5165 // like". We still have to disallow a subsequent non-bitfield, for example:
5166 // struct { int : 0; int x }
5167 // is non-integer like according to gcc.
5168 if (FD->isBitField()) {
5169 if (!RD->isUnion())
5170 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005171
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005172 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5173 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005174
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005175 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005176 }
5177
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005178 // Check if this field is at offset 0.
5179 if (Layout.getFieldOffset(idx) != 0)
5180 return false;
5181
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005182 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5183 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005184
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005185 // Only allow at most one field in a structure. This doesn't match the
5186 // wording above, but follows gcc in situations with a field following an
5187 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005188 if (!RD->isUnion()) {
5189 if (HadField)
5190 return false;
5191
5192 HadField = true;
5193 }
5194 }
5195
5196 return true;
5197}
5198
Oliver Stannard405bded2014-02-11 09:25:50 +00005199ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5200 bool isVariadic) const {
Tim Northover5627d392015-10-30 16:30:45 +00005201 bool IsEffectivelyAAPCS_VFP =
5202 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005203
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005204 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005205 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005206
Daniel Dunbar19964db2010-09-23 01:54:32 +00005207 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005208 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005209 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005210 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005211
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005212 // __fp16 gets returned as if it were an int or float, but with the top 16
5213 // bits unspecified. This is not done for OpenCL as it handles the half type
5214 // natively, and does not need to interwork with AAPCS code.
5215 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5216 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5217 llvm::Type::getFloatTy(getVMContext()) :
5218 llvm::Type::getInt32Ty(getVMContext());
5219 return ABIArgInfo::getDirect(ResType);
5220 }
5221
John McCalla1dee5302010-08-22 10:59:02 +00005222 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005223 // Treat an enum type as its underlying type.
5224 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5225 RetTy = EnumTy->getDecl()->getIntegerType();
5226
Tim Northover5a1558e2014-11-07 22:30:50 +00005227 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5228 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005229 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005230
5231 // Are we following APCS?
5232 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005233 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005234 return ABIArgInfo::getIgnore();
5235
Daniel Dunbareedf1512010-02-01 23:31:19 +00005236 // Complex types are all returned as packed integers.
5237 //
5238 // FIXME: Consider using 2 x vector types if the back end handles them
5239 // correctly.
5240 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005241 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5242 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005243
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005244 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005245 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005246 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005247 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005248 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005249 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005250 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005251 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5252 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005253 }
5254
5255 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005256 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005257 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005258
5259 // Otherwise this is an AAPCS variant.
5260
Chris Lattner458b2aa2010-07-29 02:16:43 +00005261 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005262 return ABIArgInfo::getIgnore();
5263
Bob Wilson1d9269a2011-11-02 04:51:36 +00005264 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005265 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005266 const Type *Base = nullptr;
Tim Northover5627d392015-10-30 16:30:45 +00005267 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005268 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005269 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005270 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005271 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005272 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005273 }
5274
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005275 // Aggregates <= 4 bytes are returned in r0; other aggregates
5276 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005277 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005278 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005279 if (getDataLayout().isBigEndian())
5280 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005281 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005282
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005283 // Return in the smallest viable integer type.
5284 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005285 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005286 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005287 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5288 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Tim Northover5627d392015-10-30 16:30:45 +00005289 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
5290 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
5291 llvm::Type *CoerceTy =
Rui Ueyama83aa9792016-01-14 21:00:27 +00005292 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
Tim Northover5627d392015-10-30 16:30:45 +00005293 return ABIArgInfo::getDirect(CoerceTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005294 }
5295
John McCall7f416cc2015-09-08 08:05:57 +00005296 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005297}
5298
Manman Renfef9e312012-10-16 19:18:39 +00005299/// isIllegalVector - check whether Ty is an illegal vector type.
5300bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
Stephen Hines8267e7d2015-12-04 01:39:30 +00005301 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
5302 if (isAndroid()) {
5303 // Android shipped using Clang 3.1, which supported a slightly different
5304 // vector ABI. The primary differences were that 3-element vector types
5305 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
5306 // accepts that legacy behavior for Android only.
5307 // Check whether VT is legal.
5308 unsigned NumElements = VT->getNumElements();
5309 // NumElements should be power of 2 or equal to 3.
5310 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
5311 return true;
5312 } else {
5313 // Check whether VT is legal.
5314 unsigned NumElements = VT->getNumElements();
5315 uint64_t Size = getContext().getTypeSize(VT);
5316 // NumElements should be power of 2.
5317 if (!llvm::isPowerOf2_32(NumElements))
5318 return true;
5319 // Size should be greater than 32 bits.
5320 return Size <= 32;
5321 }
Manman Renfef9e312012-10-16 19:18:39 +00005322 }
5323 return false;
5324}
5325
Reid Klecknere9f6a712014-10-31 17:10:41 +00005326bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5327 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5328 // double, or 64-bit or 128-bit vectors.
5329 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5330 if (BT->getKind() == BuiltinType::Float ||
5331 BT->getKind() == BuiltinType::Double ||
5332 BT->getKind() == BuiltinType::LongDouble)
5333 return true;
5334 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5335 unsigned VecSize = getContext().getTypeSize(VT);
5336 if (VecSize == 64 || VecSize == 128)
5337 return true;
5338 }
5339 return false;
5340}
5341
5342bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5343 uint64_t Members) const {
5344 return Members <= 4;
5345}
5346
John McCall7f416cc2015-09-08 08:05:57 +00005347Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5348 QualType Ty) const {
5349 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005350
John McCall7f416cc2015-09-08 08:05:57 +00005351 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005352 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005353 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5354 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5355 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005356 }
5357
John McCall7f416cc2015-09-08 08:05:57 +00005358 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5359 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005360
John McCall7f416cc2015-09-08 08:05:57 +00005361 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5362 bool IsIndirect = false;
Tim Northover5627d392015-10-30 16:30:45 +00005363 const Type *Base = nullptr;
5364 uint64_t Members = 0;
John McCall7f416cc2015-09-08 08:05:57 +00005365 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5366 IsIndirect = true;
5367
Tim Northover5627d392015-10-30 16:30:45 +00005368 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
5369 // allocated by the caller.
5370 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
5371 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5372 !isHomogeneousAggregate(Ty, Base, Members)) {
5373 IsIndirect = true;
5374
John McCall7f416cc2015-09-08 08:05:57 +00005375 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005376 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5377 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005378 // Our callers should be prepared to handle an under-aligned address.
5379 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5380 getABIKind() == ARMABIInfo::AAPCS) {
5381 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5382 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
Tim Northover4c5cb9c2015-11-02 19:32:23 +00005383 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5384 // ARMv7k allows type alignment up to 16 bytes.
5385 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5386 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
John McCall7f416cc2015-09-08 08:05:57 +00005387 } else {
5388 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005389 }
John McCall7f416cc2015-09-08 08:05:57 +00005390 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005391
John McCall7f416cc2015-09-08 08:05:57 +00005392 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5393 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005394}
5395
Chris Lattner0cf24192010-06-28 20:05:43 +00005396//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005397// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005398//===----------------------------------------------------------------------===//
5399
5400namespace {
5401
Justin Holewinski83e96682012-05-24 17:43:12 +00005402class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005403public:
Justin Holewinski36837432013-03-30 14:38:24 +00005404 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005405
5406 ABIArgInfo classifyReturnType(QualType RetTy) const;
5407 ABIArgInfo classifyArgumentType(QualType Ty) const;
5408
Craig Topper4f12f102014-03-12 06:41:41 +00005409 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005410 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5411 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005412};
5413
Justin Holewinski83e96682012-05-24 17:43:12 +00005414class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005415public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005416 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5417 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005418
Eric Christopher162c91c2015-06-05 22:03:00 +00005419 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005420 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005421private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005422 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5423 // resulting MDNode to the nvvm.annotations MDNode.
5424 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005425};
5426
Justin Holewinski83e96682012-05-24 17:43:12 +00005427ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005428 if (RetTy->isVoidType())
5429 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005430
5431 // note: this is different from default ABI
5432 if (!RetTy->isScalarType())
5433 return ABIArgInfo::getDirect();
5434
5435 // Treat an enum type as its underlying type.
5436 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5437 RetTy = EnumTy->getDecl()->getIntegerType();
5438
5439 return (RetTy->isPromotableIntegerType() ?
5440 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005441}
5442
Justin Holewinski83e96682012-05-24 17:43:12 +00005443ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005444 // Treat an enum type as its underlying type.
5445 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5446 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005447
Eli Bendersky95338a02014-10-29 13:43:21 +00005448 // Return aggregates type as indirect by value
5449 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005450 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005451
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005452 return (Ty->isPromotableIntegerType() ?
5453 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005454}
5455
Justin Holewinski83e96682012-05-24 17:43:12 +00005456void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005457 if (!getCXXABI().classifyReturnType(FI))
5458 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005459 for (auto &I : FI.arguments())
5460 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005461
5462 // Always honor user-specified calling convention.
5463 if (FI.getCallingConvention() != llvm::CallingConv::C)
5464 return;
5465
John McCall882987f2013-02-28 19:01:20 +00005466 FI.setEffectiveCallingConvention(getRuntimeCC());
5467}
5468
John McCall7f416cc2015-09-08 08:05:57 +00005469Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5470 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005471 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005472}
5473
Justin Holewinski83e96682012-05-24 17:43:12 +00005474void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005475setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005476 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005477 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005478 if (!FD) return;
5479
5480 llvm::Function *F = cast<llvm::Function>(GV);
5481
5482 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005483 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005484 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005485 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005486 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005487 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005488 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5489 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005490 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005491 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005492 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005493 }
Justin Holewinski38031972011-10-05 17:58:44 +00005494
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005495 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005496 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005497 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005498 // __global__ functions cannot be called from the device, we do not
5499 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005500 if (FD->hasAttr<CUDAGlobalAttr>()) {
5501 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5502 addNVVMMetadata(F, "kernel", 1);
5503 }
Artem Belevich7093e402015-04-21 22:55:54 +00005504 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005505 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005506 llvm::APSInt MaxThreads(32);
5507 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5508 if (MaxThreads > 0)
5509 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5510
5511 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5512 // not specified in __launch_bounds__ or if the user specified a 0 value,
5513 // we don't have to add a PTX directive.
5514 if (Attr->getMinBlocks()) {
5515 llvm::APSInt MinBlocks(32);
5516 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5517 if (MinBlocks > 0)
5518 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5519 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005520 }
5521 }
Justin Holewinski38031972011-10-05 17:58:44 +00005522 }
5523}
5524
Eli Benderskye06a2c42014-04-15 16:57:05 +00005525void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5526 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005527 llvm::Module *M = F->getParent();
5528 llvm::LLVMContext &Ctx = M->getContext();
5529
5530 // Get "nvvm.annotations" metadata node
5531 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5532
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005533 llvm::Metadata *MDVals[] = {
5534 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5535 llvm::ConstantAsMetadata::get(
5536 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005537 // Append metadata to nvvm.annotations
5538 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5539}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005540}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005541
5542//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005543// SystemZ ABI Implementation
5544//===----------------------------------------------------------------------===//
5545
5546namespace {
5547
5548class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005549 bool HasVector;
5550
Ulrich Weigand47445072013-05-06 16:26:41 +00005551public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005552 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5553 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005554
5555 bool isPromotableIntegerType(QualType Ty) const;
5556 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005557 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005558 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005559 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005560
5561 ABIArgInfo classifyReturnType(QualType RetTy) const;
5562 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5563
Craig Topper4f12f102014-03-12 06:41:41 +00005564 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005565 if (!getCXXABI().classifyReturnType(FI))
5566 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005567 for (auto &I : FI.arguments())
5568 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005569 }
5570
John McCall7f416cc2015-09-08 08:05:57 +00005571 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5572 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005573};
5574
5575class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5576public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005577 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5578 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005579};
5580
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005581}
Ulrich Weigand47445072013-05-06 16:26:41 +00005582
5583bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5584 // Treat an enum type as its underlying type.
5585 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5586 Ty = EnumTy->getDecl()->getIntegerType();
5587
5588 // Promotable integer types are required to be promoted by the ABI.
5589 if (Ty->isPromotableIntegerType())
5590 return true;
5591
5592 // 32-bit values must also be promoted.
5593 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5594 switch (BT->getKind()) {
5595 case BuiltinType::Int:
5596 case BuiltinType::UInt:
5597 return true;
5598 default:
5599 return false;
5600 }
5601 return false;
5602}
5603
5604bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005605 return (Ty->isAnyComplexType() ||
5606 Ty->isVectorType() ||
5607 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005608}
5609
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005610bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5611 return (HasVector &&
5612 Ty->isVectorType() &&
5613 getContext().getTypeSize(Ty) <= 128);
5614}
5615
Ulrich Weigand47445072013-05-06 16:26:41 +00005616bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5617 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5618 switch (BT->getKind()) {
5619 case BuiltinType::Float:
5620 case BuiltinType::Double:
5621 return true;
5622 default:
5623 return false;
5624 }
5625
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005626 return false;
5627}
5628
5629QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005630 if (const RecordType *RT = Ty->getAsStructureType()) {
5631 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005632 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005633
5634 // If this is a C++ record, check the bases first.
5635 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005636 for (const auto &I : CXXRD->bases()) {
5637 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005638
5639 // Empty bases don't affect things either way.
5640 if (isEmptyRecord(getContext(), Base, true))
5641 continue;
5642
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005643 if (!Found.isNull())
5644 return Ty;
5645 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005646 }
5647
5648 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005649 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005650 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005651 // Unlike isSingleElementStruct(), empty structure and array fields
5652 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005653 if (getContext().getLangOpts().CPlusPlus &&
5654 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5655 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005656
5657 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005658 // Nested structures still do though.
5659 if (!Found.isNull())
5660 return Ty;
5661 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005662 }
5663
5664 // Unlike isSingleElementStruct(), trailing padding is allowed.
5665 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005666 if (!Found.isNull())
5667 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005668 }
5669
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005670 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005671}
5672
John McCall7f416cc2015-09-08 08:05:57 +00005673Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5674 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005675 // Assume that va_list type is correct; should be pointer to LLVM type:
5676 // struct {
5677 // i64 __gpr;
5678 // i64 __fpr;
5679 // i8 *__overflow_arg_area;
5680 // i8 *__reg_save_area;
5681 // };
5682
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005683 // Every non-vector argument occupies 8 bytes and is passed by preference
5684 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5685 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005686 Ty = getContext().getCanonicalType(Ty);
5687 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005688 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005689 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005690 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005691 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005692 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005693 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005694 CharUnits UnpaddedSize;
5695 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005696 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005697 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5698 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005699 } else {
5700 if (AI.getCoerceToType())
5701 ArgTy = AI.getCoerceToType();
5702 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005703 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005704 UnpaddedSize = TyInfo.first;
5705 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005706 }
John McCall7f416cc2015-09-08 08:05:57 +00005707 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5708 if (IsVector && UnpaddedSize > PaddedSize)
5709 PaddedSize = CharUnits::fromQuantity(16);
5710 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005711
John McCall7f416cc2015-09-08 08:05:57 +00005712 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005713
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005714 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005715 llvm::Value *PaddedSizeV =
5716 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005717
5718 if (IsVector) {
5719 // Work out the address of a vector argument on the stack.
5720 // Vector arguments are always passed in the high bits of a
5721 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005722 Address OverflowArgAreaPtr =
5723 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005724 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005725 Address OverflowArgArea =
5726 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5727 TyInfo.second);
5728 Address MemAddr =
5729 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005730
5731 // Update overflow_arg_area_ptr pointer
5732 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005733 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5734 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005735 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5736
5737 return MemAddr;
5738 }
5739
John McCall7f416cc2015-09-08 08:05:57 +00005740 assert(PaddedSize.getQuantity() == 8);
5741
5742 unsigned MaxRegs, RegCountField, RegSaveIndex;
5743 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005744 if (InFPRs) {
5745 MaxRegs = 4; // Maximum of 4 FPR arguments
5746 RegCountField = 1; // __fpr
5747 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005748 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005749 } else {
5750 MaxRegs = 5; // Maximum of 5 GPR arguments
5751 RegCountField = 0; // __gpr
5752 RegSaveIndex = 2; // save offset for r2
5753 RegPadding = Padding; // values are passed in the low bits of a GPR
5754 }
5755
John McCall7f416cc2015-09-08 08:05:57 +00005756 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5757 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5758 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005759 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005760 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5761 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005762 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005763
5764 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5765 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5766 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5767 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5768
5769 // Emit code to load the value if it was passed in registers.
5770 CGF.EmitBlock(InRegBlock);
5771
5772 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005773 llvm::Value *ScaledRegCount =
5774 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5775 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005776 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5777 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005778 llvm::Value *RegOffset =
5779 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005780 Address RegSaveAreaPtr =
5781 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5782 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005783 llvm::Value *RegSaveArea =
5784 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005785 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5786 "raw_reg_addr"),
5787 PaddedSize);
5788 Address RegAddr =
5789 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005790
5791 // Update the register count
5792 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5793 llvm::Value *NewRegCount =
5794 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5795 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5796 CGF.EmitBranch(ContBlock);
5797
5798 // Emit code to load the value if it was passed in memory.
5799 CGF.EmitBlock(InMemBlock);
5800
5801 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005802 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5803 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5804 Address OverflowArgArea =
5805 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5806 PaddedSize);
5807 Address RawMemAddr =
5808 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5809 Address MemAddr =
5810 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005811
5812 // Update overflow_arg_area_ptr pointer
5813 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005814 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5815 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005816 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5817 CGF.EmitBranch(ContBlock);
5818
5819 // Return the appropriate result.
5820 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005821 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5822 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005823
5824 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005825 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5826 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005827
5828 return ResAddr;
5829}
5830
Ulrich Weigand47445072013-05-06 16:26:41 +00005831ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5832 if (RetTy->isVoidType())
5833 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005834 if (isVectorArgumentType(RetTy))
5835 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005836 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005837 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005838 return (isPromotableIntegerType(RetTy) ?
5839 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5840}
5841
5842ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5843 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005844 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005845 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005846
5847 // Integers and enums are extended to full register width.
5848 if (isPromotableIntegerType(Ty))
5849 return ABIArgInfo::getExtend();
5850
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005851 // Handle vector types and vector-like structure types. Note that
5852 // as opposed to float-like structure types, we do not allow any
5853 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005854 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005855 QualType SingleElementTy = GetSingleElementType(Ty);
5856 if (isVectorArgumentType(SingleElementTy) &&
5857 getContext().getTypeSize(SingleElementTy) == Size)
5858 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5859
5860 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005861 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005862 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005863
5864 // Handle small structures.
5865 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5866 // Structures with flexible arrays have variable length, so really
5867 // fail the size test above.
5868 const RecordDecl *RD = RT->getDecl();
5869 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005870 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005871
5872 // The structure is passed as an unextended integer, a float, or a double.
5873 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005874 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005875 assert(Size == 32 || Size == 64);
5876 if (Size == 32)
5877 PassTy = llvm::Type::getFloatTy(getVMContext());
5878 else
5879 PassTy = llvm::Type::getDoubleTy(getVMContext());
5880 } else
5881 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5882 return ABIArgInfo::getDirect(PassTy);
5883 }
5884
5885 // Non-structure compounds are passed indirectly.
5886 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005887 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005888
Craig Topper8a13c412014-05-21 05:09:00 +00005889 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005890}
5891
5892//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005893// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005894//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005895
5896namespace {
5897
5898class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5899public:
Chris Lattner2b037972010-07-29 02:01:43 +00005900 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5901 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005902 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005903 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005904};
5905
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005906}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005907
Eric Christopher162c91c2015-06-05 22:03:00 +00005908void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005909 llvm::GlobalValue *GV,
5910 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005911 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005912 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5913 // Handle 'interrupt' attribute:
5914 llvm::Function *F = cast<llvm::Function>(GV);
5915
5916 // Step 1: Set ISR calling convention.
5917 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5918
5919 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005920 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005921
5922 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005923 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005924 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5925 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005926 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005927 }
5928}
5929
Chris Lattner0cf24192010-06-28 20:05:43 +00005930//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005931// MIPS ABI Implementation. This works for both little-endian and
5932// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005933//===----------------------------------------------------------------------===//
5934
John McCall943fae92010-05-27 06:19:26 +00005935namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005936class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005937 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005938 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5939 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005940 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005941 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005942 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005943 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005944public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005945 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005946 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005947 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005948
5949 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005950 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005951 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005952 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5953 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005954 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005955};
5956
John McCall943fae92010-05-27 06:19:26 +00005957class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005958 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005959public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005960 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5961 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005962 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005963
Craig Topper4f12f102014-03-12 06:41:41 +00005964 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005965 return 29;
5966 }
5967
Eric Christopher162c91c2015-06-05 22:03:00 +00005968 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005969 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005970 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005971 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005972 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005973 if (FD->hasAttr<Mips16Attr>()) {
5974 Fn->addFnAttr("mips16");
5975 }
5976 else if (FD->hasAttr<NoMips16Attr>()) {
5977 Fn->addFnAttr("nomips16");
5978 }
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005979
5980 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
5981 if (!Attr)
5982 return;
5983
5984 const char *Kind;
5985 switch (Attr->getInterrupt()) {
Daniel Sandersbd3f47f2015-11-27 18:03:44 +00005986 case MipsInterruptAttr::eic: Kind = "eic"; break;
5987 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
5988 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
5989 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
5990 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
5991 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
5992 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
5993 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
5994 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
5995 }
5996
5997 Fn->addFnAttr("interrupt", Kind);
5998
Reed Kotler373feca2013-01-16 17:10:28 +00005999 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00006000
John McCall943fae92010-05-27 06:19:26 +00006001 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006002 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00006003
Craig Topper4f12f102014-03-12 06:41:41 +00006004 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00006005 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00006006 }
John McCall943fae92010-05-27 06:19:26 +00006007};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006008}
John McCall943fae92010-05-27 06:19:26 +00006009
Eric Christopher7565e0d2015-05-29 23:09:49 +00006010void MipsABIInfo::CoerceToIntArgs(
6011 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006012 llvm::IntegerType *IntTy =
6013 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006014
6015 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6016 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6017 ArgList.push_back(IntTy);
6018
6019 // If necessary, add one more integer type to ArgList.
6020 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6021
6022 if (R)
6023 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006024}
6025
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006026// In N32/64, an aligned double precision floating point field is passed in
6027// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006028llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006029 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6030
6031 if (IsO32) {
6032 CoerceToIntArgs(TySize, ArgList);
6033 return llvm::StructType::get(getVMContext(), ArgList);
6034 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006035
Akira Hatanaka02e13e52012-01-12 00:52:17 +00006036 if (Ty->isComplexType())
6037 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00006038
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006039 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006040
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006041 // Unions/vectors are passed in integer registers.
6042 if (!RT || !RT->isStructureOrClassType()) {
6043 CoerceToIntArgs(TySize, ArgList);
6044 return llvm::StructType::get(getVMContext(), ArgList);
6045 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006046
6047 const RecordDecl *RD = RT->getDecl();
6048 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006049 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00006050
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006051 uint64_t LastOffset = 0;
6052 unsigned idx = 0;
6053 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6054
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00006055 // Iterate over fields in the struct/class and check if there are any aligned
6056 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006057 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6058 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006059 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006060 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6061
6062 if (!BT || BT->getKind() != BuiltinType::Double)
6063 continue;
6064
6065 uint64_t Offset = Layout.getFieldOffset(idx);
6066 if (Offset % 64) // Ignore doubles that are not aligned.
6067 continue;
6068
6069 // Add ((Offset - LastOffset) / 64) args of type i64.
6070 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6071 ArgList.push_back(I64);
6072
6073 // Add double type.
6074 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6075 LastOffset = Offset + 64;
6076 }
6077
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006078 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6079 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00006080
6081 return llvm::StructType::get(getVMContext(), ArgList);
6082}
6083
Akira Hatanakaddd66342013-10-29 18:41:15 +00006084llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6085 uint64_t Offset) const {
6086 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00006087 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006088
Akira Hatanakaddd66342013-10-29 18:41:15 +00006089 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006090}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00006091
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006092ABIArgInfo
6093MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00006094 Ty = useFirstFieldIfTransparentUnion(Ty);
6095
Akira Hatanaka1632af62012-01-09 19:31:25 +00006096 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006097 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00006098 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006099
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006100 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6101 (uint64_t)StackAlignInBytes);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006102 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6103 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00006104
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006105 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00006106 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006107 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006108 return ABIArgInfo::getIgnore();
6109
Mark Lacey3825e832013-10-06 01:33:34 +00006110 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006111 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00006112 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00006113 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00006114
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006115 // If we have reached here, aggregates are passed directly by coercing to
6116 // another structure type. Padding is inserted if the offset of the
6117 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00006118 ABIArgInfo ArgInfo =
6119 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6120 getPaddingType(OrigOffset, CurrOffset));
6121 ArgInfo.setInReg(true);
6122 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006123 }
6124
6125 // Treat an enum type as its underlying type.
6126 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6127 Ty = EnumTy->getDecl()->getIntegerType();
6128
Daniel Sanders5b445b32014-10-24 14:42:42 +00006129 // All integral types are promoted to the GPR width.
6130 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00006131 return ABIArgInfo::getExtend();
6132
Akira Hatanakaddd66342013-10-29 18:41:15 +00006133 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00006134 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00006135}
6136
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006137llvm::Type*
6138MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00006139 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006140 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006141
Akira Hatanakab6f74432012-02-09 18:49:26 +00006142 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006143 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00006144 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6145 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006146
Akira Hatanakab6f74432012-02-09 18:49:26 +00006147 // N32/64 returns struct/classes in floating point registers if the
6148 // following conditions are met:
6149 // 1. The size of the struct/class is no larger than 128-bit.
6150 // 2. The struct/class has one or two fields all of which are floating
6151 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006152 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00006153 //
6154 // Any other composite results are returned in integer registers.
6155 //
6156 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6157 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6158 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006159 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006160
Akira Hatanakab6f74432012-02-09 18:49:26 +00006161 if (!BT || !BT->isFloatingPoint())
6162 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006163
David Blaikie2d7c57e2012-04-30 02:36:29 +00006164 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006165 }
6166
6167 if (b == e)
6168 return llvm::StructType::get(getVMContext(), RTList,
6169 RD->hasAttr<PackedAttr>());
6170
6171 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006172 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006173 }
6174
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006175 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006176 return llvm::StructType::get(getVMContext(), RTList);
6177}
6178
Akira Hatanakab579fe52011-06-02 00:09:17 +00006179ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006180 uint64_t Size = getContext().getTypeSize(RetTy);
6181
Daniel Sandersed39f582014-09-04 13:28:14 +00006182 if (RetTy->isVoidType())
6183 return ABIArgInfo::getIgnore();
6184
6185 // O32 doesn't treat zero-sized structs differently from other structs.
6186 // However, N32/N64 ignores zero sized return values.
6187 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006188 return ABIArgInfo::getIgnore();
6189
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006190 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006191 if (Size <= 128) {
6192 if (RetTy->isAnyComplexType())
6193 return ABIArgInfo::getDirect();
6194
Daniel Sanderse5018b62014-09-04 15:05:39 +00006195 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006196 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006197 if (!IsO32 ||
6198 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6199 ABIArgInfo ArgInfo =
6200 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6201 ArgInfo.setInReg(true);
6202 return ArgInfo;
6203 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006204 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006205
John McCall7f416cc2015-09-08 08:05:57 +00006206 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006207 }
6208
6209 // Treat an enum type as its underlying type.
6210 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6211 RetTy = EnumTy->getDecl()->getIntegerType();
6212
6213 return (RetTy->isPromotableIntegerType() ?
6214 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6215}
6216
6217void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006218 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006219 if (!getCXXABI().classifyReturnType(FI))
6220 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006221
Eric Christopher7565e0d2015-05-29 23:09:49 +00006222 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006223 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006224
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006225 for (auto &I : FI.arguments())
6226 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006227}
6228
John McCall7f416cc2015-09-08 08:05:57 +00006229Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6230 QualType OrigTy) const {
6231 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006232
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006233 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6234 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006235 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006236 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006237 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006238 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006239 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006240 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006241 DidPromote = true;
6242 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6243 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006244 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006245
John McCall7f416cc2015-09-08 08:05:57 +00006246 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006247
John McCall7f416cc2015-09-08 08:05:57 +00006248 // The alignment of things in the argument area is never larger than
6249 // StackAlignInBytes.
6250 TyInfo.second =
6251 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6252
6253 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6254 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6255
6256 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6257 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6258
6259
6260 // If there was a promotion, "unpromote" into a temporary.
6261 // TODO: can we just use a pointer into a subset of the original slot?
6262 if (DidPromote) {
6263 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6264 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6265
6266 // Truncate down to the right width.
6267 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6268 : CGF.IntPtrTy);
6269 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6270 if (OrigTy->isPointerType())
6271 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6272
6273 CGF.Builder.CreateStore(V, Temp);
6274 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006275 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006276
John McCall7f416cc2015-09-08 08:05:57 +00006277 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006278}
6279
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006280bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6281 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006282
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006283 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6284 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6285 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006286
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006287 return false;
6288}
6289
John McCall943fae92010-05-27 06:19:26 +00006290bool
6291MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6292 llvm::Value *Address) const {
6293 // This information comes from gcc's implementation, which seems to
6294 // as canonical as it gets.
6295
John McCall943fae92010-05-27 06:19:26 +00006296 // Everything on MIPS is 4 bytes. Double-precision FP registers
6297 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006298 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006299
6300 // 0-31 are the general purpose registers, $0 - $31.
6301 // 32-63 are the floating-point registers, $f0 - $f31.
6302 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6303 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006304 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006305
6306 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6307 // They are one bit wide and ignored here.
6308
6309 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6310 // (coprocessor 1 is the FP unit)
6311 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6312 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6313 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006314 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006315 return false;
6316}
6317
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006318//===----------------------------------------------------------------------===//
6319// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006320// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006321// handling.
6322//===----------------------------------------------------------------------===//
6323
6324namespace {
6325
6326class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6327public:
6328 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6329 : DefaultTargetCodeGenInfo(CGT) {}
6330
Eric Christopher162c91c2015-06-05 22:03:00 +00006331 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006332 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006333};
6334
Eric Christopher162c91c2015-06-05 22:03:00 +00006335void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006336 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006337 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006338 if (!FD) return;
6339
6340 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006341
David Blaikiebbafb8a2012-03-11 07:00:24 +00006342 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006343 if (FD->hasAttr<OpenCLKernelAttr>()) {
6344 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006345 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006346 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6347 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006348 // Convert the reqd_work_group_size() attributes to metadata.
6349 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006350 llvm::NamedMDNode *OpenCLMetadata =
6351 M.getModule().getOrInsertNamedMetadata(
6352 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006353
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006354 SmallVector<llvm::Metadata *, 5> Operands;
6355 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006356
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006357 Operands.push_back(
6358 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6359 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6360 Operands.push_back(
6361 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6362 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6363 Operands.push_back(
6364 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6365 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006366
Eric Christopher7565e0d2015-05-29 23:09:49 +00006367 // Add a boolean constant operand for "required" (true) or "hint"
6368 // (false) for implementing the work_group_size_hint attr later.
6369 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006370 Operands.push_back(
6371 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006372 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6373 }
6374 }
6375 }
6376}
6377
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006378}
John McCall943fae92010-05-27 06:19:26 +00006379
Tony Linthicum76329bf2011-12-12 21:14:55 +00006380//===----------------------------------------------------------------------===//
6381// Hexagon ABI Implementation
6382//===----------------------------------------------------------------------===//
6383
6384namespace {
6385
6386class HexagonABIInfo : public ABIInfo {
6387
6388
6389public:
6390 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6391
6392private:
6393
6394 ABIArgInfo classifyReturnType(QualType RetTy) const;
6395 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6396
Craig Topper4f12f102014-03-12 06:41:41 +00006397 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006398
John McCall7f416cc2015-09-08 08:05:57 +00006399 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6400 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006401};
6402
6403class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6404public:
6405 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6406 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6407
Craig Topper4f12f102014-03-12 06:41:41 +00006408 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006409 return 29;
6410 }
6411};
6412
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006413}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006414
6415void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006416 if (!getCXXABI().classifyReturnType(FI))
6417 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006418 for (auto &I : FI.arguments())
6419 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006420}
6421
6422ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6423 if (!isAggregateTypeForABI(Ty)) {
6424 // Treat an enum type as its underlying type.
6425 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6426 Ty = EnumTy->getDecl()->getIntegerType();
6427
6428 return (Ty->isPromotableIntegerType() ?
6429 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6430 }
6431
6432 // Ignore empty records.
6433 if (isEmptyRecord(getContext(), Ty, true))
6434 return ABIArgInfo::getIgnore();
6435
Mark Lacey3825e832013-10-06 01:33:34 +00006436 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006437 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006438
6439 uint64_t Size = getContext().getTypeSize(Ty);
6440 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006441 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006442 // Pass in the smallest viable integer type.
6443 else if (Size > 32)
6444 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6445 else if (Size > 16)
6446 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6447 else if (Size > 8)
6448 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6449 else
6450 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6451}
6452
6453ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6454 if (RetTy->isVoidType())
6455 return ABIArgInfo::getIgnore();
6456
6457 // Large vector types should be returned via memory.
6458 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006459 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006460
6461 if (!isAggregateTypeForABI(RetTy)) {
6462 // Treat an enum type as its underlying type.
6463 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6464 RetTy = EnumTy->getDecl()->getIntegerType();
6465
6466 return (RetTy->isPromotableIntegerType() ?
6467 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6468 }
6469
Tony Linthicum76329bf2011-12-12 21:14:55 +00006470 if (isEmptyRecord(getContext(), RetTy, true))
6471 return ABIArgInfo::getIgnore();
6472
6473 // Aggregates <= 8 bytes are returned in r0; other aggregates
6474 // are returned indirectly.
6475 uint64_t Size = getContext().getTypeSize(RetTy);
6476 if (Size <= 64) {
6477 // Return in the smallest viable integer type.
6478 if (Size <= 8)
6479 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6480 if (Size <= 16)
6481 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6482 if (Size <= 32)
6483 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6484 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6485 }
6486
John McCall7f416cc2015-09-08 08:05:57 +00006487 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006488}
6489
John McCall7f416cc2015-09-08 08:05:57 +00006490Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6491 QualType Ty) const {
6492 // FIXME: Someone needs to audit that this handle alignment correctly.
6493 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6494 getContext().getTypeInfoInChars(Ty),
6495 CharUnits::fromQuantity(4),
6496 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006497}
6498
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006499//===----------------------------------------------------------------------===//
6500// AMDGPU ABI Implementation
6501//===----------------------------------------------------------------------===//
6502
6503namespace {
6504
6505class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6506public:
6507 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6508 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006509 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006510 CodeGen::CodeGenModule &M) const override;
6511};
6512
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006513}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006514
Eric Christopher162c91c2015-06-05 22:03:00 +00006515void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006516 const Decl *D,
6517 llvm::GlobalValue *GV,
6518 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006519 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006520 if (!FD)
6521 return;
6522
6523 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6524 llvm::Function *F = cast<llvm::Function>(GV);
6525 uint32_t NumVGPR = Attr->getNumVGPR();
6526 if (NumVGPR != 0)
6527 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6528 }
6529
6530 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6531 llvm::Function *F = cast<llvm::Function>(GV);
6532 unsigned NumSGPR = Attr->getNumSGPR();
6533 if (NumSGPR != 0)
6534 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6535 }
6536}
6537
Tony Linthicum76329bf2011-12-12 21:14:55 +00006538
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006539//===----------------------------------------------------------------------===//
6540// SPARC v9 ABI Implementation.
6541// Based on the SPARC Compliance Definition version 2.4.1.
6542//
6543// Function arguments a mapped to a nominal "parameter array" and promoted to
6544// registers depending on their type. Each argument occupies 8 or 16 bytes in
6545// the array, structs larger than 16 bytes are passed indirectly.
6546//
6547// One case requires special care:
6548//
6549// struct mixed {
6550// int i;
6551// float f;
6552// };
6553//
6554// When a struct mixed is passed by value, it only occupies 8 bytes in the
6555// parameter array, but the int is passed in an integer register, and the float
6556// is passed in a floating point register. This is represented as two arguments
6557// with the LLVM IR inreg attribute:
6558//
6559// declare void f(i32 inreg %i, float inreg %f)
6560//
6561// The code generator will only allocate 4 bytes from the parameter array for
6562// the inreg arguments. All other arguments are allocated a multiple of 8
6563// bytes.
6564//
6565namespace {
6566class SparcV9ABIInfo : public ABIInfo {
6567public:
6568 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6569
6570private:
6571 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006572 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006573 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6574 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006575
6576 // Coercion type builder for structs passed in registers. The coercion type
6577 // serves two purposes:
6578 //
6579 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6580 // in registers.
6581 // 2. Expose aligned floating point elements as first-level elements, so the
6582 // code generator knows to pass them in floating point registers.
6583 //
6584 // We also compute the InReg flag which indicates that the struct contains
6585 // aligned 32-bit floats.
6586 //
6587 struct CoerceBuilder {
6588 llvm::LLVMContext &Context;
6589 const llvm::DataLayout &DL;
6590 SmallVector<llvm::Type*, 8> Elems;
6591 uint64_t Size;
6592 bool InReg;
6593
6594 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6595 : Context(c), DL(dl), Size(0), InReg(false) {}
6596
6597 // Pad Elems with integers until Size is ToSize.
6598 void pad(uint64_t ToSize) {
6599 assert(ToSize >= Size && "Cannot remove elements");
6600 if (ToSize == Size)
6601 return;
6602
6603 // Finish the current 64-bit word.
Rui Ueyama83aa9792016-01-14 21:00:27 +00006604 uint64_t Aligned = llvm::alignTo(Size, 64);
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006605 if (Aligned > Size && Aligned <= ToSize) {
6606 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6607 Size = Aligned;
6608 }
6609
6610 // Add whole 64-bit words.
6611 while (Size + 64 <= ToSize) {
6612 Elems.push_back(llvm::Type::getInt64Ty(Context));
6613 Size += 64;
6614 }
6615
6616 // Final in-word padding.
6617 if (Size < ToSize) {
6618 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6619 Size = ToSize;
6620 }
6621 }
6622
6623 // Add a floating point element at Offset.
6624 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6625 // Unaligned floats are treated as integers.
6626 if (Offset % Bits)
6627 return;
6628 // The InReg flag is only required if there are any floats < 64 bits.
6629 if (Bits < 64)
6630 InReg = true;
6631 pad(Offset);
6632 Elems.push_back(Ty);
6633 Size = Offset + Bits;
6634 }
6635
6636 // Add a struct type to the coercion type, starting at Offset (in bits).
6637 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6638 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6639 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6640 llvm::Type *ElemTy = StrTy->getElementType(i);
6641 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6642 switch (ElemTy->getTypeID()) {
6643 case llvm::Type::StructTyID:
6644 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6645 break;
6646 case llvm::Type::FloatTyID:
6647 addFloat(ElemOffset, ElemTy, 32);
6648 break;
6649 case llvm::Type::DoubleTyID:
6650 addFloat(ElemOffset, ElemTy, 64);
6651 break;
6652 case llvm::Type::FP128TyID:
6653 addFloat(ElemOffset, ElemTy, 128);
6654 break;
6655 case llvm::Type::PointerTyID:
6656 if (ElemOffset % 64 == 0) {
6657 pad(ElemOffset);
6658 Elems.push_back(ElemTy);
6659 Size += 64;
6660 }
6661 break;
6662 default:
6663 break;
6664 }
6665 }
6666 }
6667
6668 // Check if Ty is a usable substitute for the coercion type.
6669 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006670 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006671 }
6672
6673 // Get the coercion type as a literal struct type.
6674 llvm::Type *getType() const {
6675 if (Elems.size() == 1)
6676 return Elems.front();
6677 else
6678 return llvm::StructType::get(Context, Elems);
6679 }
6680 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006681};
6682} // end anonymous namespace
6683
6684ABIArgInfo
6685SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6686 if (Ty->isVoidType())
6687 return ABIArgInfo::getIgnore();
6688
6689 uint64_t Size = getContext().getTypeSize(Ty);
6690
6691 // Anything too big to fit in registers is passed with an explicit indirect
6692 // pointer / sret pointer.
6693 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006694 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006695
6696 // Treat an enum type as its underlying type.
6697 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6698 Ty = EnumTy->getDecl()->getIntegerType();
6699
6700 // Integer types smaller than a register are extended.
6701 if (Size < 64 && Ty->isIntegerType())
6702 return ABIArgInfo::getExtend();
6703
6704 // Other non-aggregates go in registers.
6705 if (!isAggregateTypeForABI(Ty))
6706 return ABIArgInfo::getDirect();
6707
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006708 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6709 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6710 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006711 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006712
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006713 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006714 // Build a coercion type from the LLVM struct type.
6715 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6716 if (!StrTy)
6717 return ABIArgInfo::getDirect();
6718
6719 CoerceBuilder CB(getVMContext(), getDataLayout());
6720 CB.addStruct(0, StrTy);
Rui Ueyama83aa9792016-01-14 21:00:27 +00006721 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006722
6723 // Try to use the original type for coercion.
6724 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6725
6726 if (CB.InReg)
6727 return ABIArgInfo::getDirectInReg(CoerceTy);
6728 else
6729 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006730}
6731
John McCall7f416cc2015-09-08 08:05:57 +00006732Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6733 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006734 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6735 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6736 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6737 AI.setCoerceToType(ArgTy);
6738
John McCall7f416cc2015-09-08 08:05:57 +00006739 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006740
John McCall7f416cc2015-09-08 08:05:57 +00006741 CGBuilderTy &Builder = CGF.Builder;
6742 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6743 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6744
6745 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6746
6747 Address ArgAddr = Address::invalid();
6748 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006749 switch (AI.getKind()) {
6750 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006751 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006752 llvm_unreachable("Unsupported ABI kind for va_arg");
6753
John McCall7f416cc2015-09-08 08:05:57 +00006754 case ABIArgInfo::Extend: {
6755 Stride = SlotSize;
6756 CharUnits Offset = SlotSize - TypeInfo.first;
6757 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006758 break;
John McCall7f416cc2015-09-08 08:05:57 +00006759 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006760
John McCall7f416cc2015-09-08 08:05:57 +00006761 case ABIArgInfo::Direct: {
6762 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
Rui Ueyama83aa9792016-01-14 21:00:27 +00006763 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006764 ArgAddr = Addr;
6765 break;
John McCall7f416cc2015-09-08 08:05:57 +00006766 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006767
6768 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006769 Stride = SlotSize;
6770 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6771 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6772 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006773 break;
6774
6775 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006776 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006777 }
6778
6779 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006780 llvm::Value *NextPtr =
6781 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6782 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006783
John McCall7f416cc2015-09-08 08:05:57 +00006784 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006785}
6786
6787void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6788 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006789 for (auto &I : FI.arguments())
6790 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006791}
6792
6793namespace {
6794class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6795public:
6796 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6797 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006798
Craig Topper4f12f102014-03-12 06:41:41 +00006799 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006800 return 14;
6801 }
6802
6803 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006804 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006805};
6806} // end anonymous namespace
6807
Roman Divackyf02c9942014-02-24 18:46:27 +00006808bool
6809SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6810 llvm::Value *Address) const {
6811 // This is calculated from the LLVM and GCC tables and verified
6812 // against gcc output. AFAIK all ABIs use the same encoding.
6813
6814 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6815
6816 llvm::IntegerType *i8 = CGF.Int8Ty;
6817 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6818 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6819
6820 // 0-31: the 8-byte general-purpose registers
6821 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6822
6823 // 32-63: f0-31, the 4-byte floating-point registers
6824 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6825
6826 // Y = 64
6827 // PSR = 65
6828 // WIM = 66
6829 // TBR = 67
6830 // PC = 68
6831 // NPC = 69
6832 // FSR = 70
6833 // CSR = 71
6834 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006835
Roman Divackyf02c9942014-02-24 18:46:27 +00006836 // 72-87: d0-15, the 8-byte floating-point registers
6837 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6838
6839 return false;
6840}
6841
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006842
Robert Lytton0e076492013-08-13 09:43:10 +00006843//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006844// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006845//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006846
Robert Lytton0e076492013-08-13 09:43:10 +00006847namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006848
6849/// A SmallStringEnc instance is used to build up the TypeString by passing
6850/// it by reference between functions that append to it.
6851typedef llvm::SmallString<128> SmallStringEnc;
6852
6853/// TypeStringCache caches the meta encodings of Types.
6854///
6855/// The reason for caching TypeStrings is two fold:
6856/// 1. To cache a type's encoding for later uses;
6857/// 2. As a means to break recursive member type inclusion.
6858///
6859/// A cache Entry can have a Status of:
6860/// NonRecursive: The type encoding is not recursive;
6861/// Recursive: The type encoding is recursive;
6862/// Incomplete: An incomplete TypeString;
6863/// IncompleteUsed: An incomplete TypeString that has been used in a
6864/// Recursive type encoding.
6865///
6866/// A NonRecursive entry will have all of its sub-members expanded as fully
6867/// as possible. Whilst it may contain types which are recursive, the type
6868/// itself is not recursive and thus its encoding may be safely used whenever
6869/// the type is encountered.
6870///
6871/// A Recursive entry will have all of its sub-members expanded as fully as
6872/// possible. The type itself is recursive and it may contain other types which
6873/// are recursive. The Recursive encoding must not be used during the expansion
6874/// of a recursive type's recursive branch. For simplicity the code uses
6875/// IncompleteCount to reject all usage of Recursive encodings for member types.
6876///
6877/// An Incomplete entry is always a RecordType and only encodes its
6878/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6879/// are placed into the cache during type expansion as a means to identify and
6880/// handle recursive inclusion of types as sub-members. If there is recursion
6881/// the entry becomes IncompleteUsed.
6882///
6883/// During the expansion of a RecordType's members:
6884///
6885/// If the cache contains a NonRecursive encoding for the member type, the
6886/// cached encoding is used;
6887///
6888/// If the cache contains a Recursive encoding for the member type, the
6889/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6890///
6891/// If the member is a RecordType, an Incomplete encoding is placed into the
6892/// cache to break potential recursive inclusion of itself as a sub-member;
6893///
6894/// Once a member RecordType has been expanded, its temporary incomplete
6895/// entry is removed from the cache. If a Recursive encoding was swapped out
6896/// it is swapped back in;
6897///
6898/// If an incomplete entry is used to expand a sub-member, the incomplete
6899/// entry is marked as IncompleteUsed. The cache keeps count of how many
6900/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6901///
6902/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6903/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6904/// Else the member is part of a recursive type and thus the recursion has
6905/// been exited too soon for the encoding to be correct for the member.
6906///
6907class TypeStringCache {
6908 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6909 struct Entry {
6910 std::string Str; // The encoded TypeString for the type.
6911 enum Status State; // Information about the encoding in 'Str'.
6912 std::string Swapped; // A temporary place holder for a Recursive encoding
6913 // during the expansion of RecordType's members.
6914 };
6915 std::map<const IdentifierInfo *, struct Entry> Map;
6916 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6917 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6918public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006919 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006920 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6921 bool removeIncomplete(const IdentifierInfo *ID);
6922 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6923 bool IsRecursive);
6924 StringRef lookupStr(const IdentifierInfo *ID);
6925};
6926
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006927/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006928/// FieldEncoding is a helper for this ordering process.
6929class FieldEncoding {
6930 bool HasName;
6931 std::string Enc;
6932public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006933 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6934 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006935 bool operator<(const FieldEncoding &rhs) const {
6936 if (HasName != rhs.HasName) return HasName;
6937 return Enc < rhs.Enc;
6938 }
6939};
6940
Robert Lytton7d1db152013-08-19 09:46:39 +00006941class XCoreABIInfo : public DefaultABIInfo {
6942public:
6943 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006944 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6945 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006946};
6947
Robert Lyttond21e2d72014-03-03 13:45:29 +00006948class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006949 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006950public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006951 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006952 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006953 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6954 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006955};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006956
Robert Lytton2d196952013-10-11 10:29:34 +00006957} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006958
John McCall7f416cc2015-09-08 08:05:57 +00006959Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6960 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006961 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006962
Robert Lytton2d196952013-10-11 10:29:34 +00006963 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006964 CharUnits SlotSize = CharUnits::fromQuantity(4);
6965 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006966
Robert Lytton2d196952013-10-11 10:29:34 +00006967 // Handle the argument.
6968 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006969 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006970 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6971 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6972 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006973 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006974
6975 Address Val = Address::invalid();
6976 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006977 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006978 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006979 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006980 llvm_unreachable("Unsupported ABI kind for va_arg");
6981 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006982 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6983 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006984 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006985 case ABIArgInfo::Extend:
6986 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006987 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6988 ArgSize = CharUnits::fromQuantity(
6989 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
Rui Ueyama83aa9792016-01-14 21:00:27 +00006990 ArgSize = ArgSize.alignTo(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006991 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006992 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006993 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6994 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6995 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006996 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006997 }
Robert Lytton2d196952013-10-11 10:29:34 +00006998
6999 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00007000 if (!ArgSize.isZero()) {
7001 llvm::Value *APN =
7002 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
7003 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00007004 }
John McCall7f416cc2015-09-08 08:05:57 +00007005
Robert Lytton2d196952013-10-11 10:29:34 +00007006 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00007007}
Robert Lytton0e076492013-08-13 09:43:10 +00007008
Robert Lytton844aeeb2014-05-02 09:33:20 +00007009/// During the expansion of a RecordType, an incomplete TypeString is placed
7010/// into the cache as a means to identify and break recursion.
7011/// If there is a Recursive encoding in the cache, it is swapped out and will
7012/// be reinserted by removeIncomplete().
7013/// All other types of encoding should have been used rather than arriving here.
7014void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
7015 std::string StubEnc) {
7016 if (!ID)
7017 return;
7018 Entry &E = Map[ID];
7019 assert( (E.Str.empty() || E.State == Recursive) &&
7020 "Incorrectly use of addIncomplete");
7021 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
7022 E.Swapped.swap(E.Str); // swap out the Recursive
7023 E.Str.swap(StubEnc);
7024 E.State = Incomplete;
7025 ++IncompleteCount;
7026}
7027
7028/// Once the RecordType has been expanded, the temporary incomplete TypeString
7029/// must be removed from the cache.
7030/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
7031/// Returns true if the RecordType was defined recursively.
7032bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
7033 if (!ID)
7034 return false;
7035 auto I = Map.find(ID);
7036 assert(I != Map.end() && "Entry not present");
7037 Entry &E = I->second;
7038 assert( (E.State == Incomplete ||
7039 E.State == IncompleteUsed) &&
7040 "Entry must be an incomplete type");
7041 bool IsRecursive = false;
7042 if (E.State == IncompleteUsed) {
7043 // We made use of our Incomplete encoding, thus we are recursive.
7044 IsRecursive = true;
7045 --IncompleteUsedCount;
7046 }
7047 if (E.Swapped.empty())
7048 Map.erase(I);
7049 else {
7050 // Swap the Recursive back.
7051 E.Swapped.swap(E.Str);
7052 E.Swapped.clear();
7053 E.State = Recursive;
7054 }
7055 --IncompleteCount;
7056 return IsRecursive;
7057}
7058
7059/// Add the encoded TypeString to the cache only if it is NonRecursive or
7060/// Recursive (viz: all sub-members were expanded as fully as possible).
7061void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
7062 bool IsRecursive) {
7063 if (!ID || IncompleteUsedCount)
7064 return; // No key or it is is an incomplete sub-type so don't add.
7065 Entry &E = Map[ID];
7066 if (IsRecursive && !E.Str.empty()) {
7067 assert(E.State==Recursive && E.Str.size() == Str.size() &&
7068 "This is not the same Recursive entry");
7069 // The parent container was not recursive after all, so we could have used
7070 // this Recursive sub-member entry after all, but we assumed the worse when
7071 // we started viz: IncompleteCount!=0.
7072 return;
7073 }
7074 assert(E.Str.empty() && "Entry already present");
7075 E.Str = Str.str();
7076 E.State = IsRecursive? Recursive : NonRecursive;
7077}
7078
7079/// Return a cached TypeString encoding for the ID. If there isn't one, or we
7080/// are recursively expanding a type (IncompleteCount != 0) and the cached
7081/// encoding is Recursive, return an empty StringRef.
7082StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
7083 if (!ID)
7084 return StringRef(); // We have no key.
7085 auto I = Map.find(ID);
7086 if (I == Map.end())
7087 return StringRef(); // We have no encoding.
7088 Entry &E = I->second;
7089 if (E.State == Recursive && IncompleteCount)
7090 return StringRef(); // We don't use Recursive encodings for member types.
7091
7092 if (E.State == Incomplete) {
7093 // The incomplete type is being used to break out of recursion.
7094 E.State = IncompleteUsed;
7095 ++IncompleteUsedCount;
7096 }
7097 return E.Str.c_str();
7098}
7099
7100/// The XCore ABI includes a type information section that communicates symbol
7101/// type information to the linker. The linker uses this information to verify
7102/// safety/correctness of things such as array bound and pointers et al.
7103/// The ABI only requires C (and XC) language modules to emit TypeStrings.
7104/// This type information (TypeString) is emitted into meta data for all global
7105/// symbols: definitions, declarations, functions & variables.
7106///
7107/// The TypeString carries type, qualifier, name, size & value details.
7108/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00007109/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00007110/// The output is tested by test/CodeGen/xcore-stringtype.c.
7111///
7112static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7113 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
7114
7115/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
7116void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
7117 CodeGen::CodeGenModule &CGM) const {
7118 SmallStringEnc Enc;
7119 if (getTypeString(Enc, D, CGM, TSC)) {
7120 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00007121 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
7122 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00007123 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
7124 llvm::NamedMDNode *MD =
7125 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
7126 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
7127 }
7128}
7129
7130static bool appendType(SmallStringEnc &Enc, QualType QType,
7131 const CodeGen::CodeGenModule &CGM,
7132 TypeStringCache &TSC);
7133
7134/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00007135/// Builds a SmallVector containing the encoded field types in declaration
7136/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007137static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
7138 const RecordDecl *RD,
7139 const CodeGen::CodeGenModule &CGM,
7140 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00007141 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007142 SmallStringEnc Enc;
7143 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00007144 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007145 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00007146 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00007147 Enc += "b(";
7148 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00007149 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00007150 Enc += ':';
7151 }
Hans Wennborga302cd92014-08-21 16:06:57 +00007152 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00007153 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00007154 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007155 Enc += ')';
7156 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007157 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007158 }
7159 return true;
7160}
7161
7162/// Appends structure and union types to Enc and adds encoding to cache.
7163/// Recursively calls appendType (via extractFieldType) for each field.
7164/// Union types have their fields ordered according to the ABI.
7165static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7166 const CodeGen::CodeGenModule &CGM,
7167 TypeStringCache &TSC, const IdentifierInfo *ID) {
7168 // Append the cached TypeString if we have one.
7169 StringRef TypeString = TSC.lookupStr(ID);
7170 if (!TypeString.empty()) {
7171 Enc += TypeString;
7172 return true;
7173 }
7174
7175 // Start to emit an incomplete TypeString.
7176 size_t Start = Enc.size();
7177 Enc += (RT->isUnionType()? 'u' : 's');
7178 Enc += '(';
7179 if (ID)
7180 Enc += ID->getName();
7181 Enc += "){";
7182
7183 // We collect all encoded fields and order as necessary.
7184 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007185 const RecordDecl *RD = RT->getDecl()->getDefinition();
7186 if (RD && !RD->field_empty()) {
7187 // An incomplete TypeString stub is placed in the cache for this RecordType
7188 // so that recursive calls to this RecordType will use it whilst building a
7189 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007190 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007191 std::string StubEnc(Enc.substr(Start).str());
7192 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7193 TSC.addIncomplete(ID, std::move(StubEnc));
7194 if (!extractFieldType(FE, RD, CGM, TSC)) {
7195 (void) TSC.removeIncomplete(ID);
7196 return false;
7197 }
7198 IsRecursive = TSC.removeIncomplete(ID);
7199 // The ABI requires unions to be sorted but not structures.
7200 // See FieldEncoding::operator< for sort algorithm.
7201 if (RT->isUnionType())
7202 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007203 // We can now complete the TypeString.
7204 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007205 for (unsigned I = 0; I != E; ++I) {
7206 if (I)
7207 Enc += ',';
7208 Enc += FE[I].str();
7209 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007210 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007211 Enc += '}';
7212 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7213 return true;
7214}
7215
7216/// Appends enum types to Enc and adds the encoding to the cache.
7217static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7218 TypeStringCache &TSC,
7219 const IdentifierInfo *ID) {
7220 // Append the cached TypeString if we have one.
7221 StringRef TypeString = TSC.lookupStr(ID);
7222 if (!TypeString.empty()) {
7223 Enc += TypeString;
7224 return true;
7225 }
7226
7227 size_t Start = Enc.size();
7228 Enc += "e(";
7229 if (ID)
7230 Enc += ID->getName();
7231 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007232
7233 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007234 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007235 SmallVector<FieldEncoding, 16> FE;
7236 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7237 ++I) {
7238 SmallStringEnc EnumEnc;
7239 EnumEnc += "m(";
7240 EnumEnc += I->getName();
7241 EnumEnc += "){";
7242 I->getInitVal().toString(EnumEnc);
7243 EnumEnc += '}';
7244 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7245 }
7246 std::sort(FE.begin(), FE.end());
7247 unsigned E = FE.size();
7248 for (unsigned I = 0; I != E; ++I) {
7249 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007250 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007251 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007252 }
7253 }
7254 Enc += '}';
7255 TSC.addIfComplete(ID, Enc.substr(Start), false);
7256 return true;
7257}
7258
7259/// Appends type's qualifier to Enc.
7260/// This is done prior to appending the type's encoding.
7261static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7262 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007263 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007264 int Lookup = 0;
7265 if (QT.isConstQualified())
7266 Lookup += 1<<0;
7267 if (QT.isRestrictQualified())
7268 Lookup += 1<<1;
7269 if (QT.isVolatileQualified())
7270 Lookup += 1<<2;
7271 Enc += Table[Lookup];
7272}
7273
7274/// Appends built-in types to Enc.
7275static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7276 const char *EncType;
7277 switch (BT->getKind()) {
7278 case BuiltinType::Void:
7279 EncType = "0";
7280 break;
7281 case BuiltinType::Bool:
7282 EncType = "b";
7283 break;
7284 case BuiltinType::Char_U:
7285 EncType = "uc";
7286 break;
7287 case BuiltinType::UChar:
7288 EncType = "uc";
7289 break;
7290 case BuiltinType::SChar:
7291 EncType = "sc";
7292 break;
7293 case BuiltinType::UShort:
7294 EncType = "us";
7295 break;
7296 case BuiltinType::Short:
7297 EncType = "ss";
7298 break;
7299 case BuiltinType::UInt:
7300 EncType = "ui";
7301 break;
7302 case BuiltinType::Int:
7303 EncType = "si";
7304 break;
7305 case BuiltinType::ULong:
7306 EncType = "ul";
7307 break;
7308 case BuiltinType::Long:
7309 EncType = "sl";
7310 break;
7311 case BuiltinType::ULongLong:
7312 EncType = "ull";
7313 break;
7314 case BuiltinType::LongLong:
7315 EncType = "sll";
7316 break;
7317 case BuiltinType::Float:
7318 EncType = "ft";
7319 break;
7320 case BuiltinType::Double:
7321 EncType = "d";
7322 break;
7323 case BuiltinType::LongDouble:
7324 EncType = "ld";
7325 break;
7326 default:
7327 return false;
7328 }
7329 Enc += EncType;
7330 return true;
7331}
7332
7333/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7334static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7335 const CodeGen::CodeGenModule &CGM,
7336 TypeStringCache &TSC) {
7337 Enc += "p(";
7338 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7339 return false;
7340 Enc += ')';
7341 return true;
7342}
7343
7344/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007345static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7346 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007347 const CodeGen::CodeGenModule &CGM,
7348 TypeStringCache &TSC, StringRef NoSizeEnc) {
7349 if (AT->getSizeModifier() != ArrayType::Normal)
7350 return false;
7351 Enc += "a(";
7352 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7353 CAT->getSize().toStringUnsigned(Enc);
7354 else
7355 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7356 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007357 // The Qualifiers should be attached to the type rather than the array.
7358 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007359 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7360 return false;
7361 Enc += ')';
7362 return true;
7363}
7364
7365/// Appends a function encoding to Enc, calling appendType for the return type
7366/// and the arguments.
7367static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7368 const CodeGen::CodeGenModule &CGM,
7369 TypeStringCache &TSC) {
7370 Enc += "f{";
7371 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7372 return false;
7373 Enc += "}(";
7374 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7375 // N.B. we are only interested in the adjusted param types.
7376 auto I = FPT->param_type_begin();
7377 auto E = FPT->param_type_end();
7378 if (I != E) {
7379 do {
7380 if (!appendType(Enc, *I, CGM, TSC))
7381 return false;
7382 ++I;
7383 if (I != E)
7384 Enc += ',';
7385 } while (I != E);
7386 if (FPT->isVariadic())
7387 Enc += ",va";
7388 } else {
7389 if (FPT->isVariadic())
7390 Enc += "va";
7391 else
7392 Enc += '0';
7393 }
7394 }
7395 Enc += ')';
7396 return true;
7397}
7398
7399/// Handles the type's qualifier before dispatching a call to handle specific
7400/// type encodings.
7401static bool appendType(SmallStringEnc &Enc, QualType QType,
7402 const CodeGen::CodeGenModule &CGM,
7403 TypeStringCache &TSC) {
7404
7405 QualType QT = QType.getCanonicalType();
7406
Robert Lytton6adb20f2014-06-05 09:06:21 +00007407 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7408 // The Qualifiers should be attached to the type rather than the array.
7409 // Thus we don't call appendQualifier() here.
7410 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7411
Robert Lytton844aeeb2014-05-02 09:33:20 +00007412 appendQualifier(Enc, QT);
7413
7414 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7415 return appendBuiltinType(Enc, BT);
7416
Robert Lytton844aeeb2014-05-02 09:33:20 +00007417 if (const PointerType *PT = QT->getAs<PointerType>())
7418 return appendPointerType(Enc, PT, CGM, TSC);
7419
7420 if (const EnumType *ET = QT->getAs<EnumType>())
7421 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7422
7423 if (const RecordType *RT = QT->getAsStructureType())
7424 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7425
7426 if (const RecordType *RT = QT->getAsUnionType())
7427 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7428
7429 if (const FunctionType *FT = QT->getAs<FunctionType>())
7430 return appendFunctionType(Enc, FT, CGM, TSC);
7431
7432 return false;
7433}
7434
7435static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7436 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7437 if (!D)
7438 return false;
7439
7440 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7441 if (FD->getLanguageLinkage() != CLanguageLinkage)
7442 return false;
7443 return appendType(Enc, FD->getType(), CGM, TSC);
7444 }
7445
7446 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7447 if (VD->getLanguageLinkage() != CLanguageLinkage)
7448 return false;
7449 QualType QT = VD->getType().getCanonicalType();
7450 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7451 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007452 // The Qualifiers should be attached to the type rather than the array.
7453 // Thus we don't call appendQualifier() here.
7454 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007455 }
7456 return appendType(Enc, QT, CGM, TSC);
7457 }
7458 return false;
7459}
7460
7461
Robert Lytton0e076492013-08-13 09:43:10 +00007462//===----------------------------------------------------------------------===//
7463// Driver code
7464//===----------------------------------------------------------------------===//
7465
Rafael Espindola9f834732014-09-19 01:54:22 +00007466const llvm::Triple &CodeGenModule::getTriple() const {
7467 return getTarget().getTriple();
7468}
7469
7470bool CodeGenModule::supportsCOMDAT() const {
7471 return !getTriple().isOSBinFormatMachO();
7472}
7473
Chris Lattner2b037972010-07-29 02:01:43 +00007474const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007475 if (TheTargetCodeGenInfo)
7476 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007477
John McCallc8e01702013-04-16 22:48:15 +00007478 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007479 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007480 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007481 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007482
Derek Schuff09338a22012-09-06 17:37:28 +00007483 case llvm::Triple::le32:
7484 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007485 case llvm::Triple::mips:
7486 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007487 if (Triple.getOS() == llvm::Triple::NaCl)
7488 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007489 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7490
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007491 case llvm::Triple::mips64:
7492 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007493 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7494
Tim Northover25e8a672014-05-24 12:51:25 +00007495 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007496 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007497 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007498 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007499 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007500
Tim Northover573cbee2014-05-24 12:52:07 +00007501 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007502 }
7503
Dan Gohmanc2853072015-09-03 22:51:53 +00007504 case llvm::Triple::wasm32:
7505 case llvm::Triple::wasm64:
7506 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7507
Daniel Dunbard59655c2009-09-12 00:59:49 +00007508 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007509 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007510 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007511 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007512 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007513 if (Triple.getOS() == llvm::Triple::Win32) {
7514 TheTargetCodeGenInfo =
7515 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7516 return *TheTargetCodeGenInfo;
7517 }
7518
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007519 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Tim Northover5627d392015-10-30 16:30:45 +00007520 StringRef ABIStr = getTarget().getABI();
7521 if (ABIStr == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007522 Kind = ARMABIInfo::APCS;
Tim Northover5627d392015-10-30 16:30:45 +00007523 else if (ABIStr == "aapcs16")
7524 Kind = ARMABIInfo::AAPCS16_VFP;
David Tweed8f676532012-10-25 13:33:01 +00007525 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007526 (CodeGenOpts.FloatABI != "soft" &&
7527 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007528 Kind = ARMABIInfo::AAPCS_VFP;
7529
Derek Schuff71658bd2015-01-29 00:47:04 +00007530 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007531 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007532
John McCallea8d8bb2010-03-11 00:10:12 +00007533 case llvm::Triple::ppc:
Petar Jovanovic88a328f2015-12-14 17:51:50 +00007534 return *(TheTargetCodeGenInfo =
7535 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
Roman Divackyd966e722012-05-09 18:22:46 +00007536 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007537 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007538 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007539 if (getTarget().getABI() == "elfv2")
7540 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007541 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007542
Ulrich Weigandb7122372014-07-21 00:48:09 +00007543 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007544 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007545 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007546 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007547 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007548 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007549 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007550 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007551 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007552 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007553
Ulrich Weigandb7122372014-07-21 00:48:09 +00007554 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007555 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007556 }
John McCallea8d8bb2010-03-11 00:10:12 +00007557
Peter Collingbournec947aae2012-05-20 23:28:41 +00007558 case llvm::Triple::nvptx:
7559 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007560 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007561
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007562 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007563 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007564
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007565 case llvm::Triple::systemz: {
7566 bool HasVector = getTarget().getABI() == "vector";
7567 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7568 HasVector));
7569 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007570
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007571 case llvm::Triple::tce:
7572 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7573
Eli Friedman33465822011-07-08 23:31:17 +00007574 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007575 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007576 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007577 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007578 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007579
John McCall1fe2a8c2013-06-18 02:46:29 +00007580 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007581 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007582 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Eric Christopher7565e0d2015-05-29 23:09:49 +00007583 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007584 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007585 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007586 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00007587 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7588 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007589 }
Eli Friedman33465822011-07-08 23:31:17 +00007590 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007591
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007592 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007593 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007594 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7595 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007596 X86AVXABILevel::None);
7597
Chris Lattner04dc9572010-08-31 16:44:54 +00007598 switch (Triple.getOS()) {
7599 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007600 return *(TheTargetCodeGenInfo =
7601 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007602 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007603 return *(TheTargetCodeGenInfo =
7604 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007605 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007606 return *(TheTargetCodeGenInfo =
7607 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007608 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007609 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007610 case llvm::Triple::hexagon:
7611 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007612 case llvm::Triple::r600:
7613 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007614 case llvm::Triple::amdgcn:
7615 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007616 case llvm::Triple::sparcv9:
7617 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007618 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007619 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007620 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007621}