blob: 282c1038b56f67141fad9eff7ed5b07f729cfcec [file] [log] [blame]
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001//===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// These classes wrap the information about a call or function
11// definition used to handle ABI compliancy.
12//
13//===----------------------------------------------------------------------===//
14
Anton Korobeynikov55bcea12010-01-10 12:58:08 +000015#include "TargetInfo.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000016#include "ABIInfo.h"
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000017#include "CGCXXABI.h"
Reid Kleckner9b3e3df2014-09-04 20:04:38 +000018#include "CGValue.h"
Anton Korobeynikov244360d2009-06-05 22:08:42 +000019#include "CodeGenFunction.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000020#include "clang/AST/RecordLayout.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000021#include "clang/CodeGen/CGFunctionInfo.h"
Sandeep Patel45df3dd2011-04-05 00:23:47 +000022#include "clang/Frontend/CodeGenOptions.h"
Matt Arsenault43fae6c2014-12-04 20:38:18 +000023#include "llvm/ADT/StringExtras.h"
Daniel Dunbare3532f82009-08-24 08:52:16 +000024#include "llvm/ADT/Triple.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/Type.h"
Daniel Dunbar7230fa52009-12-03 09:13:49 +000027#include "llvm/Support/raw_ostream.h"
Robert Lytton844aeeb2014-05-02 09:33:20 +000028#include <algorithm> // std::sort
29
Anton Korobeynikov244360d2009-06-05 22:08:42 +000030using namespace clang;
31using namespace CodeGen;
32
John McCall943fae92010-05-27 06:19:26 +000033static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
34 llvm::Value *Array,
35 llvm::Value *Value,
36 unsigned FirstIndex,
37 unsigned LastIndex) {
38 // Alternatively, we could emit this as a loop in the source.
39 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
David Blaikiefb901c7a2015-04-04 15:12:29 +000040 llvm::Value *Cell =
41 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
John McCall7f416cc2015-09-08 08:05:57 +000042 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
John McCall943fae92010-05-27 06:19:26 +000043 }
44}
45
John McCalla1dee5302010-08-22 10:59:02 +000046static bool isAggregateTypeForABI(QualType T) {
John McCall47fb9502013-03-07 21:37:08 +000047 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
John McCalla1dee5302010-08-22 10:59:02 +000048 T->isMemberFunctionPointerType();
49}
50
John McCall7f416cc2015-09-08 08:05:57 +000051ABIArgInfo
52ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
53 llvm::Type *Padding) const {
54 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
55 ByRef, Realign, Padding);
56}
57
58ABIArgInfo
59ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
60 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
61 /*ByRef*/ false, Realign);
62}
63
Charles Davisc7d5c942015-09-17 20:55:33 +000064Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
65 QualType Ty) const {
66 return Address::invalid();
67}
68
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000069ABIInfo::~ABIInfo() {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +000070
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000071static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
Mark Lacey3825e832013-10-06 01:33:34 +000072 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000073 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
74 if (!RD)
75 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000076 return CXXABI.getRecordArgABI(RD);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000077}
78
79static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
Mark Lacey3825e832013-10-06 01:33:34 +000080 CGCXXABI &CXXABI) {
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +000081 const RecordType *RT = T->getAs<RecordType>();
82 if (!RT)
83 return CGCXXABI::RAA_Default;
Mark Lacey3825e832013-10-06 01:33:34 +000084 return getRecordArgABI(RT, CXXABI);
85}
86
Reid Klecknerb1be6832014-11-15 01:41:41 +000087/// Pass transparent unions as if they were the type of the first element. Sema
88/// should ensure that all elements of the union have the same "machine type".
89static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
90 if (const RecordType *UT = Ty->getAsUnionType()) {
91 const RecordDecl *UD = UT->getDecl();
92 if (UD->hasAttr<TransparentUnionAttr>()) {
93 assert(!UD->field_empty() && "sema created an empty transparent union");
94 return UD->field_begin()->getType();
95 }
96 }
97 return Ty;
98}
99
Mark Lacey3825e832013-10-06 01:33:34 +0000100CGCXXABI &ABIInfo::getCXXABI() const {
101 return CGT.getCXXABI();
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000102}
103
Chris Lattner2b037972010-07-29 02:01:43 +0000104ASTContext &ABIInfo::getContext() const {
105 return CGT.getContext();
106}
107
108llvm::LLVMContext &ABIInfo::getVMContext() const {
109 return CGT.getLLVMContext();
110}
111
Micah Villmowdd31ca12012-10-08 16:25:52 +0000112const llvm::DataLayout &ABIInfo::getDataLayout() const {
113 return CGT.getDataLayout();
Chris Lattner2b037972010-07-29 02:01:43 +0000114}
115
John McCallc8e01702013-04-16 22:48:15 +0000116const TargetInfo &ABIInfo::getTarget() const {
117 return CGT.getTarget();
118}
Chris Lattner2b037972010-07-29 02:01:43 +0000119
Reid Klecknere9f6a712014-10-31 17:10:41 +0000120bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
121 return false;
122}
123
124bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
125 uint64_t Members) const {
126 return false;
127}
128
Petar Jovanovic1a3f9652015-05-26 21:07:19 +0000129bool ABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
130 return false;
131}
132
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000133void ABIArgInfo::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000134 raw_ostream &OS = llvm::errs();
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000135 OS << "(ABIArgInfo Kind=";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000136 switch (TheKind) {
137 case Direct:
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000138 OS << "Direct Type=";
Chris Lattner2192fe52011-07-18 04:24:23 +0000139 if (llvm::Type *Ty = getCoerceToType())
Chris Lattnerfe34c1d2010-07-29 06:26:06 +0000140 Ty->print(OS);
141 else
142 OS << "null";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000143 break;
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000144 case Extend:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000145 OS << "Extend";
Anton Korobeynikov18adbf52009-06-06 09:36:29 +0000146 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000147 case Ignore:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000148 OS << "Ignore";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000149 break;
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000150 case InAlloca:
151 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
152 break;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000153 case Indirect:
John McCall7f416cc2015-09-08 08:05:57 +0000154 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
Joerg Sonnenberger4921fe22011-07-15 18:23:44 +0000155 << " ByVal=" << getIndirectByVal()
Daniel Dunbar7b7c2932010-09-16 20:42:02 +0000156 << " Realign=" << getIndirectRealign();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000157 break;
158 case Expand:
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000159 OS << "Expand";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000160 break;
161 }
Daniel Dunbar7230fa52009-12-03 09:13:49 +0000162 OS << ")\n";
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000163}
164
John McCall7f416cc2015-09-08 08:05:57 +0000165/// Emit va_arg for a platform using the common void* representation,
166/// where arguments are simply emitted in an array of slots on the stack.
167///
168/// This version implements the core direct-value passing rules.
169///
170/// \param SlotSize - The size and alignment of a stack slot.
171/// Each argument will be allocated to a multiple of this number of
172/// slots, and all the slots will be aligned to this value.
173/// \param AllowHigherAlign - The slot alignment is not a cap;
174/// an argument type with an alignment greater than the slot size
175/// will be emitted on a higher-alignment address, potentially
176/// leaving one or more empty slots behind as padding. If this
177/// is false, the returned address might be less-aligned than
178/// DirectAlign.
179static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
180 Address VAListAddr,
181 llvm::Type *DirectTy,
182 CharUnits DirectSize,
183 CharUnits DirectAlign,
184 CharUnits SlotSize,
185 bool AllowHigherAlign) {
186 // Cast the element type to i8* if necessary. Some platforms define
187 // va_list as a struct containing an i8* instead of just an i8*.
188 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
189 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
190
191 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
192
193 // If the CC aligns values higher than the slot size, do so if needed.
194 Address Addr = Address::invalid();
195 if (AllowHigherAlign && DirectAlign > SlotSize) {
196 llvm::Value *PtrAsInt = Ptr;
197 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
198 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
199 llvm::ConstantInt::get(CGF.IntPtrTy, DirectAlign.getQuantity() - 1));
200 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
201 llvm::ConstantInt::get(CGF.IntPtrTy, -DirectAlign.getQuantity()));
202 Addr = Address(CGF.Builder.CreateIntToPtr(PtrAsInt, Ptr->getType(),
203 "argp.cur.aligned"),
204 DirectAlign);
205 } else {
206 Addr = Address(Ptr, SlotSize);
207 }
208
209 // Advance the pointer past the argument, then store that back.
210 CharUnits FullDirectSize = DirectSize.RoundUpToAlignment(SlotSize);
211 llvm::Value *NextPtr =
212 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
213 "argp.next");
214 CGF.Builder.CreateStore(NextPtr, VAListAddr);
215
216 // If the argument is smaller than a slot, and this is a big-endian
217 // target, the argument will be right-adjusted in its slot.
218 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian()) {
219 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
220 }
221
222 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
223 return Addr;
224}
225
226/// Emit va_arg for a platform using the common void* representation,
227/// where arguments are simply emitted in an array of slots on the stack.
228///
229/// \param IsIndirect - Values of this type are passed indirectly.
230/// \param ValueInfo - The size and alignment of this type, generally
231/// computed with getContext().getTypeInfoInChars(ValueTy).
232/// \param SlotSizeAndAlign - The size and alignment of a stack slot.
233/// Each argument will be allocated to a multiple of this number of
234/// slots, and all the slots will be aligned to this value.
235/// \param AllowHigherAlign - The slot alignment is not a cap;
236/// an argument type with an alignment greater than the slot size
237/// will be emitted on a higher-alignment address, potentially
238/// leaving one or more empty slots behind as padding.
239static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
240 QualType ValueTy, bool IsIndirect,
241 std::pair<CharUnits, CharUnits> ValueInfo,
242 CharUnits SlotSizeAndAlign,
243 bool AllowHigherAlign) {
244 // The size and alignment of the value that was passed directly.
245 CharUnits DirectSize, DirectAlign;
246 if (IsIndirect) {
247 DirectSize = CGF.getPointerSize();
248 DirectAlign = CGF.getPointerAlign();
249 } else {
250 DirectSize = ValueInfo.first;
251 DirectAlign = ValueInfo.second;
252 }
253
254 // Cast the address we've calculated to the right type.
255 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
256 if (IsIndirect)
257 DirectTy = DirectTy->getPointerTo(0);
258
259 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
260 DirectSize, DirectAlign,
261 SlotSizeAndAlign,
262 AllowHigherAlign);
263
264 if (IsIndirect) {
265 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
266 }
267
268 return Addr;
269
270}
271
272static Address emitMergePHI(CodeGenFunction &CGF,
273 Address Addr1, llvm::BasicBlock *Block1,
274 Address Addr2, llvm::BasicBlock *Block2,
275 const llvm::Twine &Name = "") {
276 assert(Addr1.getType() == Addr2.getType());
277 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
278 PHI->addIncoming(Addr1.getPointer(), Block1);
279 PHI->addIncoming(Addr2.getPointer(), Block2);
280 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
281 return Address(PHI, Align);
282}
283
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000284TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
285
John McCall3480ef22011-08-30 01:42:09 +0000286// If someone can figure out a general rule for this, that would be great.
287// It's probably just doomed to be platform-dependent, though.
288unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
289 // Verified for:
290 // x86-64 FreeBSD, Linux, Darwin
291 // x86-32 FreeBSD, Linux, Darwin
292 // PowerPC Linux, Darwin
293 // ARM Darwin (*not* EABI)
Tim Northover9bb857a2013-01-31 12:13:10 +0000294 // AArch64 Linux
John McCall3480ef22011-08-30 01:42:09 +0000295 return 32;
296}
297
John McCalla729c622012-02-17 03:33:10 +0000298bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
299 const FunctionNoProtoType *fnType) const {
John McCallcbc038a2011-09-21 08:08:30 +0000300 // The following conventions are known to require this to be false:
301 // x86_stdcall
302 // MIPS
303 // For everything else, we just prefer false unless we opt out.
304 return false;
305}
306
Reid Klecknere43f0fe2013-05-08 13:44:39 +0000307void
308TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
309 llvm::SmallString<24> &Opt) const {
310 // This assumes the user is passing a library name like "rt" instead of a
311 // filename like "librt.a/so", and that they don't care whether it's static or
312 // dynamic.
313 Opt = "-l";
314 Opt += Lib;
315}
316
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000317static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000318
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000319/// isEmptyField - Return true iff a the field is "empty", that is it
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000320/// is an unnamed bit-field or an (array of) empty record(s).
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000321static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
322 bool AllowArrays) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000323 if (FD->isUnnamedBitfield())
324 return true;
325
326 QualType FT = FD->getType();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000327
Eli Friedman0b3f2012011-11-18 03:47:20 +0000328 // Constant arrays of empty records count as empty, strip them off.
329 // Constant arrays of zero length always count as empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000330 if (AllowArrays)
Eli Friedman0b3f2012011-11-18 03:47:20 +0000331 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
332 if (AT->getSize() == 0)
333 return true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000334 FT = AT->getElementType();
Eli Friedman0b3f2012011-11-18 03:47:20 +0000335 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000336
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000337 const RecordType *RT = FT->getAs<RecordType>();
338 if (!RT)
339 return false;
340
341 // C++ record fields are never empty, at least in the Itanium ABI.
342 //
343 // FIXME: We should use a predicate for whether this behavior is true in the
344 // current ABI.
345 if (isa<CXXRecordDecl>(RT->getDecl()))
346 return false;
347
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000348 return isEmptyRecord(Context, FT, AllowArrays);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000349}
350
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000351/// isEmptyRecord - Return true iff a structure contains only empty
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000352/// fields. Note that a structure with a flexible array member is not
353/// considered empty.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000354static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000355 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000356 if (!RT)
357 return 0;
358 const RecordDecl *RD = RT->getDecl();
359 if (RD->hasFlexibleArrayMember())
360 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000361
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000362 // If this is a C++ record, check the bases first.
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000363 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +0000364 for (const auto &I : CXXRD->bases())
365 if (!isEmptyRecord(Context, I.getType(), true))
Argyrios Kyrtzidisd42411f2011-05-17 02:17:52 +0000366 return false;
Daniel Dunbarcd20ce12010-05-17 16:46:00 +0000367
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000368 for (const auto *I : RD->fields())
369 if (!isEmptyField(Context, I, AllowArrays))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000370 return false;
371 return true;
372}
373
374/// isSingleElementStruct - Determine if a structure is a "single
375/// element struct", i.e. it has exactly one non-empty field or
376/// exactly one field which is itself a single element
377/// struct. Structures with flexible array members are never
378/// considered single element structs.
379///
380/// \return The field declaration for the single non-empty field, if
381/// it exists.
382static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
Benjamin Kramer83b1bf32015-03-02 16:09:24 +0000383 const RecordType *RT = T->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000384 if (!RT)
Craig Topper8a13c412014-05-21 05:09:00 +0000385 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000386
387 const RecordDecl *RD = RT->getDecl();
388 if (RD->hasFlexibleArrayMember())
Craig Topper8a13c412014-05-21 05:09:00 +0000389 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000390
Craig Topper8a13c412014-05-21 05:09:00 +0000391 const Type *Found = nullptr;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000392
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000393 // If this is a C++ record, check the bases first.
394 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000395 for (const auto &I : CXXRD->bases()) {
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000396 // Ignore empty records.
Aaron Ballman574705e2014-03-13 15:41:46 +0000397 if (isEmptyRecord(Context, I.getType(), true))
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000398 continue;
399
400 // If we already found an element then this isn't a single-element struct.
401 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000402 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000403
404 // If this is non-empty and not a single element struct, the composite
405 // cannot be a single element struct.
Aaron Ballman574705e2014-03-13 15:41:46 +0000406 Found = isSingleElementStruct(I.getType(), Context);
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000407 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000408 return nullptr;
Daniel Dunbar12ebb472010-05-11 21:15:36 +0000409 }
410 }
411
412 // Check for single element.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000413 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000414 QualType FT = FD->getType();
415
416 // Ignore empty fields.
Daniel Dunbar626f1d82009-09-13 08:03:58 +0000417 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000418 continue;
419
420 // If we already found an element then this isn't a single-element
421 // struct.
422 if (Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000423 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000424
425 // Treat single element arrays as the element.
426 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
427 if (AT->getSize().getZExtValue() != 1)
428 break;
429 FT = AT->getElementType();
430 }
431
John McCalla1dee5302010-08-22 10:59:02 +0000432 if (!isAggregateTypeForABI(FT)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000433 Found = FT.getTypePtr();
434 } else {
435 Found = isSingleElementStruct(FT, Context);
436 if (!Found)
Craig Topper8a13c412014-05-21 05:09:00 +0000437 return nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000438 }
439 }
440
Eli Friedmanee945342011-11-18 01:25:50 +0000441 // We don't consider a struct a single-element struct if it has
442 // padding beyond the element type.
443 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
Craig Topper8a13c412014-05-21 05:09:00 +0000444 return nullptr;
Eli Friedmanee945342011-11-18 01:25:50 +0000445
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000446 return Found;
447}
448
449static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
Eli Friedmana92db672012-11-29 23:21:04 +0000450 // Treat complex types as the element type.
451 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
452 Ty = CTy->getElementType();
453
454 // Check for a type which we know has a simple scalar argument-passing
455 // convention without any padding. (We're specifically looking for 32
456 // and 64-bit integer and integer-equivalents, float, and double.)
Daniel Dunbar6b45b672010-05-14 03:40:53 +0000457 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
Eli Friedmana92db672012-11-29 23:21:04 +0000458 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000459 return false;
460
461 uint64_t Size = Context.getTypeSize(Ty);
462 return Size == 32 || Size == 64;
463}
464
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000465/// canExpandIndirectArgument - Test whether an argument type which is to be
466/// passed indirectly (on the stack) would have the equivalent layout if it was
467/// expanded into separate arguments. If so, we prefer to do the latter to avoid
468/// inhibiting optimizations.
469///
470// FIXME: This predicate is missing many cases, currently it just follows
471// llvm-gcc (checks that all fields are 32-bit or 64-bit primitive types). We
472// should probably make this smarter, or better yet make the LLVM backend
473// capable of handling it.
474static bool canExpandIndirectArgument(QualType Ty, ASTContext &Context) {
475 // We can only expand structure types.
476 const RecordType *RT = Ty->getAs<RecordType>();
477 if (!RT)
478 return false;
479
480 // We can only expand (C) structures.
481 //
482 // FIXME: This needs to be generalized to handle classes as well.
483 const RecordDecl *RD = RT->getDecl();
Manman Ren27382782015-04-03 18:10:29 +0000484 if (!RD->isStruct())
Daniel Dunbar11c08c82009-11-09 01:33:53 +0000485 return false;
486
Manman Ren27382782015-04-03 18:10:29 +0000487 // We try to expand CLike CXXRecordDecl.
488 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
489 if (!CXXRD->isCLike())
490 return false;
491 }
492
Eli Friedmane5c85622011-11-18 01:32:26 +0000493 uint64_t Size = 0;
494
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000495 for (const auto *FD : RD->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000496 if (!is32Or64BitBasicType(FD->getType(), Context))
497 return false;
498
499 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
500 // how to expand them yet, and the predicate for telling if a bitfield still
501 // counts as "basic" is more complicated than what we were doing previously.
502 if (FD->isBitField())
503 return false;
Eli Friedmane5c85622011-11-18 01:32:26 +0000504
505 Size += Context.getTypeSize(FD->getType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000506 }
507
Eli Friedmane5c85622011-11-18 01:32:26 +0000508 // Make sure there are not any holes in the struct.
509 if (Size != Context.getTypeSize(Ty))
510 return false;
511
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000512 return true;
513}
514
515namespace {
516/// DefaultABIInfo - The default implementation for ABI specific
517/// details. This implementation provides information which results in
518/// self-consistent and sensible LLVM IR generation, but does not
519/// conform to any particular ABI.
520class DefaultABIInfo : public ABIInfo {
Chris Lattner2b037972010-07-29 02:01:43 +0000521public:
522 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000523
Chris Lattner458b2aa2010-07-29 02:16:43 +0000524 ABIArgInfo classifyReturnType(QualType RetTy) const;
525 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000526
Craig Topper4f12f102014-03-12 06:41:41 +0000527 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000528 if (!getCXXABI().classifyReturnType(FI))
529 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +0000530 for (auto &I : FI.arguments())
531 I.info = classifyArgumentType(I.type);
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000532 }
533
John McCall7f416cc2015-09-08 08:05:57 +0000534 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
535 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000536};
537
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000538class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
539public:
Chris Lattner2b037972010-07-29 02:01:43 +0000540 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
541 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000542};
543
John McCall7f416cc2015-09-08 08:05:57 +0000544Address DefaultABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
545 QualType Ty) const {
546 return Address::invalid();
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000547}
548
Chris Lattner458b2aa2010-07-29 02:16:43 +0000549ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerac385062015-05-18 22:46:30 +0000550 Ty = useFirstFieldIfTransparentUnion(Ty);
551
552 if (isAggregateTypeForABI(Ty)) {
553 // Records with non-trivial destructors/copy-constructors should not be
554 // passed by value.
555 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000556 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Reid Klecknerac385062015-05-18 22:46:30 +0000557
John McCall7f416cc2015-09-08 08:05:57 +0000558 return getNaturalAlignIndirect(Ty);
Reid Klecknerac385062015-05-18 22:46:30 +0000559 }
Daniel Dunbar557893d2010-04-21 19:10:51 +0000560
Chris Lattner9723d6c2010-03-11 18:19:55 +0000561 // Treat an enum type as its underlying type.
562 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
563 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +0000564
Chris Lattner9723d6c2010-03-11 18:19:55 +0000565 return (Ty->isPromotableIntegerType() ?
566 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000567}
568
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000569ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
570 if (RetTy->isVoidType())
571 return ABIArgInfo::getIgnore();
572
573 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000574 return getNaturalAlignIndirect(RetTy);
Bob Wilsonbd4520b2011-01-10 23:54:17 +0000575
576 // Treat an enum type as its underlying type.
577 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
578 RetTy = EnumTy->getDecl()->getIntegerType();
579
580 return (RetTy->isPromotableIntegerType() ?
581 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
582}
583
Derek Schuff09338a22012-09-06 17:37:28 +0000584//===----------------------------------------------------------------------===//
Dan Gohmanc2853072015-09-03 22:51:53 +0000585// WebAssembly ABI Implementation
586//
587// This is a very simple ABI that relies a lot on DefaultABIInfo.
588//===----------------------------------------------------------------------===//
589
590class WebAssemblyABIInfo final : public DefaultABIInfo {
591public:
592 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
593 : DefaultABIInfo(CGT) {}
594
595private:
596 ABIArgInfo classifyReturnType(QualType RetTy) const;
597 ABIArgInfo classifyArgumentType(QualType Ty) const;
598
599 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
600 // non-virtual, but computeInfo is virtual, so we overload that.
601 void computeInfo(CGFunctionInfo &FI) const override {
602 if (!getCXXABI().classifyReturnType(FI))
603 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
604 for (auto &Arg : FI.arguments())
605 Arg.info = classifyArgumentType(Arg.type);
606 }
607};
608
609class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
610public:
611 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
612 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
613};
614
615/// \brief Classify argument of given type \p Ty.
616ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
617 Ty = useFirstFieldIfTransparentUnion(Ty);
618
619 if (isAggregateTypeForABI(Ty)) {
620 // Records with non-trivial destructors/copy-constructors should not be
621 // passed by value.
Dan Gohmanc2853072015-09-03 22:51:53 +0000622 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000623 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Dan Gohmanc2853072015-09-03 22:51:53 +0000624 // Ignore empty structs/unions.
625 if (isEmptyRecord(getContext(), Ty, true))
626 return ABIArgInfo::getIgnore();
627 // Lower single-element structs to just pass a regular value. TODO: We
628 // could do reasonable-size multiple-element structs too, using getExpand(),
629 // though watch out for things like bitfields.
630 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
631 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
Dan Gohmanc2853072015-09-03 22:51:53 +0000632 }
633
634 // Otherwise just do the default thing.
635 return DefaultABIInfo::classifyArgumentType(Ty);
636}
637
638ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
639 if (isAggregateTypeForABI(RetTy)) {
640 // Records with non-trivial destructors/copy-constructors should not be
641 // returned by value.
642 if (!getRecordArgABI(RetTy, getCXXABI())) {
643 // Ignore empty structs/unions.
644 if (isEmptyRecord(getContext(), RetTy, true))
645 return ABIArgInfo::getIgnore();
646 // Lower single-element structs to just return a regular value. TODO: We
647 // could do reasonable-size multiple-element structs too, using
648 // ABIArgInfo::getDirect().
649 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
650 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
651 }
652 }
653
654 // Otherwise just do the default thing.
655 return DefaultABIInfo::classifyReturnType(RetTy);
656}
657
658//===----------------------------------------------------------------------===//
Derek Schuff09338a22012-09-06 17:37:28 +0000659// le32/PNaCl bitcode ABI Implementation
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000660//
661// This is a simplified version of the x86_32 ABI. Arguments and return values
662// are always passed on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000663//===----------------------------------------------------------------------===//
664
665class PNaClABIInfo : public ABIInfo {
666 public:
667 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
668
669 ABIArgInfo classifyReturnType(QualType RetTy) const;
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000670 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Derek Schuff09338a22012-09-06 17:37:28 +0000671
Craig Topper4f12f102014-03-12 06:41:41 +0000672 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000673 Address EmitVAArg(CodeGenFunction &CGF,
674 Address VAListAddr, QualType Ty) const override;
Derek Schuff09338a22012-09-06 17:37:28 +0000675};
676
677class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
678 public:
679 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
680 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
681};
682
683void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +0000684 if (!getCXXABI().classifyReturnType(FI))
Derek Schuff09338a22012-09-06 17:37:28 +0000685 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
686
Reid Kleckner40ca9132014-05-13 22:05:45 +0000687 for (auto &I : FI.arguments())
688 I.info = classifyArgumentType(I.type);
689}
Derek Schuff09338a22012-09-06 17:37:28 +0000690
John McCall7f416cc2015-09-08 08:05:57 +0000691Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
692 QualType Ty) const {
693 return Address::invalid();
Derek Schuff09338a22012-09-06 17:37:28 +0000694}
695
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000696/// \brief Classify argument of given type \p Ty.
697ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
Derek Schuff09338a22012-09-06 17:37:28 +0000698 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +0000699 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +0000700 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
701 return getNaturalAlignIndirect(Ty);
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000702 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
703 // Treat an enum type as its underlying type.
Derek Schuff09338a22012-09-06 17:37:28 +0000704 Ty = EnumTy->getDecl()->getIntegerType();
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000705 } else if (Ty->isFloatingType()) {
706 // Floating-point types don't go inreg.
707 return ABIArgInfo::getDirect();
Derek Schuff09338a22012-09-06 17:37:28 +0000708 }
Eli Bendersky4f6791c2013-04-08 21:31:01 +0000709
710 return (Ty->isPromotableIntegerType() ?
711 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Derek Schuff09338a22012-09-06 17:37:28 +0000712}
713
714ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
715 if (RetTy->isVoidType())
716 return ABIArgInfo::getIgnore();
717
Eli Benderskye20dad62013-04-04 22:49:35 +0000718 // In the PNaCl ABI we always return records/structures on the stack.
Derek Schuff09338a22012-09-06 17:37:28 +0000719 if (isAggregateTypeForABI(RetTy))
John McCall7f416cc2015-09-08 08:05:57 +0000720 return getNaturalAlignIndirect(RetTy);
Derek Schuff09338a22012-09-06 17:37:28 +0000721
722 // Treat an enum type as its underlying type.
723 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
724 RetTy = EnumTy->getDecl()->getIntegerType();
725
726 return (RetTy->isPromotableIntegerType() ?
727 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
728}
729
Chad Rosier651c1832013-03-25 21:00:27 +0000730/// IsX86_MMXType - Return true if this is an MMX type.
731bool IsX86_MMXType(llvm::Type *IRType) {
732 // 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 +0000733 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
734 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
735 IRType->getScalarSizeInBits() != 64;
736}
737
Jay Foad7c57be32011-07-11 09:56:20 +0000738static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000739 StringRef Constraint,
Jay Foad7c57be32011-07-11 09:56:20 +0000740 llvm::Type* Ty) {
Tim Northover0ae93912013-06-07 00:04:50 +0000741 if ((Constraint == "y" || Constraint == "&y") && Ty->isVectorTy()) {
742 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
743 // Invalid MMX constraint
Craig Topper8a13c412014-05-21 05:09:00 +0000744 return nullptr;
Tim Northover0ae93912013-06-07 00:04:50 +0000745 }
746
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000747 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
Tim Northover0ae93912013-06-07 00:04:50 +0000748 }
749
750 // No operation needed
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000751 return Ty;
752}
753
Reid Kleckner80944df2014-10-31 22:00:51 +0000754/// Returns true if this type can be passed in SSE registers with the
755/// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
756static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
757 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
758 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half)
759 return true;
760 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
761 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
762 // registers specially.
763 unsigned VecSize = Context.getTypeSize(VT);
764 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
765 return true;
766 }
767 return false;
768}
769
770/// Returns true if this aggregate is small enough to be passed in SSE registers
771/// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
772static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
773 return NumMembers <= 4;
774}
775
Chris Lattner0cf24192010-06-28 20:05:43 +0000776//===----------------------------------------------------------------------===//
777// X86-32 ABI Implementation
778//===----------------------------------------------------------------------===//
Michael J. Spencerb2f376b2010-08-25 18:17:27 +0000779
Reid Kleckner661f35b2014-01-18 01:12:41 +0000780/// \brief Similar to llvm::CCState, but for Clang.
781struct CCState {
Reid Kleckner80944df2014-10-31 22:00:51 +0000782 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
Reid Kleckner661f35b2014-01-18 01:12:41 +0000783
784 unsigned CC;
785 unsigned FreeRegs;
Reid Kleckner80944df2014-10-31 22:00:51 +0000786 unsigned FreeSSERegs;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000787};
788
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000789/// X86_32ABIInfo - The X86-32 ABI information.
790class X86_32ABIInfo : public ABIInfo {
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000791 enum Class {
792 Integer,
793 Float
794 };
795
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000796 static const unsigned MinABIStackAlignInBytes = 4;
797
David Chisnallde3a0692009-08-17 23:08:21 +0000798 bool IsDarwinVectorABI;
Michael Kupersteindc745202015-10-19 07:52:25 +0000799 bool IsRetSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000800 bool IsWin32StructABI;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000801 bool IsSoftFloatABI;
Michael Kuperstein68901882015-10-25 08:18:20 +0000802 bool IsMCUABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000803 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000804
805 static bool isRegisterSize(unsigned Size) {
806 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
807 }
808
Reid Kleckner80944df2014-10-31 22:00:51 +0000809 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
810 // FIXME: Assumes vectorcall is in use.
811 return isX86VectorTypeForVectorCall(getContext(), Ty);
812 }
813
814 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
815 uint64_t NumMembers) const override {
816 // FIXME: Assumes vectorcall is in use.
817 return isX86VectorCallAggregateSmallEnough(NumMembers);
818 }
819
Reid Kleckner40ca9132014-05-13 22:05:45 +0000820 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000821
Daniel Dunbar557893d2010-04-21 19:10:51 +0000822 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
823 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000824 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
825
John McCall7f416cc2015-09-08 08:05:57 +0000826 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000827
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000828 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000829 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000830
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000831 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000832 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000833 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
834 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000835
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000836 /// \brief Rewrite the function info so that all memory arguments use
837 /// inalloca.
838 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
839
840 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000841 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000842 QualType Type) const;
843
Rafael Espindola75419dc2012-07-23 23:30:29 +0000844public:
845
Craig Topper4f12f102014-03-12 06:41:41 +0000846 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000847 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
848 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000849
Michael Kupersteindc745202015-10-19 07:52:25 +0000850 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
851 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000852 unsigned NumRegisterParameters, bool SoftFloatABI)
Michael Kupersteindc745202015-10-19 07:52:25 +0000853 : ABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
854 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
855 IsWin32StructABI(Win32StructABI),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000856 IsSoftFloatABI(SoftFloatABI),
Michael Kupersteind749f232015-10-27 07:46:22 +0000857 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
Manuel Klimekab2e28e2015-10-19 08:43:46 +0000858 DefaultNumRegisterParameters(NumRegisterParameters) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000859};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000860
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000861class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
862public:
Michael Kupersteindc745202015-10-19 07:52:25 +0000863 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
864 bool RetSmallStructInRegABI, bool Win32StructABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +0000865 unsigned NumRegisterParameters, bool SoftFloatABI)
866 : TargetCodeGenInfo(new X86_32ABIInfo(
867 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
868 NumRegisterParameters, SoftFloatABI)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000869
John McCall1fe2a8c2013-06-18 02:46:29 +0000870 static bool isStructReturnInRegABI(
871 const llvm::Triple &Triple, const CodeGenOptions &Opts);
872
Eric Christopher162c91c2015-06-05 22:03:00 +0000873 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000874 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000875
Craig Topper4f12f102014-03-12 06:41:41 +0000876 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000877 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000878 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000879 return 4;
880 }
881
882 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000883 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000884
Jay Foad7c57be32011-07-11 09:56:20 +0000885 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000886 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000887 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000888 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
889 }
890
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000891 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
892 std::string &Constraints,
893 std::vector<llvm::Type *> &ResultRegTypes,
894 std::vector<llvm::Type *> &ResultTruncRegTypes,
895 std::vector<LValue> &ResultRegDests,
896 std::string &AsmString,
897 unsigned NumOutputs) const override;
898
Craig Topper4f12f102014-03-12 06:41:41 +0000899 llvm::Constant *
900 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000901 unsigned Sig = (0xeb << 0) | // jmp rel8
902 (0x06 << 8) | // .+0x08
903 ('F' << 16) |
904 ('T' << 24);
905 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
906 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000907};
908
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000909}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000910
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000911/// Rewrite input constraint references after adding some output constraints.
912/// In the case where there is one output and one input and we add one output,
913/// we need to replace all operand references greater than or equal to 1:
914/// mov $0, $1
915/// mov eax, $1
916/// The result will be:
917/// mov $0, $2
918/// mov eax, $2
919static void rewriteInputConstraintReferences(unsigned FirstIn,
920 unsigned NumNewOuts,
921 std::string &AsmString) {
922 std::string Buf;
923 llvm::raw_string_ostream OS(Buf);
924 size_t Pos = 0;
925 while (Pos < AsmString.size()) {
926 size_t DollarStart = AsmString.find('$', Pos);
927 if (DollarStart == std::string::npos)
928 DollarStart = AsmString.size();
929 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
930 if (DollarEnd == std::string::npos)
931 DollarEnd = AsmString.size();
932 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
933 Pos = DollarEnd;
934 size_t NumDollars = DollarEnd - DollarStart;
935 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
936 // We have an operand reference.
937 size_t DigitStart = Pos;
938 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
939 if (DigitEnd == std::string::npos)
940 DigitEnd = AsmString.size();
941 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
942 unsigned OperandIndex;
943 if (!OperandStr.getAsInteger(10, OperandIndex)) {
944 if (OperandIndex >= FirstIn)
945 OperandIndex += NumNewOuts;
946 OS << OperandIndex;
947 } else {
948 OS << OperandStr;
949 }
950 Pos = DigitEnd;
951 }
952 }
953 AsmString = std::move(OS.str());
954}
955
956/// Add output constraints for EAX:EDX because they are return registers.
957void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
958 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
959 std::vector<llvm::Type *> &ResultRegTypes,
960 std::vector<llvm::Type *> &ResultTruncRegTypes,
961 std::vector<LValue> &ResultRegDests, std::string &AsmString,
962 unsigned NumOutputs) const {
963 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
964
965 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
966 // larger.
967 if (!Constraints.empty())
968 Constraints += ',';
969 if (RetWidth <= 32) {
970 Constraints += "={eax}";
971 ResultRegTypes.push_back(CGF.Int32Ty);
972 } else {
973 // Use the 'A' constraint for EAX:EDX.
974 Constraints += "=A";
975 ResultRegTypes.push_back(CGF.Int64Ty);
976 }
977
978 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
979 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
980 ResultTruncRegTypes.push_back(CoerceTy);
981
982 // Coerce the integer by bitcasting the return slot pointer.
983 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
984 CoerceTy->getPointerTo()));
985 ResultRegDests.push_back(ReturnSlot);
986
987 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
988}
989
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000990/// shouldReturnTypeInRegister - Determine if the given type should be
Michael Kuperstein68901882015-10-25 08:18:20 +0000991/// returned in a register (for the Darwin and MCU ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000992bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
993 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000994 uint64_t Size = Context.getTypeSize(Ty);
995
996 // Type must be register sized.
997 if (!isRegisterSize(Size))
998 return false;
999
1000 if (Ty->isVectorType()) {
1001 // 64- and 128- bit vectors inside structures are not returned in
1002 // registers.
1003 if (Size == 64 || Size == 128)
1004 return false;
1005
1006 return true;
1007 }
1008
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001009 // If this is a builtin, pointer, enum, complex type, member pointer, or
1010 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001011 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001012 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001013 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001014 return true;
1015
1016 // Arrays are treated like records.
1017 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001018 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001019
1020 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001021 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001022 if (!RT) return false;
1023
Anders Carlsson40446e82010-01-27 03:25:19 +00001024 // FIXME: Traverse bases here too.
1025
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001026 // Structure types are passed in register if all fields would be
1027 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001028 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001029 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001030 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001031 continue;
1032
1033 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001034 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001035 return false;
1036 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001037 return true;
1038}
1039
John McCall7f416cc2015-09-08 08:05:57 +00001040ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001041 // If the return value is indirect, then the hidden argument is consuming one
1042 // integer register.
1043 if (State.FreeRegs) {
1044 --State.FreeRegs;
John McCall7f416cc2015-09-08 08:05:57 +00001045 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001046 }
John McCall7f416cc2015-09-08 08:05:57 +00001047 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001048}
1049
Eric Christopher7565e0d2015-05-29 23:09:49 +00001050ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1051 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001052 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001053 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001054
Reid Kleckner80944df2014-10-31 22:00:51 +00001055 const Type *Base = nullptr;
1056 uint64_t NumElts = 0;
1057 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1058 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1059 // The LLVM struct type for such an aggregate should lower properly.
1060 return ABIArgInfo::getDirect();
1061 }
1062
Chris Lattner458b2aa2010-07-29 02:16:43 +00001063 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001064 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001065 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001066 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001067
1068 // 128-bit vectors are a special case; they are returned in
1069 // registers and we need to make sure to pick a type the LLVM
1070 // backend will like.
1071 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001072 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001073 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001074
1075 // Always return in register if it fits in a general purpose
1076 // register, or if it is 64 bits and has a single element.
1077 if ((Size == 8 || Size == 16 || Size == 32) ||
1078 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001079 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001080 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001081
John McCall7f416cc2015-09-08 08:05:57 +00001082 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001083 }
1084
1085 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001086 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001087
John McCalla1dee5302010-08-22 10:59:02 +00001088 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001089 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001090 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001091 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001092 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001093 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001094
David Chisnallde3a0692009-08-17 23:08:21 +00001095 // If specified, structs and unions are always indirect.
Michael Kupersteindc745202015-10-19 07:52:25 +00001096 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001097 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001098
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001099 // Small structures which are register sized are generally returned
1100 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001101 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001102 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001103
1104 // As a special-case, if the struct is a "single-element" struct, and
1105 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001106 // floating-point register. (MSVC does not apply this special case.)
1107 // We apply a similar transformation for pointer types to improve the
1108 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001109 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001110 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001111 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001112 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1113
1114 // FIXME: We should be able to narrow this integer in cases with dead
1115 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001116 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001117 }
1118
John McCall7f416cc2015-09-08 08:05:57 +00001119 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001120 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001121
Chris Lattner458b2aa2010-07-29 02:16:43 +00001122 // Treat an enum type as its underlying type.
1123 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1124 RetTy = EnumTy->getDecl()->getIntegerType();
1125
1126 return (RetTy->isPromotableIntegerType() ?
1127 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001128}
1129
Eli Friedman7919bea2012-06-05 19:40:46 +00001130static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1131 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1132}
1133
Daniel Dunbared23de32010-09-16 20:42:00 +00001134static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1135 const RecordType *RT = Ty->getAs<RecordType>();
1136 if (!RT)
1137 return 0;
1138 const RecordDecl *RD = RT->getDecl();
1139
1140 // If this is a C++ record, check the bases first.
1141 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001142 for (const auto &I : CXXRD->bases())
1143 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001144 return false;
1145
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001146 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001147 QualType FT = i->getType();
1148
Eli Friedman7919bea2012-06-05 19:40:46 +00001149 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001150 return true;
1151
1152 if (isRecordWithSSEVectorType(Context, FT))
1153 return true;
1154 }
1155
1156 return false;
1157}
1158
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001159unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1160 unsigned Align) const {
1161 // Otherwise, if the alignment is less than or equal to the minimum ABI
1162 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001163 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001164 return 0; // Use default alignment.
1165
1166 // On non-Darwin, the stack type alignment is always 4.
1167 if (!IsDarwinVectorABI) {
1168 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001169 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001170 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001171
Daniel Dunbared23de32010-09-16 20:42:00 +00001172 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001173 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1174 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001175 return 16;
1176
1177 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001178}
1179
Rafael Espindola703c47f2012-10-19 05:04:37 +00001180ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001181 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001182 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001183 if (State.FreeRegs) {
1184 --State.FreeRegs; // Non-byval indirects just use one pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001185 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001186 }
John McCall7f416cc2015-09-08 08:05:57 +00001187 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001188 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001189
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001190 // Compute the byval alignment.
1191 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1192 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1193 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001194 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001195
1196 // If the stack alignment is less than the type alignment, realign the
1197 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001198 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001199 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1200 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001201}
1202
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001203X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1204 const Type *T = isSingleElementStruct(Ty, getContext());
1205 if (!T)
1206 T = Ty.getTypePtr();
1207
1208 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1209 BuiltinType::Kind K = BT->getKind();
1210 if (K == BuiltinType::Float || K == BuiltinType::Double)
1211 return Float;
1212 }
1213 return Integer;
1214}
1215
Reid Kleckner661f35b2014-01-18 01:12:41 +00001216bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
1217 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +00001218 NeedsPadding = false;
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001219 if (!IsSoftFloatABI) {
1220 Class C = classify(Ty);
1221 if (C == Float)
1222 return false;
1223 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001224
Rafael Espindola077dd592012-10-24 01:58:58 +00001225 unsigned Size = getContext().getTypeSize(Ty);
1226 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001227
1228 if (SizeInRegs == 0)
1229 return false;
1230
Michael Kuperstein68901882015-10-25 08:18:20 +00001231 if (!IsMCUABI) {
1232 if (SizeInRegs > State.FreeRegs) {
1233 State.FreeRegs = 0;
1234 return false;
1235 }
1236 } else {
1237 // The MCU psABI allows passing parameters in-reg even if there are
1238 // earlier parameters that are passed on the stack. Also,
1239 // it does not allow passing >8-byte structs in-register,
1240 // even if there are 3 free registers available.
1241 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1242 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001243 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001244
Reid Kleckner661f35b2014-01-18 01:12:41 +00001245 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001246
Reid Kleckner80944df2014-10-31 22:00:51 +00001247 if (State.CC == llvm::CallingConv::X86_FastCall ||
1248 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001249 if (Size > 32)
1250 return false;
1251
1252 if (Ty->isIntegralOrEnumerationType())
1253 return true;
1254
1255 if (Ty->isPointerType())
1256 return true;
1257
1258 if (Ty->isReferenceType())
1259 return true;
1260
Reid Kleckner661f35b2014-01-18 01:12:41 +00001261 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001262 NeedsPadding = true;
1263
Rafael Espindola077dd592012-10-24 01:58:58 +00001264 return false;
1265 }
1266
Rafael Espindola703c47f2012-10-19 05:04:37 +00001267 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001268}
1269
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001270ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1271 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001272 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001273
Reid Klecknerb1be6832014-11-15 01:41:41 +00001274 Ty = useFirstFieldIfTransparentUnion(Ty);
1275
Reid Kleckner80944df2014-10-31 22:00:51 +00001276 // Check with the C++ ABI first.
1277 const RecordType *RT = Ty->getAs<RecordType>();
1278 if (RT) {
1279 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1280 if (RAA == CGCXXABI::RAA_Indirect) {
1281 return getIndirectResult(Ty, false, State);
1282 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1283 // The field index doesn't matter, we'll fix it up later.
1284 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1285 }
1286 }
1287
1288 // vectorcall adds the concept of a homogenous vector aggregate, similar
1289 // to other targets.
1290 const Type *Base = nullptr;
1291 uint64_t NumElts = 0;
1292 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1293 isHomogeneousAggregate(Ty, Base, NumElts)) {
1294 if (State.FreeSSERegs >= NumElts) {
1295 State.FreeSSERegs -= NumElts;
1296 if (Ty->isBuiltinType() || Ty->isVectorType())
1297 return ABIArgInfo::getDirect();
1298 return ABIArgInfo::getExpand();
1299 }
1300 return getIndirectResult(Ty, /*ByVal=*/false, State);
1301 }
1302
1303 if (isAggregateTypeForABI(Ty)) {
1304 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001305 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001306 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001307 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001308
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001309 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001310 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001311 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001312 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001313
Eli Friedman9f061a32011-11-18 00:28:11 +00001314 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001315 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001316 return ABIArgInfo::getIgnore();
1317
Rafael Espindolafad28de2012-10-24 01:59:00 +00001318 llvm::LLVMContext &LLVMContext = getVMContext();
1319 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1320 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001321 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001322 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001323 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001324 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1325 return ABIArgInfo::getDirectInReg(Result);
1326 }
Craig Topper8a13c412014-05-21 05:09:00 +00001327 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001328
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001329 // Expand small (<= 128-bit) record types when we know that the stack layout
1330 // of those arguments will match the struct. This is important because the
1331 // LLVM backend isn't smart enough to remove byval, which inhibits many
1332 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001333 if (getContext().getTypeSize(Ty) <= 4*32 &&
1334 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001335 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001336 State.CC == llvm::CallingConv::X86_FastCall ||
1337 State.CC == llvm::CallingConv::X86_VectorCall,
1338 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001339
Reid Kleckner661f35b2014-01-18 01:12:41 +00001340 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001341 }
1342
Chris Lattnerd774ae92010-08-26 20:05:13 +00001343 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001344 // On Darwin, some vectors are passed in memory, we handle this by passing
1345 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001346 if (IsDarwinVectorABI) {
1347 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001348 if ((Size == 8 || Size == 16 || Size == 32) ||
1349 (Size == 64 && VT->getNumElements() == 1))
1350 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1351 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001352 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001353
Chad Rosier651c1832013-03-25 21:00:27 +00001354 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1355 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001356
Chris Lattnerd774ae92010-08-26 20:05:13 +00001357 return ABIArgInfo::getDirect();
1358 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001359
1360
Chris Lattner458b2aa2010-07-29 02:16:43 +00001361 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1362 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001363
Rafael Espindolafad28de2012-10-24 01:59:00 +00001364 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001365 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001366
1367 if (Ty->isPromotableIntegerType()) {
1368 if (InReg)
1369 return ABIArgInfo::getExtendInReg();
1370 return ABIArgInfo::getExtend();
1371 }
1372 if (InReg)
1373 return ABIArgInfo::getDirectInReg();
1374 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001375}
1376
Rafael Espindolaa6472962012-07-24 00:01:07 +00001377void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001378 CCState State(FI.getCallingConvention());
1379 if (State.CC == llvm::CallingConv::X86_FastCall)
1380 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001381 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1382 State.FreeRegs = 2;
1383 State.FreeSSERegs = 6;
1384 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001385 State.FreeRegs = FI.getRegParm();
Michael Kuperstein68901882015-10-25 08:18:20 +00001386 else if (IsMCUABI)
1387 State.FreeRegs = 3;
Rafael Espindola077dd592012-10-24 01:58:58 +00001388 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001389 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001390
Reid Kleckner677539d2014-07-10 01:58:55 +00001391 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001392 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001393 } else if (FI.getReturnInfo().isIndirect()) {
1394 // The C++ ABI is not aware of register usage, so we have to check if the
1395 // return value was sret and put it in a register ourselves if appropriate.
1396 if (State.FreeRegs) {
1397 --State.FreeRegs; // The sret parameter consumes a register.
1398 FI.getReturnInfo().setInReg(true);
1399 }
1400 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001401
Peter Collingbournef7706832014-12-12 23:41:25 +00001402 // The chain argument effectively gives us another free register.
1403 if (FI.isChainCall())
1404 ++State.FreeRegs;
1405
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001406 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001407 for (auto &I : FI.arguments()) {
1408 I.info = classifyArgumentType(I.type, State);
1409 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001410 }
1411
1412 // If we needed to use inalloca for any argument, do a second pass and rewrite
1413 // all the memory arguments to use inalloca.
1414 if (UsedInAlloca)
1415 rewriteWithInAlloca(FI);
1416}
1417
1418void
1419X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001420 CharUnits &StackOffset, ABIArgInfo &Info,
1421 QualType Type) const {
1422 // Arguments are always 4-byte-aligned.
1423 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1424
1425 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001426 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1427 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001428 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001429
John McCall7f416cc2015-09-08 08:05:57 +00001430 // Insert padding bytes to respect alignment.
1431 CharUnits FieldEnd = StackOffset;
1432 StackOffset = FieldEnd.RoundUpToAlignment(FieldAlign);
1433 if (StackOffset != FieldEnd) {
1434 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001435 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001436 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001437 FrameFields.push_back(Ty);
1438 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001439}
1440
Reid Kleckner852361d2014-07-26 00:12:26 +00001441static bool isArgInAlloca(const ABIArgInfo &Info) {
1442 // Leave ignored and inreg arguments alone.
1443 switch (Info.getKind()) {
1444 case ABIArgInfo::InAlloca:
1445 return true;
1446 case ABIArgInfo::Indirect:
1447 assert(Info.getIndirectByVal());
1448 return true;
1449 case ABIArgInfo::Ignore:
1450 return false;
1451 case ABIArgInfo::Direct:
1452 case ABIArgInfo::Extend:
1453 case ABIArgInfo::Expand:
1454 if (Info.getInReg())
1455 return false;
1456 return true;
1457 }
1458 llvm_unreachable("invalid enum");
1459}
1460
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001461void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1462 assert(IsWin32StructABI && "inalloca only supported on win32");
1463
1464 // Build a packed struct type for all of the arguments in memory.
1465 SmallVector<llvm::Type *, 6> FrameFields;
1466
John McCall7f416cc2015-09-08 08:05:57 +00001467 // The stack alignment is always 4.
1468 CharUnits StackAlign = CharUnits::fromQuantity(4);
1469
1470 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001471 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1472
1473 // Put 'this' into the struct before 'sret', if necessary.
1474 bool IsThisCall =
1475 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1476 ABIArgInfo &Ret = FI.getReturnInfo();
1477 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1478 isArgInAlloca(I->info)) {
1479 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1480 ++I;
1481 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001482
1483 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001484 if (Ret.isIndirect() && !Ret.getInReg()) {
1485 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1486 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001487 // On Windows, the hidden sret parameter is always returned in eax.
1488 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001489 }
1490
1491 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001492 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001493 ++I;
1494
1495 // Put arguments passed in memory into the struct.
1496 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001497 if (isArgInAlloca(I->info))
1498 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001499 }
1500
1501 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001502 /*isPacked=*/true),
1503 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001504}
1505
John McCall7f416cc2015-09-08 08:05:57 +00001506Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1507 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001508
John McCall7f416cc2015-09-08 08:05:57 +00001509 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001510
John McCall7f416cc2015-09-08 08:05:57 +00001511 // x86-32 changes the alignment of certain arguments on the stack.
1512 //
1513 // Just messing with TypeInfo like this works because we never pass
1514 // anything indirectly.
1515 TypeInfo.second = CharUnits::fromQuantity(
1516 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001517
John McCall7f416cc2015-09-08 08:05:57 +00001518 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1519 TypeInfo, CharUnits::fromQuantity(4),
1520 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001521}
1522
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001523bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1524 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1525 assert(Triple.getArch() == llvm::Triple::x86);
1526
1527 switch (Opts.getStructReturnConvention()) {
1528 case CodeGenOptions::SRCK_Default:
1529 break;
1530 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1531 return false;
1532 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1533 return true;
1534 }
1535
Michael Kupersteind749f232015-10-27 07:46:22 +00001536 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001537 return true;
1538
1539 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001540 case llvm::Triple::DragonFly:
1541 case llvm::Triple::FreeBSD:
1542 case llvm::Triple::OpenBSD:
1543 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001544 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001545 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001546 default:
1547 return false;
1548 }
1549}
1550
Eric Christopher162c91c2015-06-05 22:03:00 +00001551void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001552 llvm::GlobalValue *GV,
1553 CodeGen::CodeGenModule &CGM) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001554 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Charles Davis4ea31ab2010-02-13 15:54:06 +00001555 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1556 // Get the LLVM function.
1557 llvm::Function *Fn = cast<llvm::Function>(GV);
1558
1559 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001560 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001561 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001562 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1563 llvm::AttributeSet::get(CGM.getLLVMContext(),
1564 llvm::AttributeSet::FunctionIndex,
1565 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001566 }
1567 }
1568}
1569
John McCallbeec5a02010-03-06 00:35:14 +00001570bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1571 CodeGen::CodeGenFunction &CGF,
1572 llvm::Value *Address) const {
1573 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001574
Chris Lattnerece04092012-02-07 00:39:47 +00001575 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001576
John McCallbeec5a02010-03-06 00:35:14 +00001577 // 0-7 are the eight integer registers; the order is different
1578 // on Darwin (for EH), but the range is the same.
1579 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001580 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001581
John McCallc8e01702013-04-16 22:48:15 +00001582 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001583 // 12-16 are st(0..4). Not sure why we stop at 4.
1584 // These have size 16, which is sizeof(long double) on
1585 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001586 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001587 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001588
John McCallbeec5a02010-03-06 00:35:14 +00001589 } else {
1590 // 9 is %eflags, which doesn't get a size on Darwin for some
1591 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001592 Builder.CreateAlignedStore(
1593 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1594 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001595
1596 // 11-16 are st(0..5). Not sure why we stop at 5.
1597 // These have size 12, which is sizeof(long double) on
1598 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001599 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001600 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1601 }
John McCallbeec5a02010-03-06 00:35:14 +00001602
1603 return false;
1604}
1605
Chris Lattner0cf24192010-06-28 20:05:43 +00001606//===----------------------------------------------------------------------===//
1607// X86-64 ABI Implementation
1608//===----------------------------------------------------------------------===//
1609
1610
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001611namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001612/// The AVX ABI level for X86 targets.
1613enum class X86AVXABILevel {
1614 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001615 AVX,
1616 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001617};
1618
1619/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1620static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1621 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001622 case X86AVXABILevel::AVX512:
1623 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001624 case X86AVXABILevel::AVX:
1625 return 256;
1626 case X86AVXABILevel::None:
1627 return 128;
1628 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001629 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001630}
1631
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001632/// X86_64ABIInfo - The X86_64 ABI information.
1633class X86_64ABIInfo : public ABIInfo {
1634 enum Class {
1635 Integer = 0,
1636 SSE,
1637 SSEUp,
1638 X87,
1639 X87Up,
1640 ComplexX87,
1641 NoClass,
1642 Memory
1643 };
1644
1645 /// merge - Implement the X86_64 ABI merging algorithm.
1646 ///
1647 /// Merge an accumulating classification \arg Accum with a field
1648 /// classification \arg Field.
1649 ///
1650 /// \param Accum - The accumulating classification. This should
1651 /// always be either NoClass or the result of a previous merge
1652 /// call. In addition, this should never be Memory (the caller
1653 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001654 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001655
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001656 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1657 ///
1658 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1659 /// final MEMORY or SSE classes when necessary.
1660 ///
1661 /// \param AggregateSize - The size of the current aggregate in
1662 /// the classification process.
1663 ///
1664 /// \param Lo - The classification for the parts of the type
1665 /// residing in the low word of the containing object.
1666 ///
1667 /// \param Hi - The classification for the parts of the type
1668 /// residing in the higher words of the containing object.
1669 ///
1670 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1671
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001672 /// classify - Determine the x86_64 register classes in which the
1673 /// given type T should be passed.
1674 ///
1675 /// \param Lo - The classification for the parts of the type
1676 /// residing in the low word of the containing object.
1677 ///
1678 /// \param Hi - The classification for the parts of the type
1679 /// residing in the high word of the containing object.
1680 ///
1681 /// \param OffsetBase - The bit offset of this type in the
1682 /// containing object. Some parameters are classified different
1683 /// depending on whether they straddle an eightbyte boundary.
1684 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001685 /// \param isNamedArg - Whether the argument in question is a "named"
1686 /// argument, as used in AMD64-ABI 3.5.7.
1687 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001688 /// If a word is unused its result will be NoClass; if a type should
1689 /// be passed in Memory then at least the classification of \arg Lo
1690 /// will be Memory.
1691 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001692 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001693 ///
1694 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1695 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001696 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1697 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001698
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001699 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001700 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1701 unsigned IROffset, QualType SourceTy,
1702 unsigned SourceOffset) const;
1703 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1704 unsigned IROffset, QualType SourceTy,
1705 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001706
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001707 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001708 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001709 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001710
1711 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001712 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001713 ///
1714 /// \param freeIntRegs - The number of free integer registers remaining
1715 /// available.
1716 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001717
Chris Lattner458b2aa2010-07-29 02:16:43 +00001718 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001719
Bill Wendling5cd41c42010-10-18 03:41:31 +00001720 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001721 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001722 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001723 unsigned &neededSSE,
1724 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001725
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001726 bool IsIllegalVectorType(QualType Ty) const;
1727
John McCalle0fda732011-04-21 01:20:55 +00001728 /// The 0.98 ABI revision clarified a lot of ambiguities,
1729 /// unfortunately in ways that were not always consistent with
1730 /// certain previous compilers. In particular, platforms which
1731 /// required strict binary compatibility with older versions of GCC
1732 /// may need to exempt themselves.
1733 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001734 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001735 }
1736
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001737 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001738 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1739 // 64-bit hardware.
1740 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001741
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001742public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001743 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1744 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001745 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001746 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001747
John McCalla729c622012-02-17 03:33:10 +00001748 bool isPassedUsingAVXType(QualType type) const {
1749 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001750 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001751 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1752 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001753 if (info.isDirect()) {
1754 llvm::Type *ty = info.getCoerceToType();
1755 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1756 return (vectorTy->getBitWidth() > 128);
1757 }
1758 return false;
1759 }
1760
Craig Topper4f12f102014-03-12 06:41:41 +00001761 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001762
John McCall7f416cc2015-09-08 08:05:57 +00001763 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1764 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001765 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1766 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001767
1768 bool has64BitPointers() const {
1769 return Has64BitPointers;
1770 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001771};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001772
Chris Lattner04dc9572010-08-31 16:44:54 +00001773/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001774class WinX86_64ABIInfo : public ABIInfo {
Chris Lattner04dc9572010-08-31 16:44:54 +00001775public:
Reid Kleckner11a17192015-10-28 22:29:52 +00001776 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
1777 : ABIInfo(CGT),
1778 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001779
Craig Topper4f12f102014-03-12 06:41:41 +00001780 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001781
John McCall7f416cc2015-09-08 08:05:57 +00001782 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1783 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001784
1785 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1786 // FIXME: Assumes vectorcall is in use.
1787 return isX86VectorTypeForVectorCall(getContext(), Ty);
1788 }
1789
1790 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1791 uint64_t NumMembers) const override {
1792 // FIXME: Assumes vectorcall is in use.
1793 return isX86VectorCallAggregateSmallEnough(NumMembers);
1794 }
Reid Kleckner11a17192015-10-28 22:29:52 +00001795
1796private:
1797 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1798 bool IsReturnType) const;
1799
1800 bool IsMingw64;
Chris Lattner04dc9572010-08-31 16:44:54 +00001801};
1802
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001803class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1804public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001805 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001806 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001807
John McCalla729c622012-02-17 03:33:10 +00001808 const X86_64ABIInfo &getABIInfo() const {
1809 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1810 }
1811
Craig Topper4f12f102014-03-12 06:41:41 +00001812 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001813 return 7;
1814 }
1815
1816 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001817 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001818 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001819
John McCall943fae92010-05-27 06:19:26 +00001820 // 0-15 are the 16 integer registers.
1821 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001822 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001823 return false;
1824 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001825
Jay Foad7c57be32011-07-11 09:56:20 +00001826 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001827 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001828 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001829 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1830 }
1831
John McCalla729c622012-02-17 03:33:10 +00001832 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001833 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001834 // The default CC on x86-64 sets %al to the number of SSA
1835 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001836 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001837 // that when AVX types are involved: the ABI explicitly states it is
1838 // undefined, and it doesn't work in practice because of how the ABI
1839 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001840 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001841 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001842 for (CallArgList::const_iterator
1843 it = args.begin(), ie = args.end(); it != ie; ++it) {
1844 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1845 HasAVXType = true;
1846 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001847 }
1848 }
John McCalla729c622012-02-17 03:33:10 +00001849
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001850 if (!HasAVXType)
1851 return true;
1852 }
John McCallcbc038a2011-09-21 08:08:30 +00001853
John McCalla729c622012-02-17 03:33:10 +00001854 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001855 }
1856
Craig Topper4f12f102014-03-12 06:41:41 +00001857 llvm::Constant *
1858 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001859 unsigned Sig;
1860 if (getABIInfo().has64BitPointers())
1861 Sig = (0xeb << 0) | // jmp rel8
1862 (0x0a << 8) | // .+0x0c
1863 ('F' << 16) |
1864 ('T' << 24);
1865 else
1866 Sig = (0xeb << 0) | // jmp rel8
1867 (0x06 << 8) | // .+0x08
1868 ('F' << 16) |
1869 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001870 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1871 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001872};
1873
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001874class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1875public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001876 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1877 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001878
1879 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001880 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001881 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001882 // If the argument contains a space, enclose it in quotes.
1883 if (Lib.find(" ") != StringRef::npos)
1884 Opt += "\"" + Lib.str() + "\"";
1885 else
1886 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001887 }
1888};
1889
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001890static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001891 // If the argument does not end in .lib, automatically add the suffix.
1892 // If the argument contains a space, enclose it in quotes.
1893 // This matches the behavior of MSVC.
1894 bool Quote = (Lib.find(" ") != StringRef::npos);
1895 std::string ArgStr = Quote ? "\"" : "";
1896 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001897 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001898 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001899 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001900 return ArgStr;
1901}
1902
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001903class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1904public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001905 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Michael Kupersteindc745202015-10-19 07:52:25 +00001906 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
1907 unsigned NumRegisterParameters)
1908 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00001909 Win32StructABI, NumRegisterParameters, false) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001910
Eric Christopher162c91c2015-06-05 22:03:00 +00001911 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001912 CodeGen::CodeGenModule &CGM) const override;
1913
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001914 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001915 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001916 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001917 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001918 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001919
1920 void getDetectMismatchOption(llvm::StringRef Name,
1921 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001922 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001923 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001924 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001925};
1926
Hans Wennborg77dc2362015-01-20 19:45:50 +00001927static void addStackProbeSizeTargetAttribute(const Decl *D,
1928 llvm::GlobalValue *GV,
1929 CodeGen::CodeGenModule &CGM) {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00001930 if (D && isa<FunctionDecl>(D)) {
Hans Wennborg77dc2362015-01-20 19:45:50 +00001931 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1932 llvm::Function *Fn = cast<llvm::Function>(GV);
1933
Eric Christopher7565e0d2015-05-29 23:09:49 +00001934 Fn->addFnAttr("stack-probe-size",
1935 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001936 }
1937 }
1938}
1939
Eric Christopher162c91c2015-06-05 22:03:00 +00001940void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001941 llvm::GlobalValue *GV,
1942 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001943 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001944
1945 addStackProbeSizeTargetAttribute(D, GV, CGM);
1946}
1947
Chris Lattner04dc9572010-08-31 16:44:54 +00001948class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1949public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001950 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1951 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001952 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001953
Eric Christopher162c91c2015-06-05 22:03:00 +00001954 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001955 CodeGen::CodeGenModule &CGM) const override;
1956
Craig Topper4f12f102014-03-12 06:41:41 +00001957 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001958 return 7;
1959 }
1960
1961 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001962 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001963 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001964
Chris Lattner04dc9572010-08-31 16:44:54 +00001965 // 0-15 are the 16 integer registers.
1966 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001967 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001968 return false;
1969 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001970
1971 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001972 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001973 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001974 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001975 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001976
1977 void getDetectMismatchOption(llvm::StringRef Name,
1978 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001979 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001980 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001981 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001982};
1983
Eric Christopher162c91c2015-06-05 22:03:00 +00001984void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001985 llvm::GlobalValue *GV,
1986 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001987 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001988
1989 addStackProbeSizeTargetAttribute(D, GV, CGM);
1990}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001991}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001992
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001993void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1994 Class &Hi) const {
1995 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1996 //
1997 // (a) If one of the classes is Memory, the whole argument is passed in
1998 // memory.
1999 //
2000 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2001 // memory.
2002 //
2003 // (c) If the size of the aggregate exceeds two eightbytes and the first
2004 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2005 // argument is passed in memory. NOTE: This is necessary to keep the
2006 // ABI working for processors that don't support the __m256 type.
2007 //
2008 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2009 //
2010 // Some of these are enforced by the merging logic. Others can arise
2011 // only with unions; for example:
2012 // union { _Complex double; unsigned; }
2013 //
2014 // Note that clauses (b) and (c) were added in 0.98.
2015 //
2016 if (Hi == Memory)
2017 Lo = Memory;
2018 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2019 Lo = Memory;
2020 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2021 Lo = Memory;
2022 if (Hi == SSEUp && Lo != SSE)
2023 Hi = SSE;
2024}
2025
Chris Lattnerd776fb12010-06-28 21:43:59 +00002026X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002027 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2028 // classified recursively so that always two fields are
2029 // considered. The resulting class is calculated according to
2030 // the classes of the fields in the eightbyte:
2031 //
2032 // (a) If both classes are equal, this is the resulting class.
2033 //
2034 // (b) If one of the classes is NO_CLASS, the resulting class is
2035 // the other class.
2036 //
2037 // (c) If one of the classes is MEMORY, the result is the MEMORY
2038 // class.
2039 //
2040 // (d) If one of the classes is INTEGER, the result is the
2041 // INTEGER.
2042 //
2043 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2044 // MEMORY is used as class.
2045 //
2046 // (f) Otherwise class SSE is used.
2047
2048 // Accum should never be memory (we should have returned) or
2049 // ComplexX87 (because this cannot be passed in a structure).
2050 assert((Accum != Memory && Accum != ComplexX87) &&
2051 "Invalid accumulated classification during merge.");
2052 if (Accum == Field || Field == NoClass)
2053 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002054 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002055 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002056 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002057 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002058 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002059 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002060 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2061 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002062 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002063 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002064}
2065
Chris Lattner5c740f12010-06-30 19:14:05 +00002066void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002067 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002068 // FIXME: This code can be simplified by introducing a simple value class for
2069 // Class pairs with appropriate constructor methods for the various
2070 // situations.
2071
2072 // FIXME: Some of the split computations are wrong; unaligned vectors
2073 // shouldn't be passed in registers for example, so there is no chance they
2074 // can straddle an eightbyte. Verify & simplify.
2075
2076 Lo = Hi = NoClass;
2077
2078 Class &Current = OffsetBase < 64 ? Lo : Hi;
2079 Current = Memory;
2080
John McCall9dd450b2009-09-21 23:43:11 +00002081 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002082 BuiltinType::Kind k = BT->getKind();
2083
2084 if (k == BuiltinType::Void) {
2085 Current = NoClass;
2086 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2087 Lo = Integer;
2088 Hi = Integer;
2089 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2090 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002091 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002092 Current = SSE;
2093 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002094 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2095 if (LDF == &llvm::APFloat::IEEEquad) {
2096 Lo = SSE;
2097 Hi = SSEUp;
2098 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2099 Lo = X87;
2100 Hi = X87Up;
2101 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2102 Current = SSE;
2103 } else
2104 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002105 }
2106 // FIXME: _Decimal32 and _Decimal64 are SSE.
2107 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002108 return;
2109 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002110
Chris Lattnerd776fb12010-06-28 21:43:59 +00002111 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002112 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002113 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002114 return;
2115 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002116
Chris Lattnerd776fb12010-06-28 21:43:59 +00002117 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002118 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002119 return;
2120 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002121
Chris Lattnerd776fb12010-06-28 21:43:59 +00002122 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002123 if (Ty->isMemberFunctionPointerType()) {
2124 if (Has64BitPointers) {
2125 // If Has64BitPointers, this is an {i64, i64}, so classify both
2126 // Lo and Hi now.
2127 Lo = Hi = Integer;
2128 } else {
2129 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2130 // straddles an eightbyte boundary, Hi should be classified as well.
2131 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2132 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2133 if (EB_FuncPtr != EB_ThisAdj) {
2134 Lo = Hi = Integer;
2135 } else {
2136 Current = Integer;
2137 }
2138 }
2139 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002140 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002141 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002142 return;
2143 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002144
Chris Lattnerd776fb12010-06-28 21:43:59 +00002145 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002146 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002147 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2148 // gcc passes the following as integer:
2149 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2150 // 2 bytes - <2 x char>, <1 x short>
2151 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002152 Current = Integer;
2153
2154 // If this type crosses an eightbyte boundary, it should be
2155 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002156 uint64_t EB_Lo = (OffsetBase) / 64;
2157 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2158 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002159 Hi = Lo;
2160 } else if (Size == 64) {
2161 // gcc passes <1 x double> in memory. :(
2162 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2163 return;
2164
2165 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002166 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002167 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2168 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2169 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002170 Current = Integer;
2171 else
2172 Current = SSE;
2173
2174 // If this type crosses an eightbyte boundary, it should be
2175 // split.
2176 if (OffsetBase && OffsetBase != 64)
2177 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002178 } else if (Size == 128 ||
2179 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002180 // Arguments of 256-bits are split into four eightbyte chunks. The
2181 // least significant one belongs to class SSE and all the others to class
2182 // SSEUP. The original Lo and Hi design considers that types can't be
2183 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2184 // This design isn't correct for 256-bits, but since there're no cases
2185 // where the upper parts would need to be inspected, avoid adding
2186 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002187 //
2188 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2189 // registers if they are "named", i.e. not part of the "..." of a
2190 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002191 //
2192 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2193 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002194 Lo = SSE;
2195 Hi = SSEUp;
2196 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002197 return;
2198 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002199
Chris Lattnerd776fb12010-06-28 21:43:59 +00002200 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002201 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002202
Chris Lattner2b037972010-07-29 02:01:43 +00002203 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002204 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002205 if (Size <= 64)
2206 Current = Integer;
2207 else if (Size <= 128)
2208 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002209 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002210 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002211 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002212 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002213 } else if (ET == getContext().LongDoubleTy) {
2214 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2215 if (LDF == &llvm::APFloat::IEEEquad)
2216 Current = Memory;
2217 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2218 Current = ComplexX87;
2219 else if (LDF == &llvm::APFloat::IEEEdouble)
2220 Lo = Hi = SSE;
2221 else
2222 llvm_unreachable("unexpected long double representation!");
2223 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002224
2225 // If this complex type crosses an eightbyte boundary then it
2226 // should be split.
2227 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002228 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002229 if (Hi == NoClass && EB_Real != EB_Imag)
2230 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002231
Chris Lattnerd776fb12010-06-28 21:43:59 +00002232 return;
2233 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002234
Chris Lattner2b037972010-07-29 02:01:43 +00002235 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002236 // Arrays are treated like structures.
2237
Chris Lattner2b037972010-07-29 02:01:43 +00002238 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002239
2240 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002241 // than four eightbytes, ..., it has class MEMORY.
2242 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002243 return;
2244
2245 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2246 // fields, it has class MEMORY.
2247 //
2248 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002249 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002250 return;
2251
2252 // Otherwise implement simplified merge. We could be smarter about
2253 // this, but it isn't worth it and would be harder to verify.
2254 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002255 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002256 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002257
2258 // The only case a 256-bit wide vector could be used is when the array
2259 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2260 // to work for sizes wider than 128, early check and fallback to memory.
2261 if (Size > 128 && EltSize != 256)
2262 return;
2263
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002264 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2265 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002266 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002267 Lo = merge(Lo, FieldLo);
2268 Hi = merge(Hi, FieldHi);
2269 if (Lo == Memory || Hi == Memory)
2270 break;
2271 }
2272
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002273 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002274 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002275 return;
2276 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002277
Chris Lattnerd776fb12010-06-28 21:43:59 +00002278 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002279 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002280
2281 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002282 // than four eightbytes, ..., it has class MEMORY.
2283 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002284 return;
2285
Anders Carlsson20759ad2009-09-16 15:53:40 +00002286 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2287 // copy constructor or a non-trivial destructor, it is passed by invisible
2288 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002289 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002290 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002291
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002292 const RecordDecl *RD = RT->getDecl();
2293
2294 // Assume variable sized types are passed in memory.
2295 if (RD->hasFlexibleArrayMember())
2296 return;
2297
Chris Lattner2b037972010-07-29 02:01:43 +00002298 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002299
2300 // Reset Lo class, this will be recomputed.
2301 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002302
2303 // If this is a C++ record, classify the bases first.
2304 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002305 for (const auto &I : CXXRD->bases()) {
2306 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002307 "Unexpected base class!");
2308 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002309 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002310
2311 // Classify this field.
2312 //
2313 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2314 // single eightbyte, each is classified separately. Each eightbyte gets
2315 // initialized to class NO_CLASS.
2316 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002317 uint64_t Offset =
2318 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002319 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002320 Lo = merge(Lo, FieldLo);
2321 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002322 if (Lo == Memory || Hi == Memory) {
2323 postMerge(Size, Lo, Hi);
2324 return;
2325 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002326 }
2327 }
2328
2329 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002330 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002331 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002332 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002333 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2334 bool BitField = i->isBitField();
2335
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002336 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2337 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002338 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002339 // The only case a 256-bit wide vector could be used is when the struct
2340 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2341 // to work for sizes wider than 128, early check and fallback to memory.
2342 //
2343 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2344 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002345 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002346 return;
2347 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002348 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002349 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002350 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002351 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002352 return;
2353 }
2354
2355 // Classify this field.
2356 //
2357 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2358 // exceeds a single eightbyte, each is classified
2359 // separately. Each eightbyte gets initialized to class
2360 // NO_CLASS.
2361 Class FieldLo, FieldHi;
2362
2363 // Bit-fields require special handling, they do not force the
2364 // structure to be passed in memory even if unaligned, and
2365 // therefore they can straddle an eightbyte.
2366 if (BitField) {
2367 // Ignore padding bit-fields.
2368 if (i->isUnnamedBitfield())
2369 continue;
2370
2371 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002372 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002373
2374 uint64_t EB_Lo = Offset / 64;
2375 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002376
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002377 if (EB_Lo) {
2378 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2379 FieldLo = NoClass;
2380 FieldHi = Integer;
2381 } else {
2382 FieldLo = Integer;
2383 FieldHi = EB_Hi ? Integer : NoClass;
2384 }
2385 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002386 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002387 Lo = merge(Lo, FieldLo);
2388 Hi = merge(Hi, FieldHi);
2389 if (Lo == Memory || Hi == Memory)
2390 break;
2391 }
2392
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002393 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002394 }
2395}
2396
Chris Lattner22a931e2010-06-29 06:01:59 +00002397ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002398 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2399 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002400 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002401 // Treat an enum type as its underlying type.
2402 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2403 Ty = EnumTy->getDecl()->getIntegerType();
2404
2405 return (Ty->isPromotableIntegerType() ?
2406 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2407 }
2408
John McCall7f416cc2015-09-08 08:05:57 +00002409 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002410}
2411
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002412bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2413 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2414 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002415 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002416 if (Size <= 64 || Size > LargestVector)
2417 return true;
2418 }
2419
2420 return false;
2421}
2422
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002423ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2424 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002425 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2426 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002427 //
2428 // This assumption is optimistic, as there could be free registers available
2429 // when we need to pass this argument in memory, and LLVM could try to pass
2430 // the argument in the free register. This does not seem to happen currently,
2431 // but this code would be much safer if we could mark the argument with
2432 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002433 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002434 // Treat an enum type as its underlying type.
2435 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2436 Ty = EnumTy->getDecl()->getIntegerType();
2437
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002438 return (Ty->isPromotableIntegerType() ?
2439 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002440 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002441
Mark Lacey3825e832013-10-06 01:33:34 +00002442 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002443 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002444
Chris Lattner44c2b902011-05-22 23:21:23 +00002445 // Compute the byval alignment. We specify the alignment of the byval in all
2446 // cases so that the mid-level optimizer knows the alignment of the byval.
2447 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002448
2449 // Attempt to avoid passing indirect results using byval when possible. This
2450 // is important for good codegen.
2451 //
2452 // We do this by coercing the value into a scalar type which the backend can
2453 // handle naturally (i.e., without using byval).
2454 //
2455 // For simplicity, we currently only do this when we have exhausted all of the
2456 // free integer registers. Doing this when there are free integer registers
2457 // would require more care, as we would have to ensure that the coerced value
2458 // did not claim the unused register. That would require either reording the
2459 // arguments to the function (so that any subsequent inreg values came first),
2460 // or only doing this optimization when there were no following arguments that
2461 // might be inreg.
2462 //
2463 // We currently expect it to be rare (particularly in well written code) for
2464 // arguments to be passed on the stack when there are still free integer
2465 // registers available (this would typically imply large structs being passed
2466 // by value), so this seems like a fair tradeoff for now.
2467 //
2468 // We can revisit this if the backend grows support for 'onstack' parameter
2469 // attributes. See PR12193.
2470 if (freeIntRegs == 0) {
2471 uint64_t Size = getContext().getTypeSize(Ty);
2472
2473 // If this type fits in an eightbyte, coerce it into the matching integral
2474 // type, which will end up on the stack (with alignment 8).
2475 if (Align == 8 && Size <= 64)
2476 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2477 Size));
2478 }
2479
John McCall7f416cc2015-09-08 08:05:57 +00002480 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002481}
2482
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002483/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2484/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002485llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002486 // Wrapper structs/arrays that only contain vectors are passed just like
2487 // vectors; strip them off if present.
2488 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2489 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002490
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002491 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002492 if (isa<llvm::VectorType>(IRType) ||
2493 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002494 return IRType;
2495
2496 // We couldn't find the preferred IR vector type for 'Ty'.
2497 uint64_t Size = getContext().getTypeSize(Ty);
2498 assert((Size == 128 || Size == 256) && "Invalid type found!");
2499
2500 // Return a LLVM IR vector type based on the size of 'Ty'.
2501 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2502 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002503}
2504
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002505/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2506/// is known to either be off the end of the specified type or being in
2507/// alignment padding. The user type specified is known to be at most 128 bits
2508/// in size, and have passed through X86_64ABIInfo::classify with a successful
2509/// classification that put one of the two halves in the INTEGER class.
2510///
2511/// It is conservatively correct to return false.
2512static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2513 unsigned EndBit, ASTContext &Context) {
2514 // If the bytes being queried are off the end of the type, there is no user
2515 // data hiding here. This handles analysis of builtins, vectors and other
2516 // types that don't contain interesting padding.
2517 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2518 if (TySize <= StartBit)
2519 return true;
2520
Chris Lattner98076a22010-07-29 07:43:55 +00002521 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2522 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2523 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2524
2525 // Check each element to see if the element overlaps with the queried range.
2526 for (unsigned i = 0; i != NumElts; ++i) {
2527 // If the element is after the span we care about, then we're done..
2528 unsigned EltOffset = i*EltSize;
2529 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002530
Chris Lattner98076a22010-07-29 07:43:55 +00002531 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2532 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2533 EndBit-EltOffset, Context))
2534 return false;
2535 }
2536 // If it overlaps no elements, then it is safe to process as padding.
2537 return true;
2538 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002539
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002540 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2541 const RecordDecl *RD = RT->getDecl();
2542 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002543
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002544 // If this is a C++ record, check the bases first.
2545 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002546 for (const auto &I : CXXRD->bases()) {
2547 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002548 "Unexpected base class!");
2549 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002550 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002551
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002552 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002553 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002554 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002555
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002556 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002557 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002558 EndBit-BaseOffset, Context))
2559 return false;
2560 }
2561 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002562
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002563 // Verify that no field has data that overlaps the region of interest. Yes
2564 // this could be sped up a lot by being smarter about queried fields,
2565 // however we're only looking at structs up to 16 bytes, so we don't care
2566 // much.
2567 unsigned idx = 0;
2568 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2569 i != e; ++i, ++idx) {
2570 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002571
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002572 // If we found a field after the region we care about, then we're done.
2573 if (FieldOffset >= EndBit) break;
2574
2575 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2576 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2577 Context))
2578 return false;
2579 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002580
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002581 // If nothing in this record overlapped the area of interest, then we're
2582 // clean.
2583 return true;
2584 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002585
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002586 return false;
2587}
2588
Chris Lattnere556a712010-07-29 18:39:32 +00002589/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2590/// float member at the specified offset. For example, {int,{float}} has a
2591/// float at offset 4. It is conservatively correct for this routine to return
2592/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002593static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002594 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002595 // Base case if we find a float.
2596 if (IROffset == 0 && IRType->isFloatTy())
2597 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002598
Chris Lattnere556a712010-07-29 18:39:32 +00002599 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002600 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002601 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2602 unsigned Elt = SL->getElementContainingOffset(IROffset);
2603 IROffset -= SL->getElementOffset(Elt);
2604 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2605 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002606
Chris Lattnere556a712010-07-29 18:39:32 +00002607 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002608 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2609 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002610 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2611 IROffset -= IROffset/EltSize*EltSize;
2612 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2613 }
2614
2615 return false;
2616}
2617
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002618
2619/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2620/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002621llvm::Type *X86_64ABIInfo::
2622GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002623 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002624 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002625 // pass as float if the last 4 bytes is just padding. This happens for
2626 // structs that contain 3 floats.
2627 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2628 SourceOffset*8+64, getContext()))
2629 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002630
Chris Lattnere556a712010-07-29 18:39:32 +00002631 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2632 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2633 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002634 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2635 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002636 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002637
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002638 return llvm::Type::getDoubleTy(getVMContext());
2639}
2640
2641
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002642/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2643/// an 8-byte GPR. This means that we either have a scalar or we are talking
2644/// about the high or low part of an up-to-16-byte struct. This routine picks
2645/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002646/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2647/// etc).
2648///
2649/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2650/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2651/// the 8-byte value references. PrefType may be null.
2652///
Alp Toker9907f082014-07-09 14:06:35 +00002653/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002654/// an offset into this that we're processing (which is always either 0 or 8).
2655///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002656llvm::Type *X86_64ABIInfo::
2657GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002658 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002659 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2660 // returning an 8-byte unit starting with it. See if we can safely use it.
2661 if (IROffset == 0) {
2662 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002663 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2664 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002665 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002666
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002667 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2668 // goodness in the source type is just tail padding. This is allowed to
2669 // kick in for struct {double,int} on the int, but not on
2670 // struct{double,int,int} because we wouldn't return the second int. We
2671 // have to do this analysis on the source type because we can't depend on
2672 // unions being lowered a specific way etc.
2673 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002674 IRType->isIntegerTy(32) ||
2675 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2676 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2677 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002678
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002679 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2680 SourceOffset*8+64, getContext()))
2681 return IRType;
2682 }
2683 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002684
Chris Lattner2192fe52011-07-18 04:24:23 +00002685 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002686 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002687 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002688 if (IROffset < SL->getSizeInBytes()) {
2689 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2690 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002691
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002692 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2693 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002694 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002695 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002696
Chris Lattner2192fe52011-07-18 04:24:23 +00002697 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002698 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002699 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002700 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002701 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2702 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002703 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002704
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002705 // Okay, we don't have any better idea of what to pass, so we pass this in an
2706 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002707 unsigned TySizeInBytes =
2708 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002709
Chris Lattner3f763422010-07-29 17:34:39 +00002710 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002711
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002712 // It is always safe to classify this as an integer type up to i64 that
2713 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002714 return llvm::IntegerType::get(getVMContext(),
2715 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002716}
2717
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002718
2719/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2720/// be used as elements of a two register pair to pass or return, return a
2721/// first class aggregate to represent them. For example, if the low part of
2722/// a by-value argument should be passed as i32* and the high part as float,
2723/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002724static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002725GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002726 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002727 // In order to correctly satisfy the ABI, we need to the high part to start
2728 // at offset 8. If the high and low parts we inferred are both 4-byte types
2729 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2730 // the second element at offset 8. Check for this:
2731 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2732 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002733 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002734 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002735
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002736 // To handle this, we have to increase the size of the low part so that the
2737 // second element will start at an 8 byte offset. We can't increase the size
2738 // of the second element because it might make us access off the end of the
2739 // struct.
2740 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002741 // There are usually two sorts of types the ABI generation code can produce
2742 // for the low part of a pair that aren't 8 bytes in size: float or
2743 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2744 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002745 // Promote these to a larger type.
2746 if (Lo->isFloatTy())
2747 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2748 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002749 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2750 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002751 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2752 }
2753 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002754
Reid Kleckneree7cf842014-12-01 22:02:27 +00002755 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002756
2757
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002758 // Verify that the second element is at an 8-byte offset.
2759 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2760 "Invalid x86-64 argument pair!");
2761 return Result;
2762}
2763
Chris Lattner31faff52010-07-28 23:06:14 +00002764ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002765classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002766 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2767 // classification algorithm.
2768 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002769 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002770
2771 // Check some invariants.
2772 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002773 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2774
Craig Topper8a13c412014-05-21 05:09:00 +00002775 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002776 switch (Lo) {
2777 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002778 if (Hi == NoClass)
2779 return ABIArgInfo::getIgnore();
2780 // If the low part is just padding, it takes no register, leave ResType
2781 // null.
2782 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2783 "Unknown missing lo part");
2784 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002785
2786 case SSEUp:
2787 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002788 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002789
2790 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2791 // hidden argument.
2792 case Memory:
2793 return getIndirectReturnResult(RetTy);
2794
2795 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2796 // available register of the sequence %rax, %rdx is used.
2797 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002798 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002799
Chris Lattner1f3a0632010-07-29 21:42:50 +00002800 // If we have a sign or zero extended integer, make sure to return Extend
2801 // so that the parameter gets the right LLVM IR attributes.
2802 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2803 // Treat an enum type as its underlying type.
2804 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2805 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002806
Chris Lattner1f3a0632010-07-29 21:42:50 +00002807 if (RetTy->isIntegralOrEnumerationType() &&
2808 RetTy->isPromotableIntegerType())
2809 return ABIArgInfo::getExtend();
2810 }
Chris Lattner31faff52010-07-28 23:06:14 +00002811 break;
2812
2813 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2814 // available SSE register of the sequence %xmm0, %xmm1 is used.
2815 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002816 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002817 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002818
2819 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2820 // returned on the X87 stack in %st0 as 80-bit x87 number.
2821 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002822 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002823 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002824
2825 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2826 // part of the value is returned in %st0 and the imaginary part in
2827 // %st1.
2828 case ComplexX87:
2829 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002830 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002831 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002832 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002833 break;
2834 }
2835
Craig Topper8a13c412014-05-21 05:09:00 +00002836 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002837 switch (Hi) {
2838 // Memory was handled previously and X87 should
2839 // never occur as a hi class.
2840 case Memory:
2841 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002842 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002843
2844 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002845 case NoClass:
2846 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002847
Chris Lattner52b3c132010-09-01 00:20:33 +00002848 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002849 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002850 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2851 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002852 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002853 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002854 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002855 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2856 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002857 break;
2858
2859 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002860 // is passed in the next available eightbyte chunk if the last used
2861 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002862 //
Chris Lattner57540c52011-04-15 05:22:18 +00002863 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002864 case SSEUp:
2865 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002866 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002867 break;
2868
2869 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2870 // returned together with the previous X87 value in %st0.
2871 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002872 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002873 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002874 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002875 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002876 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002877 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002878 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2879 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002880 }
Chris Lattner31faff52010-07-28 23:06:14 +00002881 break;
2882 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002883
Chris Lattner52b3c132010-09-01 00:20:33 +00002884 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002885 // known to pass in the high eightbyte of the result. We do this by forming a
2886 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002887 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002888 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002889
Chris Lattner1f3a0632010-07-29 21:42:50 +00002890 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002891}
2892
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002893ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002894 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2895 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002896 const
2897{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002898 Ty = useFirstFieldIfTransparentUnion(Ty);
2899
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002900 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002901 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002902
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002903 // Check some invariants.
2904 // FIXME: Enforce these by construction.
2905 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002906 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2907
2908 neededInt = 0;
2909 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002910 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002911 switch (Lo) {
2912 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002913 if (Hi == NoClass)
2914 return ABIArgInfo::getIgnore();
2915 // If the low part is just padding, it takes no register, leave ResType
2916 // null.
2917 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2918 "Unknown missing lo part");
2919 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002920
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002921 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2922 // on the stack.
2923 case Memory:
2924
2925 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2926 // COMPLEX_X87, it is passed in memory.
2927 case X87:
2928 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002929 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002930 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002931 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002932
2933 case SSEUp:
2934 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002935 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002936
2937 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2938 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2939 // and %r9 is used.
2940 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002941 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002942
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002943 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002944 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002945
2946 // If we have a sign or zero extended integer, make sure to return Extend
2947 // so that the parameter gets the right LLVM IR attributes.
2948 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2949 // Treat an enum type as its underlying type.
2950 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2951 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002952
Chris Lattner1f3a0632010-07-29 21:42:50 +00002953 if (Ty->isIntegralOrEnumerationType() &&
2954 Ty->isPromotableIntegerType())
2955 return ABIArgInfo::getExtend();
2956 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002957
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002958 break;
2959
2960 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2961 // available SSE register is used, the registers are taken in the
2962 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002963 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002964 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002965 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002966 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002967 break;
2968 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002969 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002970
Craig Topper8a13c412014-05-21 05:09:00 +00002971 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002972 switch (Hi) {
2973 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002974 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002975 // which is passed in memory.
2976 case Memory:
2977 case X87:
2978 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002979 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002980
2981 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002982
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002983 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002984 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002985 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002986 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002987
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002988 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2989 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002990 break;
2991
2992 // X87Up generally doesn't occur here (long double is passed in
2993 // memory), except in situations involving unions.
2994 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002995 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002996 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002997
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002998 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2999 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00003000
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003001 ++neededSSE;
3002 break;
3003
3004 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3005 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003006 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003007 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00003008 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00003009 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003010 break;
3011 }
3012
Chris Lattnerbe5eb172010-09-01 00:24:35 +00003013 // If a high part was specified, merge it together with the low part. It is
3014 // known to pass in the high eightbyte of the result. We do this by forming a
3015 // first class struct aggregate with the high and low part: {low, high}
3016 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00003017 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00003018
Chris Lattner1f3a0632010-07-29 21:42:50 +00003019 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003020}
3021
Chris Lattner22326a12010-07-29 02:31:05 +00003022void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003023
Reid Kleckner40ca9132014-05-13 22:05:45 +00003024 if (!getCXXABI().classifyReturnType(FI))
3025 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003026
3027 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003028 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003029
3030 // If the return value is indirect, then the hidden argument is consuming one
3031 // integer register.
3032 if (FI.getReturnInfo().isIndirect())
3033 --freeIntRegs;
3034
Peter Collingbournef7706832014-12-12 23:41:25 +00003035 // The chain argument effectively gives us another free register.
3036 if (FI.isChainCall())
3037 ++freeIntRegs;
3038
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003039 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003040 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3041 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003042 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003043 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003044 it != ie; ++it, ++ArgNo) {
3045 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003046
Bill Wendling9987c0e2010-10-18 23:51:38 +00003047 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003048 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003049 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003050
3051 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3052 // eightbyte of an argument, the whole argument is passed on the
3053 // stack. If registers have already been assigned for some
3054 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003055 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003056 freeIntRegs -= neededInt;
3057 freeSSERegs -= neededSSE;
3058 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003059 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003060 }
3061 }
3062}
3063
John McCall7f416cc2015-09-08 08:05:57 +00003064static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3065 Address VAListAddr, QualType Ty) {
3066 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3067 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003068 llvm::Value *overflow_arg_area =
3069 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3070
3071 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3072 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003073 // It isn't stated explicitly in the standard, but in practice we use
3074 // alignment greater than 16 where necessary.
John McCall7f416cc2015-09-08 08:05:57 +00003075 uint64_t Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003076 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00003077 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00003078 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00003079 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003080 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
3081 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003082 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00003083 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003084 overflow_arg_area =
3085 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
3086 overflow_arg_area->getType(),
3087 "overflow_arg_area.align");
3088 }
3089
3090 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003091 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003092 llvm::Value *Res =
3093 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003094 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003095
3096 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3097 // l->overflow_arg_area + sizeof(type).
3098 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3099 // an 8 byte boundary.
3100
3101 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003102 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003103 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003104 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3105 "overflow_arg_area.next");
3106 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3107
3108 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
John McCall7f416cc2015-09-08 08:05:57 +00003109 return Address(Res, CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003110}
3111
John McCall7f416cc2015-09-08 08:05:57 +00003112Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3113 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003114 // Assume that va_list type is correct; should be pointer to LLVM type:
3115 // struct {
3116 // i32 gp_offset;
3117 // i32 fp_offset;
3118 // i8* overflow_arg_area;
3119 // i8* reg_save_area;
3120 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003121 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003122
John McCall7f416cc2015-09-08 08:05:57 +00003123 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003124 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003125 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003126
3127 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3128 // in the registers. If not go to step 7.
3129 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003130 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003131
3132 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3133 // general purpose registers needed to pass type and num_fp to hold
3134 // the number of floating point registers needed.
3135
3136 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3137 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3138 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3139 //
3140 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3141 // register save space).
3142
Craig Topper8a13c412014-05-21 05:09:00 +00003143 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003144 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3145 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003146 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003147 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003148 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3149 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003150 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003151 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3152 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003153 }
3154
3155 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003156 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003157 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3158 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003159 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3160 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003161 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3162 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003163 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3164 }
3165
3166 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3167 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3168 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3169 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3170
3171 // Emit code to load the value if it was passed in registers.
3172
3173 CGF.EmitBlock(InRegBlock);
3174
3175 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3176 // an offset of l->gp_offset and/or l->fp_offset. This may require
3177 // copying to a temporary location in case the parameter is passed
3178 // in different register classes or requires an alignment greater
3179 // than 8 for general purpose registers and 16 for XMM registers.
3180 //
3181 // FIXME: This really results in shameful code when we end up needing to
3182 // collect arguments from different places; often what should result in a
3183 // simple assembling of a structure from scattered addresses has many more
3184 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003185 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003186 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3187 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3188 "reg_save_area");
3189
3190 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003191 if (neededInt && neededSSE) {
3192 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003193 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003194 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003195 Address Tmp = CGF.CreateMemTemp(Ty);
3196 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003197 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003198 llvm::Type *TyLo = ST->getElementType(0);
3199 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003200 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003201 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003202 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3203 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003204 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3205 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003206 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3207 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003208
John McCall7f416cc2015-09-08 08:05:57 +00003209 // Copy the first element.
3210 llvm::Value *V =
3211 CGF.Builder.CreateDefaultAlignedLoad(
3212 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3213 CGF.Builder.CreateStore(V,
3214 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3215
3216 // Copy the second element.
3217 V = CGF.Builder.CreateDefaultAlignedLoad(
3218 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3219 CharUnits Offset = CharUnits::fromQuantity(
3220 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3221 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3222
3223 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003224 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003225 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3226 CharUnits::fromQuantity(8));
3227 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003228
3229 // Copy to a temporary if necessary to ensure the appropriate alignment.
3230 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003231 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003232 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003233 CharUnits TyAlign = SizeAlign.second;
3234
3235 // Copy into a temporary if the type is more aligned than the
3236 // register save area.
3237 if (TyAlign.getQuantity() > 8) {
3238 Address Tmp = CGF.CreateMemTemp(Ty);
3239 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003240 RegAddr = Tmp;
3241 }
John McCall7f416cc2015-09-08 08:05:57 +00003242
Chris Lattner0cf24192010-06-28 20:05:43 +00003243 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003244 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3245 CharUnits::fromQuantity(16));
3246 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003247 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003248 assert(neededSSE == 2 && "Invalid number of needed registers!");
3249 // SSE registers are spaced 16 bytes apart in the register save
3250 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003251 // The ABI isn't explicit about this, but it seems reasonable
3252 // to assume that the slots are 16-byte aligned, since the stack is
3253 // naturally 16-byte aligned and the prologue is expected to store
3254 // all the SSE registers to the RSA.
3255 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3256 CharUnits::fromQuantity(16));
3257 Address RegAddrHi =
3258 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3259 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003260 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003261 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003262 llvm::Value *V;
3263 Address Tmp = CGF.CreateMemTemp(Ty);
3264 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3265 V = CGF.Builder.CreateLoad(
3266 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3267 CGF.Builder.CreateStore(V,
3268 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3269 V = CGF.Builder.CreateLoad(
3270 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3271 CGF.Builder.CreateStore(V,
3272 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3273
3274 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003275 }
3276
3277 // AMD64-ABI 3.5.7p5: Step 5. Set:
3278 // l->gp_offset = l->gp_offset + num_gp * 8
3279 // l->fp_offset = l->fp_offset + num_fp * 16.
3280 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003281 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003282 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3283 gp_offset_p);
3284 }
3285 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003286 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003287 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3288 fp_offset_p);
3289 }
3290 CGF.EmitBranch(ContBlock);
3291
3292 // Emit code to load the value if it was passed in memory.
3293
3294 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003295 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003296
3297 // Return the appropriate result.
3298
3299 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003300 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3301 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003302 return ResAddr;
3303}
3304
Charles Davisc7d5c942015-09-17 20:55:33 +00003305Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3306 QualType Ty) const {
3307 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3308 CGF.getContext().getTypeInfoInChars(Ty),
3309 CharUnits::fromQuantity(8),
3310 /*allowHigherAlign*/ false);
3311}
3312
Reid Kleckner80944df2014-10-31 22:00:51 +00003313ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3314 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003315
3316 if (Ty->isVoidType())
3317 return ABIArgInfo::getIgnore();
3318
3319 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3320 Ty = EnumTy->getDecl()->getIntegerType();
3321
Reid Kleckner80944df2014-10-31 22:00:51 +00003322 TypeInfo Info = getContext().getTypeInfo(Ty);
3323 uint64_t Width = Info.Width;
Reid Kleckner11a17192015-10-28 22:29:52 +00003324 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003325
Reid Kleckner9005f412014-05-02 00:51:20 +00003326 const RecordType *RT = Ty->getAs<RecordType>();
3327 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003328 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003329 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003330 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003331 }
3332
3333 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003334 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003335
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003336 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner11a17192015-10-28 22:29:52 +00003337 if (Width == 128 && IsMingw64)
3338 return ABIArgInfo::getDirect(
3339 llvm::IntegerType::get(getVMContext(), Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003340 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003341
Reid Kleckner80944df2014-10-31 22:00:51 +00003342 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3343 // other targets.
3344 const Type *Base = nullptr;
3345 uint64_t NumElts = 0;
3346 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3347 if (FreeSSERegs >= NumElts) {
3348 FreeSSERegs -= NumElts;
3349 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3350 return ABIArgInfo::getDirect();
3351 return ABIArgInfo::getExpand();
3352 }
Reid Kleckner11a17192015-10-28 22:29:52 +00003353 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003354 }
3355
3356
Reid Klecknerec87fec2014-05-02 01:17:12 +00003357 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003358 // If the member pointer is represented by an LLVM int or ptr, pass it
3359 // directly.
3360 llvm::Type *LLTy = CGT.ConvertType(Ty);
3361 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3362 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003363 }
3364
Michael Kuperstein4f818702015-02-24 09:35:58 +00003365 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003366 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3367 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003368 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003369 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003370
Reid Kleckner9005f412014-05-02 00:51:20 +00003371 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003372 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003373 }
3374
Julien Lerouge10dcff82014-08-27 00:36:55 +00003375 // Bool type is always extended to the ABI, other builtin types are not
3376 // extended.
3377 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3378 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003379 return ABIArgInfo::getExtend();
3380
Reid Kleckner11a17192015-10-28 22:29:52 +00003381 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3382 // passes them indirectly through memory.
3383 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3384 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3385 if (LDF == &llvm::APFloat::x87DoubleExtended)
3386 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3387 }
3388
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003389 return ABIArgInfo::getDirect();
3390}
3391
3392void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003393 bool IsVectorCall =
3394 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003395
Reid Kleckner80944df2014-10-31 22:00:51 +00003396 // We can use up to 4 SSE return registers with vectorcall.
3397 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3398 if (!getCXXABI().classifyReturnType(FI))
3399 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3400
3401 // We can use up to 6 SSE register parameters with vectorcall.
3402 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003403 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003404 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003405}
3406
John McCall7f416cc2015-09-08 08:05:57 +00003407Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3408 QualType Ty) const {
3409 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3410 CGF.getContext().getTypeInfoInChars(Ty),
3411 CharUnits::fromQuantity(8),
3412 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003413}
Chris Lattner0cf24192010-06-28 20:05:43 +00003414
John McCallea8d8bb2010-03-11 00:10:12 +00003415// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003416namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003417/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3418class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003419public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003420 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3421
John McCall7f416cc2015-09-08 08:05:57 +00003422 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3423 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003424};
3425
3426class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3427public:
Eric Christopher7565e0d2015-05-29 23:09:49 +00003428 PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
3429 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003430
Craig Topper4f12f102014-03-12 06:41:41 +00003431 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003432 // This is recovered from gcc output.
3433 return 1; // r1 is the dedicated stack pointer
3434 }
3435
3436 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003437 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003438};
3439
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003440}
John McCallea8d8bb2010-03-11 00:10:12 +00003441
John McCall7f416cc2015-09-08 08:05:57 +00003442Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3443 QualType Ty) const {
Roman Divacky8a12d842014-11-03 18:32:54 +00003444 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3445 // TODO: Implement this. For now ignore.
3446 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003447 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003448 }
3449
John McCall7f416cc2015-09-08 08:05:57 +00003450 // struct __va_list_tag {
3451 // unsigned char gpr;
3452 // unsigned char fpr;
3453 // unsigned short reserved;
3454 // void *overflow_arg_area;
3455 // void *reg_save_area;
3456 // };
3457
Roman Divacky8a12d842014-11-03 18:32:54 +00003458 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003459 bool isInt =
3460 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
John McCall7f416cc2015-09-08 08:05:57 +00003461
3462 // All aggregates are passed indirectly? That doesn't seem consistent
3463 // with the argument-lowering code.
3464 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003465
3466 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003467
3468 // The calling convention either uses 1-2 GPRs or 1 FPR.
3469 Address NumRegsAddr = Address::invalid();
3470 if (isInt) {
3471 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3472 } else {
3473 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003474 }
John McCall7f416cc2015-09-08 08:05:57 +00003475
3476 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3477
3478 // "Align" the register count when TY is i64.
3479 if (isI64) {
3480 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3481 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3482 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003483
Eric Christopher7565e0d2015-05-29 23:09:49 +00003484 llvm::Value *CC =
John McCall7f416cc2015-09-08 08:05:57 +00003485 Builder.CreateICmpULT(NumRegs, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003486
3487 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3488 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3489 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3490
3491 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3492
John McCall7f416cc2015-09-08 08:05:57 +00003493 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3494 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003495
John McCall7f416cc2015-09-08 08:05:57 +00003496 // Case 1: consume registers.
3497 Address RegAddr = Address::invalid();
3498 {
3499 CGF.EmitBlock(UsingRegs);
3500
3501 Address RegSaveAreaPtr =
3502 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3503 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3504 CharUnits::fromQuantity(8));
3505 assert(RegAddr.getElementType() == CGF.Int8Ty);
3506
3507 // Floating-point registers start after the general-purpose registers.
3508 if (!isInt) {
3509 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3510 CharUnits::fromQuantity(32));
3511 }
3512
3513 // Get the address of the saved value by scaling the number of
3514 // registers we've used by the number of
3515 CharUnits RegSize = CharUnits::fromQuantity(isInt ? 4 : 8);
3516 llvm::Value *RegOffset =
3517 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3518 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3519 RegAddr.getPointer(), RegOffset),
3520 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3521 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3522
3523 // Increase the used-register count.
3524 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(isI64 ? 2 : 1));
3525 Builder.CreateStore(NumRegs, NumRegsAddr);
3526
3527 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003528 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003529
John McCall7f416cc2015-09-08 08:05:57 +00003530 // Case 2: consume space in the overflow area.
3531 Address MemAddr = Address::invalid();
3532 {
3533 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003534
John McCall7f416cc2015-09-08 08:05:57 +00003535 // Everything in the overflow area is rounded up to a size of at least 4.
3536 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3537
3538 CharUnits Size;
3539 if (!isIndirect) {
3540 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
3541 Size = TypeInfo.first.RoundUpToAlignment(OverflowAreaAlign);
3542 } else {
3543 Size = CGF.getPointerSize();
3544 }
3545
3546 Address OverflowAreaAddr =
3547 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
3548 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr),
3549 OverflowAreaAlign);
3550
3551 // The current address is the address of the varargs element.
3552 // FIXME: do we not need to round up to alignment?
3553 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3554
3555 // Increase the overflow area.
3556 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3557 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3558 CGF.EmitBranch(Cont);
3559 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003560
3561 CGF.EmitBlock(Cont);
3562
John McCall7f416cc2015-09-08 08:05:57 +00003563 // Merge the cases with a phi.
3564 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3565 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003566
John McCall7f416cc2015-09-08 08:05:57 +00003567 // Load the pointer if the argument was passed indirectly.
3568 if (isIndirect) {
3569 Result = Address(Builder.CreateLoad(Result, "aggr"),
3570 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003571 }
3572
3573 return Result;
3574}
3575
John McCallea8d8bb2010-03-11 00:10:12 +00003576bool
3577PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3578 llvm::Value *Address) const {
3579 // This is calculated from the LLVM and GCC tables and verified
3580 // against gcc output. AFAIK all ABIs use the same encoding.
3581
3582 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003583
Chris Lattnerece04092012-02-07 00:39:47 +00003584 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003585 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3586 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3587 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3588
3589 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003590 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003591
3592 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003593 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003594
3595 // 64-76 are various 4-byte special-purpose registers:
3596 // 64: mq
3597 // 65: lr
3598 // 66: ctr
3599 // 67: ap
3600 // 68-75 cr0-7
3601 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003602 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003603
3604 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003605 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003606
3607 // 109: vrsave
3608 // 110: vscr
3609 // 111: spe_acc
3610 // 112: spefscr
3611 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003612 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003613
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003614 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003615}
3616
Roman Divackyd966e722012-05-09 18:22:46 +00003617// PowerPC-64
3618
3619namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003620/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3621class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003622public:
3623 enum ABIKind {
3624 ELFv1 = 0,
3625 ELFv2
3626 };
3627
3628private:
3629 static const unsigned GPRBits = 64;
3630 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003631 bool HasQPX;
3632
3633 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3634 // will be passed in a QPX register.
3635 bool IsQPXVectorTy(const Type *Ty) const {
3636 if (!HasQPX)
3637 return false;
3638
3639 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3640 unsigned NumElements = VT->getNumElements();
3641 if (NumElements == 1)
3642 return false;
3643
3644 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3645 if (getContext().getTypeSize(Ty) <= 256)
3646 return true;
3647 } else if (VT->getElementType()->
3648 isSpecificBuiltinType(BuiltinType::Float)) {
3649 if (getContext().getTypeSize(Ty) <= 128)
3650 return true;
3651 }
3652 }
3653
3654 return false;
3655 }
3656
3657 bool IsQPXVectorTy(QualType Ty) const {
3658 return IsQPXVectorTy(Ty.getTypePtr());
3659 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003660
3661public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003662 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3663 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003664
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003665 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003666 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003667
3668 ABIArgInfo classifyReturnType(QualType RetTy) const;
3669 ABIArgInfo classifyArgumentType(QualType Ty) const;
3670
Reid Klecknere9f6a712014-10-31 17:10:41 +00003671 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3672 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3673 uint64_t Members) const override;
3674
Bill Schmidt84d37792012-10-12 19:26:17 +00003675 // TODO: We can add more logic to computeInfo to improve performance.
3676 // Example: For aggregate arguments that fit in a register, we could
3677 // use getDirectInReg (as is done below for structs containing a single
3678 // floating-point value) to avoid pushing them to memory on function
3679 // entry. This would require changing the logic in PPCISelLowering
3680 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003681 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003682 if (!getCXXABI().classifyReturnType(FI))
3683 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003684 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003685 // We rely on the default argument classification for the most part.
3686 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003687 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003688 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003689 if (T) {
3690 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003691 if (IsQPXVectorTy(T) ||
3692 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003693 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003694 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003695 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003696 continue;
3697 }
3698 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003699 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003700 }
3701 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003702
John McCall7f416cc2015-09-08 08:05:57 +00003703 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3704 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003705};
3706
3707class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003708
Bill Schmidt25cb3492012-10-03 19:18:57 +00003709public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003710 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003711 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003712 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003713
Craig Topper4f12f102014-03-12 06:41:41 +00003714 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003715 // This is recovered from gcc output.
3716 return 1; // r1 is the dedicated stack pointer
3717 }
3718
3719 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003720 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003721};
3722
Roman Divackyd966e722012-05-09 18:22:46 +00003723class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3724public:
3725 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3726
Craig Topper4f12f102014-03-12 06:41:41 +00003727 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003728 // This is recovered from gcc output.
3729 return 1; // r1 is the dedicated stack pointer
3730 }
3731
3732 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003733 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003734};
3735
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003736}
Roman Divackyd966e722012-05-09 18:22:46 +00003737
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003738// Return true if the ABI requires Ty to be passed sign- or zero-
3739// extended to 64 bits.
3740bool
3741PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3742 // Treat an enum type as its underlying type.
3743 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3744 Ty = EnumTy->getDecl()->getIntegerType();
3745
3746 // Promotable integer types are required to be promoted by the ABI.
3747 if (Ty->isPromotableIntegerType())
3748 return true;
3749
3750 // In addition to the usual promotable integer types, we also need to
3751 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3752 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3753 switch (BT->getKind()) {
3754 case BuiltinType::Int:
3755 case BuiltinType::UInt:
3756 return true;
3757 default:
3758 break;
3759 }
3760
3761 return false;
3762}
3763
John McCall7f416cc2015-09-08 08:05:57 +00003764/// isAlignedParamType - Determine whether a type requires 16-byte or
3765/// higher alignment in the parameter area. Always returns at least 8.
3766CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003767 // Complex types are passed just like their elements.
3768 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3769 Ty = CTy->getElementType();
3770
3771 // Only vector types of size 16 bytes need alignment (larger types are
3772 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003773 if (IsQPXVectorTy(Ty)) {
3774 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003775 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003776
John McCall7f416cc2015-09-08 08:05:57 +00003777 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003778 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003779 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003780 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003781
3782 // For single-element float/vector structs, we consider the whole type
3783 // to have the same alignment requirements as its single element.
3784 const Type *AlignAsType = nullptr;
3785 const Type *EltType = isSingleElementStruct(Ty, getContext());
3786 if (EltType) {
3787 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003788 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003789 getContext().getTypeSize(EltType) == 128) ||
3790 (BT && BT->isFloatingPoint()))
3791 AlignAsType = EltType;
3792 }
3793
Ulrich Weigandb7122372014-07-21 00:48:09 +00003794 // Likewise for ELFv2 homogeneous aggregates.
3795 const Type *Base = nullptr;
3796 uint64_t Members = 0;
3797 if (!AlignAsType && Kind == ELFv2 &&
3798 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3799 AlignAsType = Base;
3800
Ulrich Weigand581badc2014-07-10 17:20:07 +00003801 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003802 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3803 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003804 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003805
John McCall7f416cc2015-09-08 08:05:57 +00003806 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003807 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003808 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003809 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003810
3811 // Otherwise, we only need alignment for any aggregate type that
3812 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003813 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3814 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003815 return CharUnits::fromQuantity(32);
3816 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003817 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003818
John McCall7f416cc2015-09-08 08:05:57 +00003819 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003820}
3821
Ulrich Weigandb7122372014-07-21 00:48:09 +00003822/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3823/// aggregate. Base is set to the base element type, and Members is set
3824/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003825bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3826 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003827 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3828 uint64_t NElements = AT->getSize().getZExtValue();
3829 if (NElements == 0)
3830 return false;
3831 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3832 return false;
3833 Members *= NElements;
3834 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3835 const RecordDecl *RD = RT->getDecl();
3836 if (RD->hasFlexibleArrayMember())
3837 return false;
3838
3839 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003840
3841 // If this is a C++ record, check the bases first.
3842 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3843 for (const auto &I : CXXRD->bases()) {
3844 // Ignore empty records.
3845 if (isEmptyRecord(getContext(), I.getType(), true))
3846 continue;
3847
3848 uint64_t FldMembers;
3849 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3850 return false;
3851
3852 Members += FldMembers;
3853 }
3854 }
3855
Ulrich Weigandb7122372014-07-21 00:48:09 +00003856 for (const auto *FD : RD->fields()) {
3857 // Ignore (non-zero arrays of) empty records.
3858 QualType FT = FD->getType();
3859 while (const ConstantArrayType *AT =
3860 getContext().getAsConstantArrayType(FT)) {
3861 if (AT->getSize().getZExtValue() == 0)
3862 return false;
3863 FT = AT->getElementType();
3864 }
3865 if (isEmptyRecord(getContext(), FT, true))
3866 continue;
3867
3868 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3869 if (getContext().getLangOpts().CPlusPlus &&
3870 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3871 continue;
3872
3873 uint64_t FldMembers;
3874 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3875 return false;
3876
3877 Members = (RD->isUnion() ?
3878 std::max(Members, FldMembers) : Members + FldMembers);
3879 }
3880
3881 if (!Base)
3882 return false;
3883
3884 // Ensure there is no padding.
3885 if (getContext().getTypeSize(Base) * Members !=
3886 getContext().getTypeSize(Ty))
3887 return false;
3888 } else {
3889 Members = 1;
3890 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3891 Members = 2;
3892 Ty = CT->getElementType();
3893 }
3894
Reid Klecknere9f6a712014-10-31 17:10:41 +00003895 // Most ABIs only support float, double, and some vector type widths.
3896 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003897 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003898
3899 // The base type must be the same for all members. Types that
3900 // agree in both total size and mode (float vs. vector) are
3901 // treated as being equivalent here.
3902 const Type *TyPtr = Ty.getTypePtr();
3903 if (!Base)
3904 Base = TyPtr;
3905
3906 if (Base->isVectorType() != TyPtr->isVectorType() ||
3907 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3908 return false;
3909 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003910 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3911}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003912
Reid Klecknere9f6a712014-10-31 17:10:41 +00003913bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3914 // Homogeneous aggregates for ELFv2 must have base types of float,
3915 // double, long double, or 128-bit vectors.
3916 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3917 if (BT->getKind() == BuiltinType::Float ||
3918 BT->getKind() == BuiltinType::Double ||
3919 BT->getKind() == BuiltinType::LongDouble)
3920 return true;
3921 }
3922 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003923 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003924 return true;
3925 }
3926 return false;
3927}
3928
3929bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3930 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003931 // Vector types require one register, floating point types require one
3932 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003933 uint32_t NumRegs =
3934 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003935
3936 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003937 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003938}
3939
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003940ABIArgInfo
3941PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003942 Ty = useFirstFieldIfTransparentUnion(Ty);
3943
Bill Schmidt90b22c92012-11-27 02:46:43 +00003944 if (Ty->isAnyComplexType())
3945 return ABIArgInfo::getDirect();
3946
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003947 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3948 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003949 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003950 uint64_t Size = getContext().getTypeSize(Ty);
3951 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003952 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003953 else if (Size < 128) {
3954 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3955 return ABIArgInfo::getDirect(CoerceTy);
3956 }
3957 }
3958
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003959 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003960 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003961 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003962
John McCall7f416cc2015-09-08 08:05:57 +00003963 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
3964 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00003965
3966 // ELFv2 homogeneous aggregates are passed as array types.
3967 const Type *Base = nullptr;
3968 uint64_t Members = 0;
3969 if (Kind == ELFv2 &&
3970 isHomogeneousAggregate(Ty, Base, Members)) {
3971 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3972 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3973 return ABIArgInfo::getDirect(CoerceTy);
3974 }
3975
Ulrich Weigand601957f2014-07-21 00:56:36 +00003976 // If an aggregate may end up fully in registers, we do not
3977 // use the ByVal method, but pass the aggregate as array.
3978 // This is usually beneficial since we avoid forcing the
3979 // back-end to store the argument to memory.
3980 uint64_t Bits = getContext().getTypeSize(Ty);
3981 if (Bits > 0 && Bits <= 8 * GPRBits) {
3982 llvm::Type *CoerceTy;
3983
3984 // Types up to 8 bytes are passed as integer type (which will be
3985 // properly aligned in the argument save area doubleword).
3986 if (Bits <= GPRBits)
3987 CoerceTy = llvm::IntegerType::get(getVMContext(),
3988 llvm::RoundUpToAlignment(Bits, 8));
3989 // Larger types are passed as arrays, with the base type selected
3990 // according to the required alignment in the save area.
3991 else {
3992 uint64_t RegBits = ABIAlign * 8;
3993 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3994 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3995 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3996 }
3997
3998 return ABIArgInfo::getDirect(CoerceTy);
3999 }
4000
Ulrich Weigandb7122372014-07-21 00:48:09 +00004001 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00004002 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4003 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00004004 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004005 }
4006
4007 return (isPromotableTypeForABI(Ty) ?
4008 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4009}
4010
4011ABIArgInfo
4012PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4013 if (RetTy->isVoidType())
4014 return ABIArgInfo::getIgnore();
4015
Bill Schmidta3d121c2012-12-17 04:20:17 +00004016 if (RetTy->isAnyComplexType())
4017 return ABIArgInfo::getDirect();
4018
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004019 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4020 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00004021 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004022 uint64_t Size = getContext().getTypeSize(RetTy);
4023 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004024 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00004025 else if (Size < 128) {
4026 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4027 return ABIArgInfo::getDirect(CoerceTy);
4028 }
4029 }
4030
Ulrich Weigandb7122372014-07-21 00:48:09 +00004031 if (isAggregateTypeForABI(RetTy)) {
4032 // ELFv2 homogeneous aggregates are returned as array types.
4033 const Type *Base = nullptr;
4034 uint64_t Members = 0;
4035 if (Kind == ELFv2 &&
4036 isHomogeneousAggregate(RetTy, Base, Members)) {
4037 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4038 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4039 return ABIArgInfo::getDirect(CoerceTy);
4040 }
4041
4042 // ELFv2 small aggregates are returned in up to two registers.
4043 uint64_t Bits = getContext().getTypeSize(RetTy);
4044 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4045 if (Bits == 0)
4046 return ABIArgInfo::getIgnore();
4047
4048 llvm::Type *CoerceTy;
4049 if (Bits > GPRBits) {
4050 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004051 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004052 } else
4053 CoerceTy = llvm::IntegerType::get(getVMContext(),
4054 llvm::RoundUpToAlignment(Bits, 8));
4055 return ABIArgInfo::getDirect(CoerceTy);
4056 }
4057
4058 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004059 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004060 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004061
4062 return (isPromotableTypeForABI(RetTy) ?
4063 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4064}
4065
Bill Schmidt25cb3492012-10-03 19:18:57 +00004066// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004067Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4068 QualType Ty) const {
4069 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4070 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004071
John McCall7f416cc2015-09-08 08:05:57 +00004072 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004073
Bill Schmidt924c4782013-01-14 17:45:36 +00004074 // If we have a complex type and the base type is smaller than 8 bytes,
4075 // the ABI calls for the real and imaginary parts to be right-adjusted
4076 // in separate doublewords. However, Clang expects us to produce a
4077 // pointer to a structure with the two parts packed tightly. So generate
4078 // loads of the real and imaginary parts relative to the va_list pointer,
4079 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004080 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4081 CharUnits EltSize = TypeInfo.first / 2;
4082 if (EltSize < SlotSize) {
4083 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4084 SlotSize * 2, SlotSize,
4085 SlotSize, /*AllowHigher*/ true);
4086
4087 Address RealAddr = Addr;
4088 Address ImagAddr = RealAddr;
4089 if (CGF.CGM.getDataLayout().isBigEndian()) {
4090 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4091 SlotSize - EltSize);
4092 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4093 2 * SlotSize - EltSize);
4094 } else {
4095 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4096 }
4097
4098 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4099 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4100 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4101 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4102 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4103
4104 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4105 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4106 /*init*/ true);
4107 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004108 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004109 }
4110
John McCall7f416cc2015-09-08 08:05:57 +00004111 // Otherwise, just use the general rule.
4112 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4113 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004114}
4115
4116static bool
4117PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4118 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004119 // This is calculated from the LLVM and GCC tables and verified
4120 // against gcc output. AFAIK all ABIs use the same encoding.
4121
4122 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4123
4124 llvm::IntegerType *i8 = CGF.Int8Ty;
4125 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4126 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4127 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4128
4129 // 0-31: r0-31, the 8-byte general-purpose registers
4130 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4131
4132 // 32-63: fp0-31, the 8-byte floating-point registers
4133 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4134
4135 // 64-76 are various 4-byte special-purpose registers:
4136 // 64: mq
4137 // 65: lr
4138 // 66: ctr
4139 // 67: ap
4140 // 68-75 cr0-7
4141 // 76: xer
4142 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4143
4144 // 77-108: v0-31, the 16-byte vector registers
4145 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4146
4147 // 109: vrsave
4148 // 110: vscr
4149 // 111: spe_acc
4150 // 112: spefscr
4151 // 113: sfp
4152 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4153
4154 return false;
4155}
John McCallea8d8bb2010-03-11 00:10:12 +00004156
Bill Schmidt25cb3492012-10-03 19:18:57 +00004157bool
4158PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4159 CodeGen::CodeGenFunction &CGF,
4160 llvm::Value *Address) const {
4161
4162 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4163}
4164
4165bool
4166PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4167 llvm::Value *Address) const {
4168
4169 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4170}
4171
Chris Lattner0cf24192010-06-28 20:05:43 +00004172//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004173// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004174//===----------------------------------------------------------------------===//
4175
4176namespace {
4177
Tim Northover573cbee2014-05-24 12:52:07 +00004178class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004179public:
4180 enum ABIKind {
4181 AAPCS = 0,
4182 DarwinPCS
4183 };
4184
4185private:
4186 ABIKind Kind;
4187
4188public:
Tim Northover573cbee2014-05-24 12:52:07 +00004189 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004190
4191private:
4192 ABIKind getABIKind() const { return Kind; }
4193 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4194
4195 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004196 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004197 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4198 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4199 uint64_t Members) const override;
4200
Tim Northovera2ee4332014-03-29 15:09:45 +00004201 bool isIllegalVectorType(QualType Ty) const;
4202
David Blaikie1cbb9712014-11-14 19:09:44 +00004203 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004204 if (!getCXXABI().classifyReturnType(FI))
4205 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004206
Tim Northoverb047bfa2014-11-27 21:02:49 +00004207 for (auto &it : FI.arguments())
4208 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004209 }
4210
John McCall7f416cc2015-09-08 08:05:57 +00004211 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4212 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004213
John McCall7f416cc2015-09-08 08:05:57 +00004214 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4215 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004216
John McCall7f416cc2015-09-08 08:05:57 +00004217 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4218 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004219 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4220 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4221 }
4222};
4223
Tim Northover573cbee2014-05-24 12:52:07 +00004224class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004225public:
Tim Northover573cbee2014-05-24 12:52:07 +00004226 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4227 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004228
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004229 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004230 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4231 }
4232
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004233 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4234 return 31;
4235 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004236
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004237 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004238};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004239}
Tim Northovera2ee4332014-03-29 15:09:45 +00004240
Tim Northoverb047bfa2014-11-27 21:02:49 +00004241ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004242 Ty = useFirstFieldIfTransparentUnion(Ty);
4243
Tim Northovera2ee4332014-03-29 15:09:45 +00004244 // Handle illegal vector types here.
4245 if (isIllegalVectorType(Ty)) {
4246 uint64_t Size = getContext().getTypeSize(Ty);
4247 if (Size <= 32) {
4248 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004249 return ABIArgInfo::getDirect(ResType);
4250 }
4251 if (Size == 64) {
4252 llvm::Type *ResType =
4253 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004254 return ABIArgInfo::getDirect(ResType);
4255 }
4256 if (Size == 128) {
4257 llvm::Type *ResType =
4258 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004259 return ABIArgInfo::getDirect(ResType);
4260 }
John McCall7f416cc2015-09-08 08:05:57 +00004261 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004262 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004263
4264 if (!isAggregateTypeForABI(Ty)) {
4265 // Treat an enum type as its underlying type.
4266 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4267 Ty = EnumTy->getDecl()->getIntegerType();
4268
Tim Northovera2ee4332014-03-29 15:09:45 +00004269 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4270 ? ABIArgInfo::getExtend()
4271 : ABIArgInfo::getDirect());
4272 }
4273
4274 // Structures with either a non-trivial destructor or a non-trivial
4275 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004276 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004277 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4278 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004279 }
4280
4281 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4282 // elsewhere for GNU compatibility.
4283 if (isEmptyRecord(getContext(), Ty, true)) {
4284 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4285 return ABIArgInfo::getIgnore();
4286
Tim Northovera2ee4332014-03-29 15:09:45 +00004287 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4288 }
4289
4290 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004291 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004292 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004293 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004294 return ABIArgInfo::getDirect(
4295 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004296 }
4297
4298 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4299 uint64_t Size = getContext().getTypeSize(Ty);
4300 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004301 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004302 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004303
Tim Northovera2ee4332014-03-29 15:09:45 +00004304 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4305 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004306 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004307 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4308 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4309 }
4310 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4311 }
4312
John McCall7f416cc2015-09-08 08:05:57 +00004313 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004314}
4315
Tim Northover573cbee2014-05-24 12:52:07 +00004316ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004317 if (RetTy->isVoidType())
4318 return ABIArgInfo::getIgnore();
4319
4320 // Large vector types should be returned via memory.
4321 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004322 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004323
4324 if (!isAggregateTypeForABI(RetTy)) {
4325 // Treat an enum type as its underlying type.
4326 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4327 RetTy = EnumTy->getDecl()->getIntegerType();
4328
Tim Northover4dab6982014-04-18 13:46:08 +00004329 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4330 ? ABIArgInfo::getExtend()
4331 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004332 }
4333
Tim Northovera2ee4332014-03-29 15:09:45 +00004334 if (isEmptyRecord(getContext(), RetTy, true))
4335 return ABIArgInfo::getIgnore();
4336
Craig Topper8a13c412014-05-21 05:09:00 +00004337 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004338 uint64_t Members = 0;
4339 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004340 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4341 return ABIArgInfo::getDirect();
4342
4343 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4344 uint64_t Size = getContext().getTypeSize(RetTy);
4345 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004346 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004347 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004348
4349 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4350 // For aggregates with 16-byte alignment, we use i128.
4351 if (Alignment < 128 && Size == 128) {
4352 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4353 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4354 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004355 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4356 }
4357
John McCall7f416cc2015-09-08 08:05:57 +00004358 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004359}
4360
Tim Northover573cbee2014-05-24 12:52:07 +00004361/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4362bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004363 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4364 // Check whether VT is legal.
4365 unsigned NumElements = VT->getNumElements();
4366 uint64_t Size = getContext().getTypeSize(VT);
4367 // NumElements should be power of 2 between 1 and 16.
4368 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4369 return true;
4370 return Size != 64 && (Size != 128 || NumElements == 1);
4371 }
4372 return false;
4373}
4374
Reid Klecknere9f6a712014-10-31 17:10:41 +00004375bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4376 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4377 // point type or a short-vector type. This is the same as the 32-bit ABI,
4378 // but with the difference that any floating-point type is allowed,
4379 // including __fp16.
4380 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4381 if (BT->isFloatingPoint())
4382 return true;
4383 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4384 unsigned VecSize = getContext().getTypeSize(VT);
4385 if (VecSize == 64 || VecSize == 128)
4386 return true;
4387 }
4388 return false;
4389}
4390
4391bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4392 uint64_t Members) const {
4393 return Members <= 4;
4394}
4395
John McCall7f416cc2015-09-08 08:05:57 +00004396Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004397 QualType Ty,
4398 CodeGenFunction &CGF) const {
4399 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004400 bool IsIndirect = AI.isIndirect();
4401
Tim Northoverb047bfa2014-11-27 21:02:49 +00004402 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4403 if (IsIndirect)
4404 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4405 else if (AI.getCoerceToType())
4406 BaseTy = AI.getCoerceToType();
4407
4408 unsigned NumRegs = 1;
4409 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4410 BaseTy = ArrTy->getElementType();
4411 NumRegs = ArrTy->getNumElements();
4412 }
4413 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4414
Tim Northovera2ee4332014-03-29 15:09:45 +00004415 // The AArch64 va_list type and handling is specified in the Procedure Call
4416 // Standard, section B.4:
4417 //
4418 // struct {
4419 // void *__stack;
4420 // void *__gr_top;
4421 // void *__vr_top;
4422 // int __gr_offs;
4423 // int __vr_offs;
4424 // };
4425
4426 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4427 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4428 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4429 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004430
John McCall7f416cc2015-09-08 08:05:57 +00004431 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4432 CharUnits TyAlign = TyInfo.second;
4433
4434 Address reg_offs_p = Address::invalid();
4435 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004436 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004437 CharUnits reg_top_offset;
4438 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004439 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004440 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004441 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004442 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4443 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004444 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4445 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004446 reg_top_offset = CharUnits::fromQuantity(8);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004447 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004448 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004449 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004450 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004451 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4452 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004453 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4454 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004455 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004456 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004457 }
4458
4459 //=======================================
4460 // Find out where argument was passed
4461 //=======================================
4462
4463 // If reg_offs >= 0 we're already using the stack for this type of
4464 // argument. We don't want to keep updating reg_offs (in case it overflows,
4465 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4466 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004467 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004468 UsingStack = CGF.Builder.CreateICmpSGE(
4469 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4470
4471 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4472
4473 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004474 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004475 CGF.EmitBlock(MaybeRegBlock);
4476
4477 // Integer arguments may need to correct register alignment (for example a
4478 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4479 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004480 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4481 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004482
4483 reg_offs = CGF.Builder.CreateAdd(
4484 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4485 "align_regoffs");
4486 reg_offs = CGF.Builder.CreateAnd(
4487 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4488 "aligned_regoffs");
4489 }
4490
4491 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004492 // The fact that this is done unconditionally reflects the fact that
4493 // allocating an argument to the stack also uses up all the remaining
4494 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004495 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004496 NewOffset = CGF.Builder.CreateAdd(
4497 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4498 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4499
4500 // Now we're in a position to decide whether this argument really was in
4501 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004502 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004503 InRegs = CGF.Builder.CreateICmpSLE(
4504 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4505
4506 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4507
4508 //=======================================
4509 // Argument was in registers
4510 //=======================================
4511
4512 // Now we emit the code for if the argument was originally passed in
4513 // registers. First start the appropriate block:
4514 CGF.EmitBlock(InRegBlock);
4515
John McCall7f416cc2015-09-08 08:05:57 +00004516 llvm::Value *reg_top = nullptr;
4517 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4518 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004519 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004520 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4521 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4522 Address RegAddr = Address::invalid();
4523 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004524
4525 if (IsIndirect) {
4526 // If it's been passed indirectly (actually a struct), whatever we find from
4527 // stored registers or on the stack will actually be a struct **.
4528 MemTy = llvm::PointerType::getUnqual(MemTy);
4529 }
4530
Craig Topper8a13c412014-05-21 05:09:00 +00004531 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004532 uint64_t NumMembers = 0;
4533 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004534 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004535 // Homogeneous aggregates passed in registers will have their elements split
4536 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4537 // qN+1, ...). We reload and store into a temporary local variable
4538 // contiguously.
4539 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004540 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004541 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4542 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004543 Address Tmp = CGF.CreateTempAlloca(HFATy,
4544 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004545
John McCall7f416cc2015-09-08 08:05:57 +00004546 // On big-endian platforms, the value will be right-aligned in its slot.
4547 int Offset = 0;
4548 if (CGF.CGM.getDataLayout().isBigEndian() &&
4549 BaseTyInfo.first.getQuantity() < 16)
4550 Offset = 16 - BaseTyInfo.first.getQuantity();
4551
Tim Northovera2ee4332014-03-29 15:09:45 +00004552 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004553 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4554 Address LoadAddr =
4555 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4556 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4557
4558 Address StoreAddr =
4559 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004560
4561 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4562 CGF.Builder.CreateStore(Elem, StoreAddr);
4563 }
4564
John McCall7f416cc2015-09-08 08:05:57 +00004565 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004566 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004567 // Otherwise the object is contiguous in memory.
4568
4569 // It might be right-aligned in its slot.
4570 CharUnits SlotSize = BaseAddr.getAlignment();
4571 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004572 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004573 TyInfo.first < SlotSize) {
4574 CharUnits Offset = SlotSize - TyInfo.first;
4575 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004576 }
4577
John McCall7f416cc2015-09-08 08:05:57 +00004578 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004579 }
4580
4581 CGF.EmitBranch(ContBlock);
4582
4583 //=======================================
4584 // Argument was on the stack
4585 //=======================================
4586 CGF.EmitBlock(OnStackBlock);
4587
John McCall7f416cc2015-09-08 08:05:57 +00004588 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4589 CharUnits::Zero(), "stack_p");
4590 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004591
John McCall7f416cc2015-09-08 08:05:57 +00004592 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004593 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004594 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4595 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004596
John McCall7f416cc2015-09-08 08:05:57 +00004597 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004598
John McCall7f416cc2015-09-08 08:05:57 +00004599 OnStackPtr = CGF.Builder.CreateAdd(
4600 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004601 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004602 OnStackPtr = CGF.Builder.CreateAnd(
4603 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004604 "align_stack");
4605
John McCall7f416cc2015-09-08 08:05:57 +00004606 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004607 }
John McCall7f416cc2015-09-08 08:05:57 +00004608 Address OnStackAddr(OnStackPtr,
4609 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004610
John McCall7f416cc2015-09-08 08:05:57 +00004611 // All stack slots are multiples of 8 bytes.
4612 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4613 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004614 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004615 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004616 else
John McCall7f416cc2015-09-08 08:05:57 +00004617 StackSize = TyInfo.first.RoundUpToAlignment(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004618
John McCall7f416cc2015-09-08 08:05:57 +00004619 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004620 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004621 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004622
4623 // Write the new value of __stack for the next call to va_arg
4624 CGF.Builder.CreateStore(NewStack, stack_p);
4625
4626 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004627 TyInfo.first < StackSlotSize) {
4628 CharUnits Offset = StackSlotSize - TyInfo.first;
4629 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004630 }
4631
John McCall7f416cc2015-09-08 08:05:57 +00004632 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004633
4634 CGF.EmitBranch(ContBlock);
4635
4636 //=======================================
4637 // Tidy up
4638 //=======================================
4639 CGF.EmitBlock(ContBlock);
4640
John McCall7f416cc2015-09-08 08:05:57 +00004641 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4642 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004643
4644 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004645 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4646 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004647
4648 return ResAddr;
4649}
4650
John McCall7f416cc2015-09-08 08:05:57 +00004651Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4652 CodeGenFunction &CGF) const {
4653 // The backend's lowering doesn't support va_arg for aggregates or
4654 // illegal vector types. Lower VAArg here for these cases and use
4655 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004656 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004657 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004658
John McCall7f416cc2015-09-08 08:05:57 +00004659 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004660
John McCall7f416cc2015-09-08 08:05:57 +00004661 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004662 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004663 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4664 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4665 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004666 }
4667
John McCall7f416cc2015-09-08 08:05:57 +00004668 // The size of the actual thing passed, which might end up just
4669 // being a pointer for indirect types.
4670 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4671
4672 // Arguments bigger than 16 bytes which aren't homogeneous
4673 // aggregates should be passed indirectly.
4674 bool IsIndirect = false;
4675 if (TyInfo.first.getQuantity() > 16) {
4676 const Type *Base = nullptr;
4677 uint64_t Members = 0;
4678 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004679 }
4680
John McCall7f416cc2015-09-08 08:05:57 +00004681 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4682 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004683}
4684
4685//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004686// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004687//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004688
4689namespace {
4690
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004691class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004692public:
4693 enum ABIKind {
4694 APCS = 0,
4695 AAPCS = 1,
4696 AAPCS_VFP
4697 };
4698
4699private:
4700 ABIKind Kind;
4701
4702public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004703 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004704 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004705 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004706
John McCall3480ef22011-08-30 01:42:09 +00004707 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004708 switch (getTarget().getTriple().getEnvironment()) {
4709 case llvm::Triple::Android:
4710 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004711 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004712 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004713 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004714 return true;
4715 default:
4716 return false;
4717 }
John McCall3480ef22011-08-30 01:42:09 +00004718 }
4719
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004720 bool isEABIHF() const {
4721 switch (getTarget().getTriple().getEnvironment()) {
4722 case llvm::Triple::EABIHF:
4723 case llvm::Triple::GNUEABIHF:
4724 return true;
4725 default:
4726 return false;
4727 }
4728 }
4729
Daniel Dunbar020daa92009-09-12 01:00:39 +00004730 ABIKind getABIKind() const { return Kind; }
4731
Tim Northovera484bc02013-10-01 14:34:25 +00004732private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004733 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004734 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004735 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004736
Reid Klecknere9f6a712014-10-31 17:10:41 +00004737 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4738 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4739 uint64_t Members) const override;
4740
Craig Topper4f12f102014-03-12 06:41:41 +00004741 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004742
John McCall7f416cc2015-09-08 08:05:57 +00004743 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4744 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004745
4746 llvm::CallingConv::ID getLLVMDefaultCC() const;
4747 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004748 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004749};
4750
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004751class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4752public:
Chris Lattner2b037972010-07-29 02:01:43 +00004753 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4754 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004755
John McCall3480ef22011-08-30 01:42:09 +00004756 const ARMABIInfo &getABIInfo() const {
4757 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4758 }
4759
Craig Topper4f12f102014-03-12 06:41:41 +00004760 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004761 return 13;
4762 }
Roman Divackyc1617352011-05-18 19:36:54 +00004763
Craig Topper4f12f102014-03-12 06:41:41 +00004764 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004765 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4766 }
4767
Roman Divackyc1617352011-05-18 19:36:54 +00004768 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004769 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004770 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004771
4772 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004773 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004774 return false;
4775 }
John McCall3480ef22011-08-30 01:42:09 +00004776
Craig Topper4f12f102014-03-12 06:41:41 +00004777 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004778 if (getABIInfo().isEABI()) return 88;
4779 return TargetCodeGenInfo::getSizeOfUnwindException();
4780 }
Tim Northovera484bc02013-10-01 14:34:25 +00004781
Eric Christopher162c91c2015-06-05 22:03:00 +00004782 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004783 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00004784 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Tim Northovera484bc02013-10-01 14:34:25 +00004785 if (!FD)
4786 return;
4787
4788 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4789 if (!Attr)
4790 return;
4791
4792 const char *Kind;
4793 switch (Attr->getInterrupt()) {
4794 case ARMInterruptAttr::Generic: Kind = ""; break;
4795 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4796 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4797 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4798 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4799 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4800 }
4801
4802 llvm::Function *Fn = cast<llvm::Function>(GV);
4803
4804 Fn->addFnAttr("interrupt", Kind);
4805
4806 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4807 return;
4808
4809 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4810 // however this is not necessarily true on taking any interrupt. Instruct
4811 // the backend to perform a realignment as part of the function prologue.
4812 llvm::AttrBuilder B;
4813 B.addStackAlignmentAttr(8);
4814 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4815 llvm::AttributeSet::get(CGM.getLLVMContext(),
4816 llvm::AttributeSet::FunctionIndex,
4817 B));
4818 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004819};
4820
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004821class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4822 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4823 CodeGen::CodeGenModule &CGM) const;
4824
4825public:
4826 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4827 : ARMTargetCodeGenInfo(CGT, K) {}
4828
Eric Christopher162c91c2015-06-05 22:03:00 +00004829 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004830 CodeGen::CodeGenModule &CGM) const override;
4831};
4832
4833void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4834 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4835 if (!isa<FunctionDecl>(D))
4836 return;
4837 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4838 return;
4839
4840 llvm::Function *F = cast<llvm::Function>(GV);
4841 F->addFnAttr("stack-probe-size",
4842 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4843}
4844
Eric Christopher162c91c2015-06-05 22:03:00 +00004845void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004846 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004847 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004848 addStackProbeSizeTargetAttribute(D, GV, CGM);
4849}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004850}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004851
Chris Lattner22326a12010-07-29 02:31:05 +00004852void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004853 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004854 FI.getReturnInfo() =
4855 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004856
Tim Northoverbc784d12015-02-24 17:22:40 +00004857 for (auto &I : FI.arguments())
4858 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004859
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004860 // Always honor user-specified calling convention.
4861 if (FI.getCallingConvention() != llvm::CallingConv::C)
4862 return;
4863
John McCall882987f2013-02-28 19:01:20 +00004864 llvm::CallingConv::ID cc = getRuntimeCC();
4865 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004866 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004867}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004868
John McCall882987f2013-02-28 19:01:20 +00004869/// Return the default calling convention that LLVM will use.
4870llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4871 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004872 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004873 return llvm::CallingConv::ARM_AAPCS_VFP;
4874 else if (isEABI())
4875 return llvm::CallingConv::ARM_AAPCS;
4876 else
4877 return llvm::CallingConv::ARM_APCS;
4878}
4879
4880/// Return the calling convention that our ABI would like us to use
4881/// as the C calling convention.
4882llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004883 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004884 case APCS: return llvm::CallingConv::ARM_APCS;
4885 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4886 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004887 }
John McCall882987f2013-02-28 19:01:20 +00004888 llvm_unreachable("bad ABI kind");
4889}
4890
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004891void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004892 assert(getRuntimeCC() == llvm::CallingConv::C);
4893
4894 // Don't muddy up the IR with a ton of explicit annotations if
4895 // they'd just match what LLVM will infer from the triple.
4896 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4897 if (abiCC != getLLVMDefaultCC())
4898 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004899
4900 BuiltinCC = (getABIKind() == APCS ?
4901 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004902}
4903
Tim Northoverbc784d12015-02-24 17:22:40 +00004904ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4905 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004906 // 6.1.2.1 The following argument types are VFP CPRCs:
4907 // A single-precision floating-point type (including promoted
4908 // half-precision types); A double-precision floating-point type;
4909 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4910 // with a Base Type of a single- or double-precision floating-point type,
4911 // 64-bit containerized vectors or 128-bit containerized vectors with one
4912 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004913 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004914
Reid Klecknerb1be6832014-11-15 01:41:41 +00004915 Ty = useFirstFieldIfTransparentUnion(Ty);
4916
Manman Renfef9e312012-10-16 19:18:39 +00004917 // Handle illegal vector types here.
4918 if (isIllegalVectorType(Ty)) {
4919 uint64_t Size = getContext().getTypeSize(Ty);
4920 if (Size <= 32) {
4921 llvm::Type *ResType =
4922 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004923 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004924 }
4925 if (Size == 64) {
4926 llvm::Type *ResType = llvm::VectorType::get(
4927 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004928 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004929 }
4930 if (Size == 128) {
4931 llvm::Type *ResType = llvm::VectorType::get(
4932 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004933 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004934 }
John McCall7f416cc2015-09-08 08:05:57 +00004935 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00004936 }
4937
Oliver Stannarddc2854c2015-09-03 12:40:58 +00004938 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
4939 // unspecified. This is not done for OpenCL as it handles the half type
4940 // natively, and does not need to interwork with AAPCS code.
4941 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
4942 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
4943 llvm::Type::getFloatTy(getVMContext()) :
4944 llvm::Type::getInt32Ty(getVMContext());
4945 return ABIArgInfo::getDirect(ResType);
4946 }
4947
John McCalla1dee5302010-08-22 10:59:02 +00004948 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004949 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004950 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004951 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004952 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004953
Tim Northover5a1558e2014-11-07 22:30:50 +00004954 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4955 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004956 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004957
Oliver Stannard405bded2014-02-11 09:25:50 +00004958 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004959 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004960 }
Tim Northover1060eae2013-06-21 22:49:34 +00004961
Daniel Dunbar09d33622009-09-14 21:54:03 +00004962 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004963 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004964 return ABIArgInfo::getIgnore();
4965
Tim Northover5a1558e2014-11-07 22:30:50 +00004966 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004967 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4968 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004969 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004970 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004971 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004972 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004973 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004974 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004975 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004976 }
4977
Manman Ren6c30e132012-08-13 21:23:55 +00004978 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004979 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4980 // most 8-byte. We realign the indirect argument if type alignment is bigger
4981 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004982 uint64_t ABIAlign = 4;
4983 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4984 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004985 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004986 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004987
Manman Ren8cd99812012-11-06 04:58:01 +00004988 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
John McCall7f416cc2015-09-08 08:05:57 +00004989 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4990 /*ByVal=*/true,
4991 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004992 }
4993
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004994 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004995 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004996 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004997 // FIXME: Try to match the types of the arguments more accurately where
4998 // we can.
4999 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00005000 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5001 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00005002 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00005003 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5004 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00005005 }
Stuart Hastings4b214952011-04-28 18:16:06 +00005006
Tim Northover5a1558e2014-11-07 22:30:50 +00005007 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005008}
5009
Chris Lattner458b2aa2010-07-29 02:16:43 +00005010static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005011 llvm::LLVMContext &VMContext) {
5012 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5013 // is called integer-like if its size is less than or equal to one word, and
5014 // the offset of each of its addressable sub-fields is zero.
5015
5016 uint64_t Size = Context.getTypeSize(Ty);
5017
5018 // Check that the type fits in a word.
5019 if (Size > 32)
5020 return false;
5021
5022 // FIXME: Handle vector types!
5023 if (Ty->isVectorType())
5024 return false;
5025
Daniel Dunbard53bac72009-09-14 02:20:34 +00005026 // Float types are never treated as "integer like".
5027 if (Ty->isRealFloatingType())
5028 return false;
5029
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005030 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00005031 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005032 return true;
5033
Daniel Dunbar96ebba52010-02-01 23:31:26 +00005034 // Small complex integer types are "integer like".
5035 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5036 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005037
5038 // Single element and zero sized arrays should be allowed, by the definition
5039 // above, but they are not.
5040
5041 // Otherwise, it must be a record type.
5042 const RecordType *RT = Ty->getAs<RecordType>();
5043 if (!RT) return false;
5044
5045 // Ignore records with flexible arrays.
5046 const RecordDecl *RD = RT->getDecl();
5047 if (RD->hasFlexibleArrayMember())
5048 return false;
5049
5050 // Check that all sub-fields are at offset 0, and are themselves "integer
5051 // like".
5052 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5053
5054 bool HadField = false;
5055 unsigned idx = 0;
5056 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5057 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005058 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005059
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005060 // Bit-fields are not addressable, we only need to verify they are "integer
5061 // like". We still have to disallow a subsequent non-bitfield, for example:
5062 // struct { int : 0; int x }
5063 // is non-integer like according to gcc.
5064 if (FD->isBitField()) {
5065 if (!RD->isUnion())
5066 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005067
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005068 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5069 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005070
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005071 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005072 }
5073
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005074 // Check if this field is at offset 0.
5075 if (Layout.getFieldOffset(idx) != 0)
5076 return false;
5077
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005078 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5079 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005080
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005081 // Only allow at most one field in a structure. This doesn't match the
5082 // wording above, but follows gcc in situations with a field following an
5083 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005084 if (!RD->isUnion()) {
5085 if (HadField)
5086 return false;
5087
5088 HadField = true;
5089 }
5090 }
5091
5092 return true;
5093}
5094
Oliver Stannard405bded2014-02-11 09:25:50 +00005095ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5096 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00005097 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005098
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005099 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005100 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005101
Daniel Dunbar19964db2010-09-23 01:54:32 +00005102 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005103 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005104 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005105 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005106
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005107 // __fp16 gets returned as if it were an int or float, but with the top 16
5108 // bits unspecified. This is not done for OpenCL as it handles the half type
5109 // natively, and does not need to interwork with AAPCS code.
5110 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5111 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5112 llvm::Type::getFloatTy(getVMContext()) :
5113 llvm::Type::getInt32Ty(getVMContext());
5114 return ABIArgInfo::getDirect(ResType);
5115 }
5116
John McCalla1dee5302010-08-22 10:59:02 +00005117 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005118 // Treat an enum type as its underlying type.
5119 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5120 RetTy = EnumTy->getDecl()->getIntegerType();
5121
Tim Northover5a1558e2014-11-07 22:30:50 +00005122 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5123 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005124 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005125
5126 // Are we following APCS?
5127 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005128 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005129 return ABIArgInfo::getIgnore();
5130
Daniel Dunbareedf1512010-02-01 23:31:19 +00005131 // Complex types are all returned as packed integers.
5132 //
5133 // FIXME: Consider using 2 x vector types if the back end handles them
5134 // correctly.
5135 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005136 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5137 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005138
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005139 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005140 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005141 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005142 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005143 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005144 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005145 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005146 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5147 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005148 }
5149
5150 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005151 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005152 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005153
5154 // Otherwise this is an AAPCS variant.
5155
Chris Lattner458b2aa2010-07-29 02:16:43 +00005156 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005157 return ABIArgInfo::getIgnore();
5158
Bob Wilson1d9269a2011-11-02 04:51:36 +00005159 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005160 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005161 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005162 uint64_t Members;
5163 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005164 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005165 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005166 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005167 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005168 }
5169
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005170 // Aggregates <= 4 bytes are returned in r0; other aggregates
5171 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005172 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005173 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005174 if (getDataLayout().isBigEndian())
5175 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005176 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005177
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005178 // Return in the smallest viable integer type.
5179 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005180 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005181 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005182 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5183 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005184 }
5185
John McCall7f416cc2015-09-08 08:05:57 +00005186 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005187}
5188
Manman Renfef9e312012-10-16 19:18:39 +00005189/// isIllegalVector - check whether Ty is an illegal vector type.
5190bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5191 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5192 // Check whether VT is legal.
5193 unsigned NumElements = VT->getNumElements();
5194 uint64_t Size = getContext().getTypeSize(VT);
5195 // NumElements should be power of 2.
5196 if ((NumElements & (NumElements - 1)) != 0)
5197 return true;
5198 // Size should be greater than 32 bits.
5199 return Size <= 32;
5200 }
5201 return false;
5202}
5203
Reid Klecknere9f6a712014-10-31 17:10:41 +00005204bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5205 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5206 // double, or 64-bit or 128-bit vectors.
5207 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5208 if (BT->getKind() == BuiltinType::Float ||
5209 BT->getKind() == BuiltinType::Double ||
5210 BT->getKind() == BuiltinType::LongDouble)
5211 return true;
5212 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5213 unsigned VecSize = getContext().getTypeSize(VT);
5214 if (VecSize == 64 || VecSize == 128)
5215 return true;
5216 }
5217 return false;
5218}
5219
5220bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5221 uint64_t Members) const {
5222 return Members <= 4;
5223}
5224
John McCall7f416cc2015-09-08 08:05:57 +00005225Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5226 QualType Ty) const {
5227 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005228
John McCall7f416cc2015-09-08 08:05:57 +00005229 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005230 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005231 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5232 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5233 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005234 }
5235
John McCall7f416cc2015-09-08 08:05:57 +00005236 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5237 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005238
John McCall7f416cc2015-09-08 08:05:57 +00005239 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5240 bool IsIndirect = false;
5241 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5242 IsIndirect = true;
5243
5244 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005245 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5246 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005247 // Our callers should be prepared to handle an under-aligned address.
5248 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5249 getABIKind() == ARMABIInfo::AAPCS) {
5250 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5251 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5252 } else {
5253 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005254 }
John McCall7f416cc2015-09-08 08:05:57 +00005255 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005256
John McCall7f416cc2015-09-08 08:05:57 +00005257 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5258 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005259}
5260
Chris Lattner0cf24192010-06-28 20:05:43 +00005261//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005262// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005263//===----------------------------------------------------------------------===//
5264
5265namespace {
5266
Justin Holewinski83e96682012-05-24 17:43:12 +00005267class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005268public:
Justin Holewinski36837432013-03-30 14:38:24 +00005269 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005270
5271 ABIArgInfo classifyReturnType(QualType RetTy) const;
5272 ABIArgInfo classifyArgumentType(QualType Ty) const;
5273
Craig Topper4f12f102014-03-12 06:41:41 +00005274 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005275 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5276 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005277};
5278
Justin Holewinski83e96682012-05-24 17:43:12 +00005279class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005280public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005281 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5282 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005283
Eric Christopher162c91c2015-06-05 22:03:00 +00005284 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005285 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005286private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005287 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5288 // resulting MDNode to the nvvm.annotations MDNode.
5289 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005290};
5291
Justin Holewinski83e96682012-05-24 17:43:12 +00005292ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005293 if (RetTy->isVoidType())
5294 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005295
5296 // note: this is different from default ABI
5297 if (!RetTy->isScalarType())
5298 return ABIArgInfo::getDirect();
5299
5300 // Treat an enum type as its underlying type.
5301 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5302 RetTy = EnumTy->getDecl()->getIntegerType();
5303
5304 return (RetTy->isPromotableIntegerType() ?
5305 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005306}
5307
Justin Holewinski83e96682012-05-24 17:43:12 +00005308ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005309 // Treat an enum type as its underlying type.
5310 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5311 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005312
Eli Bendersky95338a02014-10-29 13:43:21 +00005313 // Return aggregates type as indirect by value
5314 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005315 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005316
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005317 return (Ty->isPromotableIntegerType() ?
5318 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005319}
5320
Justin Holewinski83e96682012-05-24 17:43:12 +00005321void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005322 if (!getCXXABI().classifyReturnType(FI))
5323 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005324 for (auto &I : FI.arguments())
5325 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005326
5327 // Always honor user-specified calling convention.
5328 if (FI.getCallingConvention() != llvm::CallingConv::C)
5329 return;
5330
John McCall882987f2013-02-28 19:01:20 +00005331 FI.setEffectiveCallingConvention(getRuntimeCC());
5332}
5333
John McCall7f416cc2015-09-08 08:05:57 +00005334Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5335 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005336 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005337}
5338
Justin Holewinski83e96682012-05-24 17:43:12 +00005339void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005340setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005341 CodeGen::CodeGenModule &M) const{
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005342 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Justin Holewinski38031972011-10-05 17:58:44 +00005343 if (!FD) return;
5344
5345 llvm::Function *F = cast<llvm::Function>(GV);
5346
5347 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005348 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005349 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005350 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005351 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005352 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005353 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5354 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005355 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005356 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005357 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005358 }
Justin Holewinski38031972011-10-05 17:58:44 +00005359
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005360 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005361 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005362 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005363 // __global__ functions cannot be called from the device, we do not
5364 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005365 if (FD->hasAttr<CUDAGlobalAttr>()) {
5366 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5367 addNVVMMetadata(F, "kernel", 1);
5368 }
Artem Belevich7093e402015-04-21 22:55:54 +00005369 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005370 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005371 llvm::APSInt MaxThreads(32);
5372 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5373 if (MaxThreads > 0)
5374 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5375
5376 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5377 // not specified in __launch_bounds__ or if the user specified a 0 value,
5378 // we don't have to add a PTX directive.
5379 if (Attr->getMinBlocks()) {
5380 llvm::APSInt MinBlocks(32);
5381 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5382 if (MinBlocks > 0)
5383 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5384 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005385 }
5386 }
Justin Holewinski38031972011-10-05 17:58:44 +00005387 }
5388}
5389
Eli Benderskye06a2c42014-04-15 16:57:05 +00005390void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5391 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005392 llvm::Module *M = F->getParent();
5393 llvm::LLVMContext &Ctx = M->getContext();
5394
5395 // Get "nvvm.annotations" metadata node
5396 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5397
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005398 llvm::Metadata *MDVals[] = {
5399 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5400 llvm::ConstantAsMetadata::get(
5401 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005402 // Append metadata to nvvm.annotations
5403 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5404}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005405}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005406
5407//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005408// SystemZ ABI Implementation
5409//===----------------------------------------------------------------------===//
5410
5411namespace {
5412
5413class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005414 bool HasVector;
5415
Ulrich Weigand47445072013-05-06 16:26:41 +00005416public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005417 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5418 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005419
5420 bool isPromotableIntegerType(QualType Ty) const;
5421 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005422 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005423 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005424 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005425
5426 ABIArgInfo classifyReturnType(QualType RetTy) const;
5427 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5428
Craig Topper4f12f102014-03-12 06:41:41 +00005429 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005430 if (!getCXXABI().classifyReturnType(FI))
5431 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005432 for (auto &I : FI.arguments())
5433 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005434 }
5435
John McCall7f416cc2015-09-08 08:05:57 +00005436 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5437 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005438};
5439
5440class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5441public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005442 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5443 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005444};
5445
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005446}
Ulrich Weigand47445072013-05-06 16:26:41 +00005447
5448bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5449 // Treat an enum type as its underlying type.
5450 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5451 Ty = EnumTy->getDecl()->getIntegerType();
5452
5453 // Promotable integer types are required to be promoted by the ABI.
5454 if (Ty->isPromotableIntegerType())
5455 return true;
5456
5457 // 32-bit values must also be promoted.
5458 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5459 switch (BT->getKind()) {
5460 case BuiltinType::Int:
5461 case BuiltinType::UInt:
5462 return true;
5463 default:
5464 return false;
5465 }
5466 return false;
5467}
5468
5469bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005470 return (Ty->isAnyComplexType() ||
5471 Ty->isVectorType() ||
5472 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005473}
5474
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005475bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5476 return (HasVector &&
5477 Ty->isVectorType() &&
5478 getContext().getTypeSize(Ty) <= 128);
5479}
5480
Ulrich Weigand47445072013-05-06 16:26:41 +00005481bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5482 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5483 switch (BT->getKind()) {
5484 case BuiltinType::Float:
5485 case BuiltinType::Double:
5486 return true;
5487 default:
5488 return false;
5489 }
5490
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005491 return false;
5492}
5493
5494QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005495 if (const RecordType *RT = Ty->getAsStructureType()) {
5496 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005497 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005498
5499 // If this is a C++ record, check the bases first.
5500 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005501 for (const auto &I : CXXRD->bases()) {
5502 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005503
5504 // Empty bases don't affect things either way.
5505 if (isEmptyRecord(getContext(), Base, true))
5506 continue;
5507
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005508 if (!Found.isNull())
5509 return Ty;
5510 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005511 }
5512
5513 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005514 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005515 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005516 // Unlike isSingleElementStruct(), empty structure and array fields
5517 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005518 if (getContext().getLangOpts().CPlusPlus &&
5519 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5520 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005521
5522 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005523 // Nested structures still do though.
5524 if (!Found.isNull())
5525 return Ty;
5526 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005527 }
5528
5529 // Unlike isSingleElementStruct(), trailing padding is allowed.
5530 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005531 if (!Found.isNull())
5532 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005533 }
5534
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005535 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005536}
5537
John McCall7f416cc2015-09-08 08:05:57 +00005538Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5539 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005540 // Assume that va_list type is correct; should be pointer to LLVM type:
5541 // struct {
5542 // i64 __gpr;
5543 // i64 __fpr;
5544 // i8 *__overflow_arg_area;
5545 // i8 *__reg_save_area;
5546 // };
5547
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005548 // Every non-vector argument occupies 8 bytes and is passed by preference
5549 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5550 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005551 Ty = getContext().getCanonicalType(Ty);
5552 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005553 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005554 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005555 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005556 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005557 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005558 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005559 CharUnits UnpaddedSize;
5560 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005561 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005562 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5563 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005564 } else {
5565 if (AI.getCoerceToType())
5566 ArgTy = AI.getCoerceToType();
5567 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005568 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005569 UnpaddedSize = TyInfo.first;
5570 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005571 }
John McCall7f416cc2015-09-08 08:05:57 +00005572 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5573 if (IsVector && UnpaddedSize > PaddedSize)
5574 PaddedSize = CharUnits::fromQuantity(16);
5575 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005576
John McCall7f416cc2015-09-08 08:05:57 +00005577 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005578
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005579 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005580 llvm::Value *PaddedSizeV =
5581 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005582
5583 if (IsVector) {
5584 // Work out the address of a vector argument on the stack.
5585 // Vector arguments are always passed in the high bits of a
5586 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005587 Address OverflowArgAreaPtr =
5588 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005589 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005590 Address OverflowArgArea =
5591 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5592 TyInfo.second);
5593 Address MemAddr =
5594 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005595
5596 // Update overflow_arg_area_ptr pointer
5597 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005598 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5599 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005600 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5601
5602 return MemAddr;
5603 }
5604
John McCall7f416cc2015-09-08 08:05:57 +00005605 assert(PaddedSize.getQuantity() == 8);
5606
5607 unsigned MaxRegs, RegCountField, RegSaveIndex;
5608 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005609 if (InFPRs) {
5610 MaxRegs = 4; // Maximum of 4 FPR arguments
5611 RegCountField = 1; // __fpr
5612 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005613 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005614 } else {
5615 MaxRegs = 5; // Maximum of 5 GPR arguments
5616 RegCountField = 0; // __gpr
5617 RegSaveIndex = 2; // save offset for r2
5618 RegPadding = Padding; // values are passed in the low bits of a GPR
5619 }
5620
John McCall7f416cc2015-09-08 08:05:57 +00005621 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5622 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5623 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005624 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005625 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5626 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005627 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005628
5629 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5630 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5631 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5632 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5633
5634 // Emit code to load the value if it was passed in registers.
5635 CGF.EmitBlock(InRegBlock);
5636
5637 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005638 llvm::Value *ScaledRegCount =
5639 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5640 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005641 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5642 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005643 llvm::Value *RegOffset =
5644 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005645 Address RegSaveAreaPtr =
5646 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5647 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005648 llvm::Value *RegSaveArea =
5649 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005650 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5651 "raw_reg_addr"),
5652 PaddedSize);
5653 Address RegAddr =
5654 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005655
5656 // Update the register count
5657 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5658 llvm::Value *NewRegCount =
5659 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5660 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5661 CGF.EmitBranch(ContBlock);
5662
5663 // Emit code to load the value if it was passed in memory.
5664 CGF.EmitBlock(InMemBlock);
5665
5666 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005667 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5668 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5669 Address OverflowArgArea =
5670 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5671 PaddedSize);
5672 Address RawMemAddr =
5673 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5674 Address MemAddr =
5675 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005676
5677 // Update overflow_arg_area_ptr pointer
5678 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005679 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5680 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005681 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5682 CGF.EmitBranch(ContBlock);
5683
5684 // Return the appropriate result.
5685 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005686 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5687 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005688
5689 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005690 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5691 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005692
5693 return ResAddr;
5694}
5695
Ulrich Weigand47445072013-05-06 16:26:41 +00005696ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5697 if (RetTy->isVoidType())
5698 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005699 if (isVectorArgumentType(RetTy))
5700 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005701 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005702 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005703 return (isPromotableIntegerType(RetTy) ?
5704 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5705}
5706
5707ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5708 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005709 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005710 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005711
5712 // Integers and enums are extended to full register width.
5713 if (isPromotableIntegerType(Ty))
5714 return ABIArgInfo::getExtend();
5715
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005716 // Handle vector types and vector-like structure types. Note that
5717 // as opposed to float-like structure types, we do not allow any
5718 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005719 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005720 QualType SingleElementTy = GetSingleElementType(Ty);
5721 if (isVectorArgumentType(SingleElementTy) &&
5722 getContext().getTypeSize(SingleElementTy) == Size)
5723 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5724
5725 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005726 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005727 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005728
5729 // Handle small structures.
5730 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5731 // Structures with flexible arrays have variable length, so really
5732 // fail the size test above.
5733 const RecordDecl *RD = RT->getDecl();
5734 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005735 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005736
5737 // The structure is passed as an unextended integer, a float, or a double.
5738 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005739 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005740 assert(Size == 32 || Size == 64);
5741 if (Size == 32)
5742 PassTy = llvm::Type::getFloatTy(getVMContext());
5743 else
5744 PassTy = llvm::Type::getDoubleTy(getVMContext());
5745 } else
5746 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5747 return ABIArgInfo::getDirect(PassTy);
5748 }
5749
5750 // Non-structure compounds are passed indirectly.
5751 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005752 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005753
Craig Topper8a13c412014-05-21 05:09:00 +00005754 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005755}
5756
5757//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005758// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005759//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005760
5761namespace {
5762
5763class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5764public:
Chris Lattner2b037972010-07-29 02:01:43 +00005765 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5766 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005767 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005768 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005769};
5770
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005771}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005772
Eric Christopher162c91c2015-06-05 22:03:00 +00005773void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005774 llvm::GlobalValue *GV,
5775 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005776 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005777 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5778 // Handle 'interrupt' attribute:
5779 llvm::Function *F = cast<llvm::Function>(GV);
5780
5781 // Step 1: Set ISR calling convention.
5782 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5783
5784 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005785 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005786
5787 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005788 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005789 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5790 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005791 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005792 }
5793}
5794
Chris Lattner0cf24192010-06-28 20:05:43 +00005795//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005796// MIPS ABI Implementation. This works for both little-endian and
5797// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005798//===----------------------------------------------------------------------===//
5799
John McCall943fae92010-05-27 06:19:26 +00005800namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005801class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005802 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005803 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5804 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005805 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005806 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005807 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005808 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005809public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005810 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005811 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005812 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005813
5814 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005815 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005816 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005817 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5818 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005819 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005820};
5821
John McCall943fae92010-05-27 06:19:26 +00005822class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005823 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005824public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005825 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5826 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005827 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005828
Craig Topper4f12f102014-03-12 06:41:41 +00005829 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005830 return 29;
5831 }
5832
Eric Christopher162c91c2015-06-05 22:03:00 +00005833 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005834 CodeGen::CodeGenModule &CGM) const override {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00005835 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005836 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005837 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005838 if (FD->hasAttr<Mips16Attr>()) {
5839 Fn->addFnAttr("mips16");
5840 }
5841 else if (FD->hasAttr<NoMips16Attr>()) {
5842 Fn->addFnAttr("nomips16");
5843 }
Reed Kotler373feca2013-01-16 17:10:28 +00005844 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005845
John McCall943fae92010-05-27 06:19:26 +00005846 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005847 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005848
Craig Topper4f12f102014-03-12 06:41:41 +00005849 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005850 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005851 }
John McCall943fae92010-05-27 06:19:26 +00005852};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005853}
John McCall943fae92010-05-27 06:19:26 +00005854
Eric Christopher7565e0d2015-05-29 23:09:49 +00005855void MipsABIInfo::CoerceToIntArgs(
5856 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005857 llvm::IntegerType *IntTy =
5858 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005859
5860 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5861 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5862 ArgList.push_back(IntTy);
5863
5864 // If necessary, add one more integer type to ArgList.
5865 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5866
5867 if (R)
5868 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005869}
5870
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005871// In N32/64, an aligned double precision floating point field is passed in
5872// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005873llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005874 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5875
5876 if (IsO32) {
5877 CoerceToIntArgs(TySize, ArgList);
5878 return llvm::StructType::get(getVMContext(), ArgList);
5879 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005880
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005881 if (Ty->isComplexType())
5882 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005883
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005884 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005885
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005886 // Unions/vectors are passed in integer registers.
5887 if (!RT || !RT->isStructureOrClassType()) {
5888 CoerceToIntArgs(TySize, ArgList);
5889 return llvm::StructType::get(getVMContext(), ArgList);
5890 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005891
5892 const RecordDecl *RD = RT->getDecl();
5893 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005894 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00005895
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005896 uint64_t LastOffset = 0;
5897 unsigned idx = 0;
5898 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5899
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005900 // Iterate over fields in the struct/class and check if there are any aligned
5901 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005902 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5903 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005904 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005905 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5906
5907 if (!BT || BT->getKind() != BuiltinType::Double)
5908 continue;
5909
5910 uint64_t Offset = Layout.getFieldOffset(idx);
5911 if (Offset % 64) // Ignore doubles that are not aligned.
5912 continue;
5913
5914 // Add ((Offset - LastOffset) / 64) args of type i64.
5915 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5916 ArgList.push_back(I64);
5917
5918 // Add double type.
5919 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5920 LastOffset = Offset + 64;
5921 }
5922
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005923 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5924 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005925
5926 return llvm::StructType::get(getVMContext(), ArgList);
5927}
5928
Akira Hatanakaddd66342013-10-29 18:41:15 +00005929llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5930 uint64_t Offset) const {
5931 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005932 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005933
Akira Hatanakaddd66342013-10-29 18:41:15 +00005934 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005935}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005936
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005937ABIArgInfo
5938MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005939 Ty = useFirstFieldIfTransparentUnion(Ty);
5940
Akira Hatanaka1632af62012-01-09 19:31:25 +00005941 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005942 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005943 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005944
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005945 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5946 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005947 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5948 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005949
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005950 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005951 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005952 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005953 return ABIArgInfo::getIgnore();
5954
Mark Lacey3825e832013-10-06 01:33:34 +00005955 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005956 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00005957 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005958 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005959
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005960 // If we have reached here, aggregates are passed directly by coercing to
5961 // another structure type. Padding is inserted if the offset of the
5962 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005963 ABIArgInfo ArgInfo =
5964 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5965 getPaddingType(OrigOffset, CurrOffset));
5966 ArgInfo.setInReg(true);
5967 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005968 }
5969
5970 // Treat an enum type as its underlying type.
5971 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5972 Ty = EnumTy->getDecl()->getIntegerType();
5973
Daniel Sanders5b445b32014-10-24 14:42:42 +00005974 // All integral types are promoted to the GPR width.
5975 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005976 return ABIArgInfo::getExtend();
5977
Akira Hatanakaddd66342013-10-29 18:41:15 +00005978 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005979 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005980}
5981
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005982llvm::Type*
5983MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005984 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005985 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005986
Akira Hatanakab6f74432012-02-09 18:49:26 +00005987 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005988 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005989 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5990 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005991
Akira Hatanakab6f74432012-02-09 18:49:26 +00005992 // N32/64 returns struct/classes in floating point registers if the
5993 // following conditions are met:
5994 // 1. The size of the struct/class is no larger than 128-bit.
5995 // 2. The struct/class has one or two fields all of which are floating
5996 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005997 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00005998 //
5999 // Any other composite results are returned in integer registers.
6000 //
6001 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6002 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6003 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00006004 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006005
Akira Hatanakab6f74432012-02-09 18:49:26 +00006006 if (!BT || !BT->isFloatingPoint())
6007 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006008
David Blaikie2d7c57e2012-04-30 02:36:29 +00006009 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00006010 }
6011
6012 if (b == e)
6013 return llvm::StructType::get(getVMContext(), RTList,
6014 RD->hasAttr<PackedAttr>());
6015
6016 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006017 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006018 }
6019
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00006020 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006021 return llvm::StructType::get(getVMContext(), RTList);
6022}
6023
Akira Hatanakab579fe52011-06-02 00:09:17 +00006024ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00006025 uint64_t Size = getContext().getTypeSize(RetTy);
6026
Daniel Sandersed39f582014-09-04 13:28:14 +00006027 if (RetTy->isVoidType())
6028 return ABIArgInfo::getIgnore();
6029
6030 // O32 doesn't treat zero-sized structs differently from other structs.
6031 // However, N32/N64 ignores zero sized return values.
6032 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00006033 return ABIArgInfo::getIgnore();
6034
Akira Hatanakac37eddf2012-05-11 21:01:17 +00006035 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006036 if (Size <= 128) {
6037 if (RetTy->isAnyComplexType())
6038 return ABIArgInfo::getDirect();
6039
Daniel Sanderse5018b62014-09-04 15:05:39 +00006040 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006041 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006042 if (!IsO32 ||
6043 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6044 ABIArgInfo ArgInfo =
6045 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6046 ArgInfo.setInReg(true);
6047 return ArgInfo;
6048 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006049 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006050
John McCall7f416cc2015-09-08 08:05:57 +00006051 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006052 }
6053
6054 // Treat an enum type as its underlying type.
6055 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6056 RetTy = EnumTy->getDecl()->getIntegerType();
6057
6058 return (RetTy->isPromotableIntegerType() ?
6059 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6060}
6061
6062void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006063 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006064 if (!getCXXABI().classifyReturnType(FI))
6065 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006066
Eric Christopher7565e0d2015-05-29 23:09:49 +00006067 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006068 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006069
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006070 for (auto &I : FI.arguments())
6071 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006072}
6073
John McCall7f416cc2015-09-08 08:05:57 +00006074Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6075 QualType OrigTy) const {
6076 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006077
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006078 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6079 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006080 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006081 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006082 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006083 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006084 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006085 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006086 DidPromote = true;
6087 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6088 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006089 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006090
John McCall7f416cc2015-09-08 08:05:57 +00006091 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006092
John McCall7f416cc2015-09-08 08:05:57 +00006093 // The alignment of things in the argument area is never larger than
6094 // StackAlignInBytes.
6095 TyInfo.second =
6096 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6097
6098 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6099 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6100
6101 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6102 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6103
6104
6105 // If there was a promotion, "unpromote" into a temporary.
6106 // TODO: can we just use a pointer into a subset of the original slot?
6107 if (DidPromote) {
6108 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6109 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6110
6111 // Truncate down to the right width.
6112 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6113 : CGF.IntPtrTy);
6114 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6115 if (OrigTy->isPointerType())
6116 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6117
6118 CGF.Builder.CreateStore(V, Temp);
6119 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006120 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006121
John McCall7f416cc2015-09-08 08:05:57 +00006122 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006123}
6124
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006125bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6126 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006127
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006128 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6129 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6130 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006131
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006132 return false;
6133}
6134
John McCall943fae92010-05-27 06:19:26 +00006135bool
6136MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6137 llvm::Value *Address) const {
6138 // This information comes from gcc's implementation, which seems to
6139 // as canonical as it gets.
6140
John McCall943fae92010-05-27 06:19:26 +00006141 // Everything on MIPS is 4 bytes. Double-precision FP registers
6142 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006143 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006144
6145 // 0-31 are the general purpose registers, $0 - $31.
6146 // 32-63 are the floating-point registers, $f0 - $f31.
6147 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6148 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006149 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006150
6151 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6152 // They are one bit wide and ignored here.
6153
6154 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6155 // (coprocessor 1 is the FP unit)
6156 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6157 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6158 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006159 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006160 return false;
6161}
6162
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006163//===----------------------------------------------------------------------===//
6164// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006165// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006166// handling.
6167//===----------------------------------------------------------------------===//
6168
6169namespace {
6170
6171class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6172public:
6173 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6174 : DefaultTargetCodeGenInfo(CGT) {}
6175
Eric Christopher162c91c2015-06-05 22:03:00 +00006176 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006177 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006178};
6179
Eric Christopher162c91c2015-06-05 22:03:00 +00006180void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006181 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006182 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006183 if (!FD) return;
6184
6185 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006186
David Blaikiebbafb8a2012-03-11 07:00:24 +00006187 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006188 if (FD->hasAttr<OpenCLKernelAttr>()) {
6189 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006190 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006191 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6192 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006193 // Convert the reqd_work_group_size() attributes to metadata.
6194 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006195 llvm::NamedMDNode *OpenCLMetadata =
6196 M.getModule().getOrInsertNamedMetadata(
6197 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006198
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006199 SmallVector<llvm::Metadata *, 5> Operands;
6200 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006201
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006202 Operands.push_back(
6203 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6204 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6205 Operands.push_back(
6206 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6207 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6208 Operands.push_back(
6209 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6210 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006211
Eric Christopher7565e0d2015-05-29 23:09:49 +00006212 // Add a boolean constant operand for "required" (true) or "hint"
6213 // (false) for implementing the work_group_size_hint attr later.
6214 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006215 Operands.push_back(
6216 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006217 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6218 }
6219 }
6220 }
6221}
6222
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006223}
John McCall943fae92010-05-27 06:19:26 +00006224
Tony Linthicum76329bf2011-12-12 21:14:55 +00006225//===----------------------------------------------------------------------===//
6226// Hexagon ABI Implementation
6227//===----------------------------------------------------------------------===//
6228
6229namespace {
6230
6231class HexagonABIInfo : public ABIInfo {
6232
6233
6234public:
6235 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6236
6237private:
6238
6239 ABIArgInfo classifyReturnType(QualType RetTy) const;
6240 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6241
Craig Topper4f12f102014-03-12 06:41:41 +00006242 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006243
John McCall7f416cc2015-09-08 08:05:57 +00006244 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6245 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006246};
6247
6248class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6249public:
6250 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6251 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6252
Craig Topper4f12f102014-03-12 06:41:41 +00006253 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006254 return 29;
6255 }
6256};
6257
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006258}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006259
6260void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006261 if (!getCXXABI().classifyReturnType(FI))
6262 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006263 for (auto &I : FI.arguments())
6264 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006265}
6266
6267ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6268 if (!isAggregateTypeForABI(Ty)) {
6269 // Treat an enum type as its underlying type.
6270 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6271 Ty = EnumTy->getDecl()->getIntegerType();
6272
6273 return (Ty->isPromotableIntegerType() ?
6274 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6275 }
6276
6277 // Ignore empty records.
6278 if (isEmptyRecord(getContext(), Ty, true))
6279 return ABIArgInfo::getIgnore();
6280
Mark Lacey3825e832013-10-06 01:33:34 +00006281 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006282 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006283
6284 uint64_t Size = getContext().getTypeSize(Ty);
6285 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006286 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006287 // Pass in the smallest viable integer type.
6288 else if (Size > 32)
6289 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6290 else if (Size > 16)
6291 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6292 else if (Size > 8)
6293 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6294 else
6295 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6296}
6297
6298ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6299 if (RetTy->isVoidType())
6300 return ABIArgInfo::getIgnore();
6301
6302 // Large vector types should be returned via memory.
6303 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006304 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006305
6306 if (!isAggregateTypeForABI(RetTy)) {
6307 // Treat an enum type as its underlying type.
6308 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6309 RetTy = EnumTy->getDecl()->getIntegerType();
6310
6311 return (RetTy->isPromotableIntegerType() ?
6312 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6313 }
6314
Tony Linthicum76329bf2011-12-12 21:14:55 +00006315 if (isEmptyRecord(getContext(), RetTy, true))
6316 return ABIArgInfo::getIgnore();
6317
6318 // Aggregates <= 8 bytes are returned in r0; other aggregates
6319 // are returned indirectly.
6320 uint64_t Size = getContext().getTypeSize(RetTy);
6321 if (Size <= 64) {
6322 // Return in the smallest viable integer type.
6323 if (Size <= 8)
6324 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6325 if (Size <= 16)
6326 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6327 if (Size <= 32)
6328 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6329 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6330 }
6331
John McCall7f416cc2015-09-08 08:05:57 +00006332 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006333}
6334
John McCall7f416cc2015-09-08 08:05:57 +00006335Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6336 QualType Ty) const {
6337 // FIXME: Someone needs to audit that this handle alignment correctly.
6338 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6339 getContext().getTypeInfoInChars(Ty),
6340 CharUnits::fromQuantity(4),
6341 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006342}
6343
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006344//===----------------------------------------------------------------------===//
6345// AMDGPU ABI Implementation
6346//===----------------------------------------------------------------------===//
6347
6348namespace {
6349
6350class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6351public:
6352 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6353 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006354 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006355 CodeGen::CodeGenModule &M) const override;
6356};
6357
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006358}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006359
Eric Christopher162c91c2015-06-05 22:03:00 +00006360void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006361 const Decl *D,
6362 llvm::GlobalValue *GV,
6363 CodeGen::CodeGenModule &M) const {
Akira Hatanakaaec6b2c2015-10-08 20:26:34 +00006364 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006365 if (!FD)
6366 return;
6367
6368 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6369 llvm::Function *F = cast<llvm::Function>(GV);
6370 uint32_t NumVGPR = Attr->getNumVGPR();
6371 if (NumVGPR != 0)
6372 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6373 }
6374
6375 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6376 llvm::Function *F = cast<llvm::Function>(GV);
6377 unsigned NumSGPR = Attr->getNumSGPR();
6378 if (NumSGPR != 0)
6379 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6380 }
6381}
6382
Tony Linthicum76329bf2011-12-12 21:14:55 +00006383
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006384//===----------------------------------------------------------------------===//
6385// SPARC v9 ABI Implementation.
6386// Based on the SPARC Compliance Definition version 2.4.1.
6387//
6388// Function arguments a mapped to a nominal "parameter array" and promoted to
6389// registers depending on their type. Each argument occupies 8 or 16 bytes in
6390// the array, structs larger than 16 bytes are passed indirectly.
6391//
6392// One case requires special care:
6393//
6394// struct mixed {
6395// int i;
6396// float f;
6397// };
6398//
6399// When a struct mixed is passed by value, it only occupies 8 bytes in the
6400// parameter array, but the int is passed in an integer register, and the float
6401// is passed in a floating point register. This is represented as two arguments
6402// with the LLVM IR inreg attribute:
6403//
6404// declare void f(i32 inreg %i, float inreg %f)
6405//
6406// The code generator will only allocate 4 bytes from the parameter array for
6407// the inreg arguments. All other arguments are allocated a multiple of 8
6408// bytes.
6409//
6410namespace {
6411class SparcV9ABIInfo : public ABIInfo {
6412public:
6413 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6414
6415private:
6416 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006417 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006418 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6419 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006420
6421 // Coercion type builder for structs passed in registers. The coercion type
6422 // serves two purposes:
6423 //
6424 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6425 // in registers.
6426 // 2. Expose aligned floating point elements as first-level elements, so the
6427 // code generator knows to pass them in floating point registers.
6428 //
6429 // We also compute the InReg flag which indicates that the struct contains
6430 // aligned 32-bit floats.
6431 //
6432 struct CoerceBuilder {
6433 llvm::LLVMContext &Context;
6434 const llvm::DataLayout &DL;
6435 SmallVector<llvm::Type*, 8> Elems;
6436 uint64_t Size;
6437 bool InReg;
6438
6439 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6440 : Context(c), DL(dl), Size(0), InReg(false) {}
6441
6442 // Pad Elems with integers until Size is ToSize.
6443 void pad(uint64_t ToSize) {
6444 assert(ToSize >= Size && "Cannot remove elements");
6445 if (ToSize == Size)
6446 return;
6447
6448 // Finish the current 64-bit word.
6449 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6450 if (Aligned > Size && Aligned <= ToSize) {
6451 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6452 Size = Aligned;
6453 }
6454
6455 // Add whole 64-bit words.
6456 while (Size + 64 <= ToSize) {
6457 Elems.push_back(llvm::Type::getInt64Ty(Context));
6458 Size += 64;
6459 }
6460
6461 // Final in-word padding.
6462 if (Size < ToSize) {
6463 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6464 Size = ToSize;
6465 }
6466 }
6467
6468 // Add a floating point element at Offset.
6469 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6470 // Unaligned floats are treated as integers.
6471 if (Offset % Bits)
6472 return;
6473 // The InReg flag is only required if there are any floats < 64 bits.
6474 if (Bits < 64)
6475 InReg = true;
6476 pad(Offset);
6477 Elems.push_back(Ty);
6478 Size = Offset + Bits;
6479 }
6480
6481 // Add a struct type to the coercion type, starting at Offset (in bits).
6482 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6483 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6484 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6485 llvm::Type *ElemTy = StrTy->getElementType(i);
6486 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6487 switch (ElemTy->getTypeID()) {
6488 case llvm::Type::StructTyID:
6489 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6490 break;
6491 case llvm::Type::FloatTyID:
6492 addFloat(ElemOffset, ElemTy, 32);
6493 break;
6494 case llvm::Type::DoubleTyID:
6495 addFloat(ElemOffset, ElemTy, 64);
6496 break;
6497 case llvm::Type::FP128TyID:
6498 addFloat(ElemOffset, ElemTy, 128);
6499 break;
6500 case llvm::Type::PointerTyID:
6501 if (ElemOffset % 64 == 0) {
6502 pad(ElemOffset);
6503 Elems.push_back(ElemTy);
6504 Size += 64;
6505 }
6506 break;
6507 default:
6508 break;
6509 }
6510 }
6511 }
6512
6513 // Check if Ty is a usable substitute for the coercion type.
6514 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006515 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006516 }
6517
6518 // Get the coercion type as a literal struct type.
6519 llvm::Type *getType() const {
6520 if (Elems.size() == 1)
6521 return Elems.front();
6522 else
6523 return llvm::StructType::get(Context, Elems);
6524 }
6525 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006526};
6527} // end anonymous namespace
6528
6529ABIArgInfo
6530SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6531 if (Ty->isVoidType())
6532 return ABIArgInfo::getIgnore();
6533
6534 uint64_t Size = getContext().getTypeSize(Ty);
6535
6536 // Anything too big to fit in registers is passed with an explicit indirect
6537 // pointer / sret pointer.
6538 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006539 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006540
6541 // Treat an enum type as its underlying type.
6542 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6543 Ty = EnumTy->getDecl()->getIntegerType();
6544
6545 // Integer types smaller than a register are extended.
6546 if (Size < 64 && Ty->isIntegerType())
6547 return ABIArgInfo::getExtend();
6548
6549 // Other non-aggregates go in registers.
6550 if (!isAggregateTypeForABI(Ty))
6551 return ABIArgInfo::getDirect();
6552
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006553 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6554 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6555 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006556 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006557
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006558 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006559 // Build a coercion type from the LLVM struct type.
6560 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6561 if (!StrTy)
6562 return ABIArgInfo::getDirect();
6563
6564 CoerceBuilder CB(getVMContext(), getDataLayout());
6565 CB.addStruct(0, StrTy);
6566 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6567
6568 // Try to use the original type for coercion.
6569 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6570
6571 if (CB.InReg)
6572 return ABIArgInfo::getDirectInReg(CoerceTy);
6573 else
6574 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006575}
6576
John McCall7f416cc2015-09-08 08:05:57 +00006577Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6578 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006579 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6580 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6581 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6582 AI.setCoerceToType(ArgTy);
6583
John McCall7f416cc2015-09-08 08:05:57 +00006584 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006585
John McCall7f416cc2015-09-08 08:05:57 +00006586 CGBuilderTy &Builder = CGF.Builder;
6587 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6588 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6589
6590 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6591
6592 Address ArgAddr = Address::invalid();
6593 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006594 switch (AI.getKind()) {
6595 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006596 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006597 llvm_unreachable("Unsupported ABI kind for va_arg");
6598
John McCall7f416cc2015-09-08 08:05:57 +00006599 case ABIArgInfo::Extend: {
6600 Stride = SlotSize;
6601 CharUnits Offset = SlotSize - TypeInfo.first;
6602 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006603 break;
John McCall7f416cc2015-09-08 08:05:57 +00006604 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006605
John McCall7f416cc2015-09-08 08:05:57 +00006606 case ABIArgInfo::Direct: {
6607 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6608 Stride = CharUnits::fromQuantity(AllocSize).RoundUpToAlignment(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006609 ArgAddr = Addr;
6610 break;
John McCall7f416cc2015-09-08 08:05:57 +00006611 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006612
6613 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006614 Stride = SlotSize;
6615 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6616 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6617 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006618 break;
6619
6620 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006621 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006622 }
6623
6624 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006625 llvm::Value *NextPtr =
6626 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6627 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006628
John McCall7f416cc2015-09-08 08:05:57 +00006629 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006630}
6631
6632void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6633 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006634 for (auto &I : FI.arguments())
6635 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006636}
6637
6638namespace {
6639class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6640public:
6641 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6642 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006643
Craig Topper4f12f102014-03-12 06:41:41 +00006644 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006645 return 14;
6646 }
6647
6648 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006649 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006650};
6651} // end anonymous namespace
6652
Roman Divackyf02c9942014-02-24 18:46:27 +00006653bool
6654SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6655 llvm::Value *Address) const {
6656 // This is calculated from the LLVM and GCC tables and verified
6657 // against gcc output. AFAIK all ABIs use the same encoding.
6658
6659 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6660
6661 llvm::IntegerType *i8 = CGF.Int8Ty;
6662 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6663 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6664
6665 // 0-31: the 8-byte general-purpose registers
6666 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6667
6668 // 32-63: f0-31, the 4-byte floating-point registers
6669 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6670
6671 // Y = 64
6672 // PSR = 65
6673 // WIM = 66
6674 // TBR = 67
6675 // PC = 68
6676 // NPC = 69
6677 // FSR = 70
6678 // CSR = 71
6679 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006680
Roman Divackyf02c9942014-02-24 18:46:27 +00006681 // 72-87: d0-15, the 8-byte floating-point registers
6682 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6683
6684 return false;
6685}
6686
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006687
Robert Lytton0e076492013-08-13 09:43:10 +00006688//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006689// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006690//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006691
Robert Lytton0e076492013-08-13 09:43:10 +00006692namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006693
6694/// A SmallStringEnc instance is used to build up the TypeString by passing
6695/// it by reference between functions that append to it.
6696typedef llvm::SmallString<128> SmallStringEnc;
6697
6698/// TypeStringCache caches the meta encodings of Types.
6699///
6700/// The reason for caching TypeStrings is two fold:
6701/// 1. To cache a type's encoding for later uses;
6702/// 2. As a means to break recursive member type inclusion.
6703///
6704/// A cache Entry can have a Status of:
6705/// NonRecursive: The type encoding is not recursive;
6706/// Recursive: The type encoding is recursive;
6707/// Incomplete: An incomplete TypeString;
6708/// IncompleteUsed: An incomplete TypeString that has been used in a
6709/// Recursive type encoding.
6710///
6711/// A NonRecursive entry will have all of its sub-members expanded as fully
6712/// as possible. Whilst it may contain types which are recursive, the type
6713/// itself is not recursive and thus its encoding may be safely used whenever
6714/// the type is encountered.
6715///
6716/// A Recursive entry will have all of its sub-members expanded as fully as
6717/// possible. The type itself is recursive and it may contain other types which
6718/// are recursive. The Recursive encoding must not be used during the expansion
6719/// of a recursive type's recursive branch. For simplicity the code uses
6720/// IncompleteCount to reject all usage of Recursive encodings for member types.
6721///
6722/// An Incomplete entry is always a RecordType and only encodes its
6723/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6724/// are placed into the cache during type expansion as a means to identify and
6725/// handle recursive inclusion of types as sub-members. If there is recursion
6726/// the entry becomes IncompleteUsed.
6727///
6728/// During the expansion of a RecordType's members:
6729///
6730/// If the cache contains a NonRecursive encoding for the member type, the
6731/// cached encoding is used;
6732///
6733/// If the cache contains a Recursive encoding for the member type, the
6734/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6735///
6736/// If the member is a RecordType, an Incomplete encoding is placed into the
6737/// cache to break potential recursive inclusion of itself as a sub-member;
6738///
6739/// Once a member RecordType has been expanded, its temporary incomplete
6740/// entry is removed from the cache. If a Recursive encoding was swapped out
6741/// it is swapped back in;
6742///
6743/// If an incomplete entry is used to expand a sub-member, the incomplete
6744/// entry is marked as IncompleteUsed. The cache keeps count of how many
6745/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6746///
6747/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6748/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6749/// Else the member is part of a recursive type and thus the recursion has
6750/// been exited too soon for the encoding to be correct for the member.
6751///
6752class TypeStringCache {
6753 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6754 struct Entry {
6755 std::string Str; // The encoded TypeString for the type.
6756 enum Status State; // Information about the encoding in 'Str'.
6757 std::string Swapped; // A temporary place holder for a Recursive encoding
6758 // during the expansion of RecordType's members.
6759 };
6760 std::map<const IdentifierInfo *, struct Entry> Map;
6761 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6762 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6763public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006764 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006765 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6766 bool removeIncomplete(const IdentifierInfo *ID);
6767 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6768 bool IsRecursive);
6769 StringRef lookupStr(const IdentifierInfo *ID);
6770};
6771
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006772/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006773/// FieldEncoding is a helper for this ordering process.
6774class FieldEncoding {
6775 bool HasName;
6776 std::string Enc;
6777public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006778 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6779 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006780 bool operator<(const FieldEncoding &rhs) const {
6781 if (HasName != rhs.HasName) return HasName;
6782 return Enc < rhs.Enc;
6783 }
6784};
6785
Robert Lytton7d1db152013-08-19 09:46:39 +00006786class XCoreABIInfo : public DefaultABIInfo {
6787public:
6788 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006789 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6790 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006791};
6792
Robert Lyttond21e2d72014-03-03 13:45:29 +00006793class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006794 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006795public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006796 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006797 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006798 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6799 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006800};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006801
Robert Lytton2d196952013-10-11 10:29:34 +00006802} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006803
John McCall7f416cc2015-09-08 08:05:57 +00006804Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6805 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006806 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006807
Robert Lytton2d196952013-10-11 10:29:34 +00006808 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006809 CharUnits SlotSize = CharUnits::fromQuantity(4);
6810 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006811
Robert Lytton2d196952013-10-11 10:29:34 +00006812 // Handle the argument.
6813 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006814 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006815 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6816 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6817 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006818 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006819
6820 Address Val = Address::invalid();
6821 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006822 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006823 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006824 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006825 llvm_unreachable("Unsupported ABI kind for va_arg");
6826 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006827 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6828 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006829 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006830 case ABIArgInfo::Extend:
6831 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006832 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6833 ArgSize = CharUnits::fromQuantity(
6834 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
6835 ArgSize = ArgSize.RoundUpToAlignment(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006836 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006837 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006838 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6839 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6840 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006841 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006842 }
Robert Lytton2d196952013-10-11 10:29:34 +00006843
6844 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006845 if (!ArgSize.isZero()) {
6846 llvm::Value *APN =
6847 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
6848 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006849 }
John McCall7f416cc2015-09-08 08:05:57 +00006850
Robert Lytton2d196952013-10-11 10:29:34 +00006851 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006852}
Robert Lytton0e076492013-08-13 09:43:10 +00006853
Robert Lytton844aeeb2014-05-02 09:33:20 +00006854/// During the expansion of a RecordType, an incomplete TypeString is placed
6855/// into the cache as a means to identify and break recursion.
6856/// If there is a Recursive encoding in the cache, it is swapped out and will
6857/// be reinserted by removeIncomplete().
6858/// All other types of encoding should have been used rather than arriving here.
6859void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6860 std::string StubEnc) {
6861 if (!ID)
6862 return;
6863 Entry &E = Map[ID];
6864 assert( (E.Str.empty() || E.State == Recursive) &&
6865 "Incorrectly use of addIncomplete");
6866 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6867 E.Swapped.swap(E.Str); // swap out the Recursive
6868 E.Str.swap(StubEnc);
6869 E.State = Incomplete;
6870 ++IncompleteCount;
6871}
6872
6873/// Once the RecordType has been expanded, the temporary incomplete TypeString
6874/// must be removed from the cache.
6875/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6876/// Returns true if the RecordType was defined recursively.
6877bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6878 if (!ID)
6879 return false;
6880 auto I = Map.find(ID);
6881 assert(I != Map.end() && "Entry not present");
6882 Entry &E = I->second;
6883 assert( (E.State == Incomplete ||
6884 E.State == IncompleteUsed) &&
6885 "Entry must be an incomplete type");
6886 bool IsRecursive = false;
6887 if (E.State == IncompleteUsed) {
6888 // We made use of our Incomplete encoding, thus we are recursive.
6889 IsRecursive = true;
6890 --IncompleteUsedCount;
6891 }
6892 if (E.Swapped.empty())
6893 Map.erase(I);
6894 else {
6895 // Swap the Recursive back.
6896 E.Swapped.swap(E.Str);
6897 E.Swapped.clear();
6898 E.State = Recursive;
6899 }
6900 --IncompleteCount;
6901 return IsRecursive;
6902}
6903
6904/// Add the encoded TypeString to the cache only if it is NonRecursive or
6905/// Recursive (viz: all sub-members were expanded as fully as possible).
6906void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6907 bool IsRecursive) {
6908 if (!ID || IncompleteUsedCount)
6909 return; // No key or it is is an incomplete sub-type so don't add.
6910 Entry &E = Map[ID];
6911 if (IsRecursive && !E.Str.empty()) {
6912 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6913 "This is not the same Recursive entry");
6914 // The parent container was not recursive after all, so we could have used
6915 // this Recursive sub-member entry after all, but we assumed the worse when
6916 // we started viz: IncompleteCount!=0.
6917 return;
6918 }
6919 assert(E.Str.empty() && "Entry already present");
6920 E.Str = Str.str();
6921 E.State = IsRecursive? Recursive : NonRecursive;
6922}
6923
6924/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6925/// are recursively expanding a type (IncompleteCount != 0) and the cached
6926/// encoding is Recursive, return an empty StringRef.
6927StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6928 if (!ID)
6929 return StringRef(); // We have no key.
6930 auto I = Map.find(ID);
6931 if (I == Map.end())
6932 return StringRef(); // We have no encoding.
6933 Entry &E = I->second;
6934 if (E.State == Recursive && IncompleteCount)
6935 return StringRef(); // We don't use Recursive encodings for member types.
6936
6937 if (E.State == Incomplete) {
6938 // The incomplete type is being used to break out of recursion.
6939 E.State = IncompleteUsed;
6940 ++IncompleteUsedCount;
6941 }
6942 return E.Str.c_str();
6943}
6944
6945/// The XCore ABI includes a type information section that communicates symbol
6946/// type information to the linker. The linker uses this information to verify
6947/// safety/correctness of things such as array bound and pointers et al.
6948/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6949/// This type information (TypeString) is emitted into meta data for all global
6950/// symbols: definitions, declarations, functions & variables.
6951///
6952/// The TypeString carries type, qualifier, name, size & value details.
6953/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00006954/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00006955/// The output is tested by test/CodeGen/xcore-stringtype.c.
6956///
6957static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6958 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6959
6960/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6961void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6962 CodeGen::CodeGenModule &CGM) const {
6963 SmallStringEnc Enc;
6964 if (getTypeString(Enc, D, CGM, TSC)) {
6965 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006966 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6967 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006968 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6969 llvm::NamedMDNode *MD =
6970 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6971 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6972 }
6973}
6974
6975static bool appendType(SmallStringEnc &Enc, QualType QType,
6976 const CodeGen::CodeGenModule &CGM,
6977 TypeStringCache &TSC);
6978
6979/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00006980/// Builds a SmallVector containing the encoded field types in declaration
6981/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006982static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6983 const RecordDecl *RD,
6984 const CodeGen::CodeGenModule &CGM,
6985 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006986 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006987 SmallStringEnc Enc;
6988 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006989 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006990 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006991 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006992 Enc += "b(";
6993 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00006994 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006995 Enc += ':';
6996 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006997 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006998 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006999 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00007000 Enc += ')';
7001 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00007002 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007003 }
7004 return true;
7005}
7006
7007/// Appends structure and union types to Enc and adds encoding to cache.
7008/// Recursively calls appendType (via extractFieldType) for each field.
7009/// Union types have their fields ordered according to the ABI.
7010static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
7011 const CodeGen::CodeGenModule &CGM,
7012 TypeStringCache &TSC, const IdentifierInfo *ID) {
7013 // Append the cached TypeString if we have one.
7014 StringRef TypeString = TSC.lookupStr(ID);
7015 if (!TypeString.empty()) {
7016 Enc += TypeString;
7017 return true;
7018 }
7019
7020 // Start to emit an incomplete TypeString.
7021 size_t Start = Enc.size();
7022 Enc += (RT->isUnionType()? 'u' : 's');
7023 Enc += '(';
7024 if (ID)
7025 Enc += ID->getName();
7026 Enc += "){";
7027
7028 // We collect all encoded fields and order as necessary.
7029 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007030 const RecordDecl *RD = RT->getDecl()->getDefinition();
7031 if (RD && !RD->field_empty()) {
7032 // An incomplete TypeString stub is placed in the cache for this RecordType
7033 // so that recursive calls to this RecordType will use it whilst building a
7034 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007035 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007036 std::string StubEnc(Enc.substr(Start).str());
7037 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7038 TSC.addIncomplete(ID, std::move(StubEnc));
7039 if (!extractFieldType(FE, RD, CGM, TSC)) {
7040 (void) TSC.removeIncomplete(ID);
7041 return false;
7042 }
7043 IsRecursive = TSC.removeIncomplete(ID);
7044 // The ABI requires unions to be sorted but not structures.
7045 // See FieldEncoding::operator< for sort algorithm.
7046 if (RT->isUnionType())
7047 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007048 // We can now complete the TypeString.
7049 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007050 for (unsigned I = 0; I != E; ++I) {
7051 if (I)
7052 Enc += ',';
7053 Enc += FE[I].str();
7054 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007055 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007056 Enc += '}';
7057 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7058 return true;
7059}
7060
7061/// Appends enum types to Enc and adds the encoding to the cache.
7062static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7063 TypeStringCache &TSC,
7064 const IdentifierInfo *ID) {
7065 // Append the cached TypeString if we have one.
7066 StringRef TypeString = TSC.lookupStr(ID);
7067 if (!TypeString.empty()) {
7068 Enc += TypeString;
7069 return true;
7070 }
7071
7072 size_t Start = Enc.size();
7073 Enc += "e(";
7074 if (ID)
7075 Enc += ID->getName();
7076 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007077
7078 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007079 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007080 SmallVector<FieldEncoding, 16> FE;
7081 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7082 ++I) {
7083 SmallStringEnc EnumEnc;
7084 EnumEnc += "m(";
7085 EnumEnc += I->getName();
7086 EnumEnc += "){";
7087 I->getInitVal().toString(EnumEnc);
7088 EnumEnc += '}';
7089 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7090 }
7091 std::sort(FE.begin(), FE.end());
7092 unsigned E = FE.size();
7093 for (unsigned I = 0; I != E; ++I) {
7094 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007095 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007096 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007097 }
7098 }
7099 Enc += '}';
7100 TSC.addIfComplete(ID, Enc.substr(Start), false);
7101 return true;
7102}
7103
7104/// Appends type's qualifier to Enc.
7105/// This is done prior to appending the type's encoding.
7106static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7107 // Qualifiers are emitted in alphabetical order.
Craig Topper273dbc62015-10-18 05:29:26 +00007108 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
Robert Lytton844aeeb2014-05-02 09:33:20 +00007109 int Lookup = 0;
7110 if (QT.isConstQualified())
7111 Lookup += 1<<0;
7112 if (QT.isRestrictQualified())
7113 Lookup += 1<<1;
7114 if (QT.isVolatileQualified())
7115 Lookup += 1<<2;
7116 Enc += Table[Lookup];
7117}
7118
7119/// Appends built-in types to Enc.
7120static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7121 const char *EncType;
7122 switch (BT->getKind()) {
7123 case BuiltinType::Void:
7124 EncType = "0";
7125 break;
7126 case BuiltinType::Bool:
7127 EncType = "b";
7128 break;
7129 case BuiltinType::Char_U:
7130 EncType = "uc";
7131 break;
7132 case BuiltinType::UChar:
7133 EncType = "uc";
7134 break;
7135 case BuiltinType::SChar:
7136 EncType = "sc";
7137 break;
7138 case BuiltinType::UShort:
7139 EncType = "us";
7140 break;
7141 case BuiltinType::Short:
7142 EncType = "ss";
7143 break;
7144 case BuiltinType::UInt:
7145 EncType = "ui";
7146 break;
7147 case BuiltinType::Int:
7148 EncType = "si";
7149 break;
7150 case BuiltinType::ULong:
7151 EncType = "ul";
7152 break;
7153 case BuiltinType::Long:
7154 EncType = "sl";
7155 break;
7156 case BuiltinType::ULongLong:
7157 EncType = "ull";
7158 break;
7159 case BuiltinType::LongLong:
7160 EncType = "sll";
7161 break;
7162 case BuiltinType::Float:
7163 EncType = "ft";
7164 break;
7165 case BuiltinType::Double:
7166 EncType = "d";
7167 break;
7168 case BuiltinType::LongDouble:
7169 EncType = "ld";
7170 break;
7171 default:
7172 return false;
7173 }
7174 Enc += EncType;
7175 return true;
7176}
7177
7178/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7179static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7180 const CodeGen::CodeGenModule &CGM,
7181 TypeStringCache &TSC) {
7182 Enc += "p(";
7183 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7184 return false;
7185 Enc += ')';
7186 return true;
7187}
7188
7189/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007190static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7191 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007192 const CodeGen::CodeGenModule &CGM,
7193 TypeStringCache &TSC, StringRef NoSizeEnc) {
7194 if (AT->getSizeModifier() != ArrayType::Normal)
7195 return false;
7196 Enc += "a(";
7197 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7198 CAT->getSize().toStringUnsigned(Enc);
7199 else
7200 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7201 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007202 // The Qualifiers should be attached to the type rather than the array.
7203 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007204 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7205 return false;
7206 Enc += ')';
7207 return true;
7208}
7209
7210/// Appends a function encoding to Enc, calling appendType for the return type
7211/// and the arguments.
7212static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7213 const CodeGen::CodeGenModule &CGM,
7214 TypeStringCache &TSC) {
7215 Enc += "f{";
7216 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7217 return false;
7218 Enc += "}(";
7219 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7220 // N.B. we are only interested in the adjusted param types.
7221 auto I = FPT->param_type_begin();
7222 auto E = FPT->param_type_end();
7223 if (I != E) {
7224 do {
7225 if (!appendType(Enc, *I, CGM, TSC))
7226 return false;
7227 ++I;
7228 if (I != E)
7229 Enc += ',';
7230 } while (I != E);
7231 if (FPT->isVariadic())
7232 Enc += ",va";
7233 } else {
7234 if (FPT->isVariadic())
7235 Enc += "va";
7236 else
7237 Enc += '0';
7238 }
7239 }
7240 Enc += ')';
7241 return true;
7242}
7243
7244/// Handles the type's qualifier before dispatching a call to handle specific
7245/// type encodings.
7246static bool appendType(SmallStringEnc &Enc, QualType QType,
7247 const CodeGen::CodeGenModule &CGM,
7248 TypeStringCache &TSC) {
7249
7250 QualType QT = QType.getCanonicalType();
7251
Robert Lytton6adb20f2014-06-05 09:06:21 +00007252 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7253 // The Qualifiers should be attached to the type rather than the array.
7254 // Thus we don't call appendQualifier() here.
7255 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7256
Robert Lytton844aeeb2014-05-02 09:33:20 +00007257 appendQualifier(Enc, QT);
7258
7259 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7260 return appendBuiltinType(Enc, BT);
7261
Robert Lytton844aeeb2014-05-02 09:33:20 +00007262 if (const PointerType *PT = QT->getAs<PointerType>())
7263 return appendPointerType(Enc, PT, CGM, TSC);
7264
7265 if (const EnumType *ET = QT->getAs<EnumType>())
7266 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7267
7268 if (const RecordType *RT = QT->getAsStructureType())
7269 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7270
7271 if (const RecordType *RT = QT->getAsUnionType())
7272 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7273
7274 if (const FunctionType *FT = QT->getAs<FunctionType>())
7275 return appendFunctionType(Enc, FT, CGM, TSC);
7276
7277 return false;
7278}
7279
7280static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7281 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7282 if (!D)
7283 return false;
7284
7285 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7286 if (FD->getLanguageLinkage() != CLanguageLinkage)
7287 return false;
7288 return appendType(Enc, FD->getType(), CGM, TSC);
7289 }
7290
7291 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7292 if (VD->getLanguageLinkage() != CLanguageLinkage)
7293 return false;
7294 QualType QT = VD->getType().getCanonicalType();
7295 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7296 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007297 // The Qualifiers should be attached to the type rather than the array.
7298 // Thus we don't call appendQualifier() here.
7299 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007300 }
7301 return appendType(Enc, QT, CGM, TSC);
7302 }
7303 return false;
7304}
7305
7306
Robert Lytton0e076492013-08-13 09:43:10 +00007307//===----------------------------------------------------------------------===//
7308// Driver code
7309//===----------------------------------------------------------------------===//
7310
Rafael Espindola9f834732014-09-19 01:54:22 +00007311const llvm::Triple &CodeGenModule::getTriple() const {
7312 return getTarget().getTriple();
7313}
7314
7315bool CodeGenModule::supportsCOMDAT() const {
7316 return !getTriple().isOSBinFormatMachO();
7317}
7318
Chris Lattner2b037972010-07-29 02:01:43 +00007319const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007320 if (TheTargetCodeGenInfo)
7321 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007322
John McCallc8e01702013-04-16 22:48:15 +00007323 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007324 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007325 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007326 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007327
Derek Schuff09338a22012-09-06 17:37:28 +00007328 case llvm::Triple::le32:
7329 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007330 case llvm::Triple::mips:
7331 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007332 if (Triple.getOS() == llvm::Triple::NaCl)
7333 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007334 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7335
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007336 case llvm::Triple::mips64:
7337 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007338 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7339
Tim Northover25e8a672014-05-24 12:51:25 +00007340 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007341 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007342 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007343 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007344 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007345
Tim Northover573cbee2014-05-24 12:52:07 +00007346 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007347 }
7348
Dan Gohmanc2853072015-09-03 22:51:53 +00007349 case llvm::Triple::wasm32:
7350 case llvm::Triple::wasm64:
7351 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7352
Daniel Dunbard59655c2009-09-12 00:59:49 +00007353 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007354 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007355 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007356 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007357 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007358 if (Triple.getOS() == llvm::Triple::Win32) {
7359 TheTargetCodeGenInfo =
7360 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7361 return *TheTargetCodeGenInfo;
7362 }
7363
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007364 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007365 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007366 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007367 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007368 (CodeGenOpts.FloatABI != "soft" &&
7369 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007370 Kind = ARMABIInfo::AAPCS_VFP;
7371
Derek Schuff71658bd2015-01-29 00:47:04 +00007372 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007373 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007374
John McCallea8d8bb2010-03-11 00:10:12 +00007375 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007376 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007377 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007378 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007379 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007380 if (getTarget().getABI() == "elfv2")
7381 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007382 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007383
Ulrich Weigandb7122372014-07-21 00:48:09 +00007384 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007385 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007386 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007387 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007388 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007389 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007390 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007391 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007392 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007393 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007394
Ulrich Weigandb7122372014-07-21 00:48:09 +00007395 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007396 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007397 }
John McCallea8d8bb2010-03-11 00:10:12 +00007398
Peter Collingbournec947aae2012-05-20 23:28:41 +00007399 case llvm::Triple::nvptx:
7400 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007401 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007402
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007403 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007404 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007405
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007406 case llvm::Triple::systemz: {
7407 bool HasVector = getTarget().getABI() == "vector";
7408 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7409 HasVector));
7410 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007411
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007412 case llvm::Triple::tce:
7413 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7414
Eli Friedman33465822011-07-08 23:31:17 +00007415 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007416 bool IsDarwinVectorABI = Triple.isOSDarwin();
Michael Kupersteindc745202015-10-19 07:52:25 +00007417 bool RetSmallStructInRegABI =
John McCall1fe2a8c2013-06-18 02:46:29 +00007418 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007419 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007420
John McCall1fe2a8c2013-06-18 02:46:29 +00007421 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007422 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007423 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Eric Christopher7565e0d2015-05-29 23:09:49 +00007424 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007425 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007426 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
Michael Kupersteindc745202015-10-19 07:52:25 +00007427 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
Michael Kupersteinb1ec50d2015-10-19 08:09:43 +00007428 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
7429 CodeGenOpts.FloatABI == "soft"));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007430 }
Eli Friedman33465822011-07-08 23:31:17 +00007431 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007432
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007433 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007434 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007435 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7436 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007437 X86AVXABILevel::None);
7438
Chris Lattner04dc9572010-08-31 16:44:54 +00007439 switch (Triple.getOS()) {
7440 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007441 return *(TheTargetCodeGenInfo =
7442 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007443 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007444 return *(TheTargetCodeGenInfo =
7445 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007446 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007447 return *(TheTargetCodeGenInfo =
7448 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007449 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007450 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007451 case llvm::Triple::hexagon:
7452 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007453 case llvm::Triple::r600:
7454 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007455 case llvm::Triple::amdgcn:
7456 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007457 case llvm::Triple::sparcv9:
7458 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007459 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007460 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007461 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007462}