blob: 07c706b49a9d03f73abfb76e25cf88dc0aa78eb8 [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
Anton Korobeynikov244360d2009-06-05 22:08:42 +000069ABIInfo::~ABIInfo() {}
70
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;
799 bool IsSmallStructInRegABI;
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000800 bool IsWin32StructABI;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000801 unsigned DefaultNumRegisterParameters;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000802
803 static bool isRegisterSize(unsigned Size) {
804 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
805 }
806
Reid Kleckner80944df2014-10-31 22:00:51 +0000807 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
808 // FIXME: Assumes vectorcall is in use.
809 return isX86VectorTypeForVectorCall(getContext(), Ty);
810 }
811
812 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
813 uint64_t NumMembers) const override {
814 // FIXME: Assumes vectorcall is in use.
815 return isX86VectorCallAggregateSmallEnough(NumMembers);
816 }
817
Reid Kleckner40ca9132014-05-13 22:05:45 +0000818 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000819
Daniel Dunbar557893d2010-04-21 19:10:51 +0000820 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
821 /// such that the argument will be passed in memory.
Reid Kleckner661f35b2014-01-18 01:12:41 +0000822 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
823
John McCall7f416cc2015-09-08 08:05:57 +0000824 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
Daniel Dunbar557893d2010-04-21 19:10:51 +0000825
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000826 /// \brief Return the alignment to use for the given type on the stack.
Daniel Dunbardd38fbc2010-09-16 20:42:06 +0000827 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +0000828
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000829 Class classify(QualType Ty) const;
Reid Kleckner40ca9132014-05-13 22:05:45 +0000830 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
Reid Kleckner661f35b2014-01-18 01:12:41 +0000831 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
832 bool shouldUseInReg(QualType Ty, CCState &State, bool &NeedsPadding) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000833
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000834 /// \brief Rewrite the function info so that all memory arguments use
835 /// inalloca.
836 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
837
838 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +0000839 CharUnits &StackOffset, ABIArgInfo &Info,
Reid Kleckner314ef7b2014-02-01 00:04:45 +0000840 QualType Type) const;
841
Rafael Espindola75419dc2012-07-23 23:30:29 +0000842public:
843
Craig Topper4f12f102014-03-12 06:41:41 +0000844 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +0000845 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
846 QualType Ty) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000847
Chad Rosier651c1832013-03-25 21:00:27 +0000848 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
Rafael Espindola06b2b4a2012-07-31 02:44:24 +0000849 unsigned r)
Eli Friedman33465822011-07-08 23:31:17 +0000850 : ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +0000851 IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000852};
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000853
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000854class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
855public:
Eli Friedmana98d1f82012-01-25 22:46:34 +0000856 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
Chad Rosier651c1832013-03-25 21:00:27 +0000857 bool d, bool p, bool w, unsigned r)
858 :TargetCodeGenInfo(new X86_32ABIInfo(CGT, d, p, w, r)) {}
Charles Davis4ea31ab2010-02-13 15:54:06 +0000859
John McCall1fe2a8c2013-06-18 02:46:29 +0000860 static bool isStructReturnInRegABI(
861 const llvm::Triple &Triple, const CodeGenOptions &Opts);
862
Eric Christopher162c91c2015-06-05 22:03:00 +0000863 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +0000864 CodeGen::CodeGenModule &CGM) const override;
John McCallbeec5a02010-03-06 00:35:14 +0000865
Craig Topper4f12f102014-03-12 06:41:41 +0000866 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +0000867 // Darwin uses different dwarf register numbers for EH.
John McCallc8e01702013-04-16 22:48:15 +0000868 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
John McCallbeec5a02010-03-06 00:35:14 +0000869 return 4;
870 }
871
872 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +0000873 llvm::Value *Address) const override;
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000874
Jay Foad7c57be32011-07-11 09:56:20 +0000875 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000876 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +0000877 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +0000878 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
879 }
880
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000881 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
882 std::string &Constraints,
883 std::vector<llvm::Type *> &ResultRegTypes,
884 std::vector<llvm::Type *> &ResultTruncRegTypes,
885 std::vector<LValue> &ResultRegDests,
886 std::string &AsmString,
887 unsigned NumOutputs) const override;
888
Craig Topper4f12f102014-03-12 06:41:41 +0000889 llvm::Constant *
890 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourneb453cd62013-10-20 21:29:19 +0000891 unsigned Sig = (0xeb << 0) | // jmp rel8
892 (0x06 << 8) | // .+0x08
893 ('F' << 16) |
894 ('T' << 24);
895 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
896 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +0000897};
898
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000899}
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000900
Reid Kleckner9b3e3df2014-09-04 20:04:38 +0000901/// Rewrite input constraint references after adding some output constraints.
902/// In the case where there is one output and one input and we add one output,
903/// we need to replace all operand references greater than or equal to 1:
904/// mov $0, $1
905/// mov eax, $1
906/// The result will be:
907/// mov $0, $2
908/// mov eax, $2
909static void rewriteInputConstraintReferences(unsigned FirstIn,
910 unsigned NumNewOuts,
911 std::string &AsmString) {
912 std::string Buf;
913 llvm::raw_string_ostream OS(Buf);
914 size_t Pos = 0;
915 while (Pos < AsmString.size()) {
916 size_t DollarStart = AsmString.find('$', Pos);
917 if (DollarStart == std::string::npos)
918 DollarStart = AsmString.size();
919 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
920 if (DollarEnd == std::string::npos)
921 DollarEnd = AsmString.size();
922 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
923 Pos = DollarEnd;
924 size_t NumDollars = DollarEnd - DollarStart;
925 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
926 // We have an operand reference.
927 size_t DigitStart = Pos;
928 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
929 if (DigitEnd == std::string::npos)
930 DigitEnd = AsmString.size();
931 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
932 unsigned OperandIndex;
933 if (!OperandStr.getAsInteger(10, OperandIndex)) {
934 if (OperandIndex >= FirstIn)
935 OperandIndex += NumNewOuts;
936 OS << OperandIndex;
937 } else {
938 OS << OperandStr;
939 }
940 Pos = DigitEnd;
941 }
942 }
943 AsmString = std::move(OS.str());
944}
945
946/// Add output constraints for EAX:EDX because they are return registers.
947void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
948 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
949 std::vector<llvm::Type *> &ResultRegTypes,
950 std::vector<llvm::Type *> &ResultTruncRegTypes,
951 std::vector<LValue> &ResultRegDests, std::string &AsmString,
952 unsigned NumOutputs) const {
953 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
954
955 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
956 // larger.
957 if (!Constraints.empty())
958 Constraints += ',';
959 if (RetWidth <= 32) {
960 Constraints += "={eax}";
961 ResultRegTypes.push_back(CGF.Int32Ty);
962 } else {
963 // Use the 'A' constraint for EAX:EDX.
964 Constraints += "=A";
965 ResultRegTypes.push_back(CGF.Int64Ty);
966 }
967
968 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
969 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
970 ResultTruncRegTypes.push_back(CoerceTy);
971
972 // Coerce the integer by bitcasting the return slot pointer.
973 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
974 CoerceTy->getPointerTo()));
975 ResultRegDests.push_back(ReturnSlot);
976
977 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
978}
979
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000980/// shouldReturnTypeInRegister - Determine if the given type should be
981/// passed in a register (for the Darwin ABI).
Reid Kleckner40ca9132014-05-13 22:05:45 +0000982bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
983 ASTContext &Context) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +0000984 uint64_t Size = Context.getTypeSize(Ty);
985
986 // Type must be register sized.
987 if (!isRegisterSize(Size))
988 return false;
989
990 if (Ty->isVectorType()) {
991 // 64- and 128- bit vectors inside structures are not returned in
992 // registers.
993 if (Size == 64 || Size == 128)
994 return false;
995
996 return true;
997 }
998
Daniel Dunbar4bd95c62010-05-15 00:00:30 +0000999 // If this is a builtin, pointer, enum, complex type, member pointer, or
1000 // member function pointer it is ok.
Daniel Dunbar6b45b672010-05-14 03:40:53 +00001001 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
Daniel Dunbarb3b1e532009-09-24 05:12:36 +00001002 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
Daniel Dunbar4bd95c62010-05-15 00:00:30 +00001003 Ty->isBlockPointerType() || Ty->isMemberPointerType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001004 return true;
1005
1006 // Arrays are treated like records.
1007 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
Reid Kleckner40ca9132014-05-13 22:05:45 +00001008 return shouldReturnTypeInRegister(AT->getElementType(), Context);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001009
1010 // Otherwise, it must be a record type.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001011 const RecordType *RT = Ty->getAs<RecordType>();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001012 if (!RT) return false;
1013
Anders Carlsson40446e82010-01-27 03:25:19 +00001014 // FIXME: Traverse bases here too.
1015
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001016 // Structure types are passed in register if all fields would be
1017 // passed in a register.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001018 for (const auto *FD : RT->getDecl()->fields()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001019 // Empty fields are ignored.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00001020 if (isEmptyField(Context, FD, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001021 continue;
1022
1023 // Check fields recursively.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001024 if (!shouldReturnTypeInRegister(FD->getType(), Context))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001025 return false;
1026 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001027 return true;
1028}
1029
John McCall7f416cc2015-09-08 08:05:57 +00001030ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001031 // If the return value is indirect, then the hidden argument is consuming one
1032 // integer register.
1033 if (State.FreeRegs) {
1034 --State.FreeRegs;
John McCall7f416cc2015-09-08 08:05:57 +00001035 return getNaturalAlignIndirectInReg(RetTy);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001036 }
John McCall7f416cc2015-09-08 08:05:57 +00001037 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
Reid Kleckner661f35b2014-01-18 01:12:41 +00001038}
1039
Eric Christopher7565e0d2015-05-29 23:09:49 +00001040ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1041 CCState &State) const {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001042 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001043 return ABIArgInfo::getIgnore();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001044
Reid Kleckner80944df2014-10-31 22:00:51 +00001045 const Type *Base = nullptr;
1046 uint64_t NumElts = 0;
1047 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1048 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1049 // The LLVM struct type for such an aggregate should lower properly.
1050 return ABIArgInfo::getDirect();
1051 }
1052
Chris Lattner458b2aa2010-07-29 02:16:43 +00001053 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001054 // On Darwin, some vectors are returned in registers.
David Chisnallde3a0692009-08-17 23:08:21 +00001055 if (IsDarwinVectorABI) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001056 uint64_t Size = getContext().getTypeSize(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001057
1058 // 128-bit vectors are a special case; they are returned in
1059 // registers and we need to make sure to pick a type the LLVM
1060 // backend will like.
1061 if (Size == 128)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001062 return ABIArgInfo::getDirect(llvm::VectorType::get(
Chris Lattner458b2aa2010-07-29 02:16:43 +00001063 llvm::Type::getInt64Ty(getVMContext()), 2));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001064
1065 // Always return in register if it fits in a general purpose
1066 // register, or if it is 64 bits and has a single element.
1067 if ((Size == 8 || Size == 16 || Size == 32) ||
1068 (Size == 64 && VT->getNumElements() == 1))
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001069 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Chris Lattner458b2aa2010-07-29 02:16:43 +00001070 Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001071
John McCall7f416cc2015-09-08 08:05:57 +00001072 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001073 }
1074
1075 return ABIArgInfo::getDirect();
Chris Lattner458b2aa2010-07-29 02:16:43 +00001076 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001077
John McCalla1dee5302010-08-22 10:59:02 +00001078 if (isAggregateTypeForABI(RetTy)) {
Anders Carlsson40446e82010-01-27 03:25:19 +00001079 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
Anders Carlsson5789c492009-10-20 22:07:59 +00001080 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001081 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00001082 return getIndirectReturnResult(RetTy, State);
Anders Carlsson5789c492009-10-20 22:07:59 +00001083 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001084
David Chisnallde3a0692009-08-17 23:08:21 +00001085 // If specified, structs and unions are always indirect.
1086 if (!IsSmallStructInRegABI && !RetTy->isAnyComplexType())
John McCall7f416cc2015-09-08 08:05:57 +00001087 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001088
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001089 // Small structures which are register sized are generally returned
1090 // in a register.
Reid Kleckner40ca9132014-05-13 22:05:45 +00001091 if (shouldReturnTypeInRegister(RetTy, getContext())) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00001092 uint64_t Size = getContext().getTypeSize(RetTy);
Eli Friedmanee945342011-11-18 01:25:50 +00001093
1094 // As a special-case, if the struct is a "single-element" struct, and
1095 // the field is of type "float" or "double", return it in a
Eli Friedmana98d1f82012-01-25 22:46:34 +00001096 // floating-point register. (MSVC does not apply this special case.)
1097 // We apply a similar transformation for pointer types to improve the
1098 // quality of the generated IR.
Eli Friedmanee945342011-11-18 01:25:50 +00001099 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001100 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
Eli Friedmana98d1f82012-01-25 22:46:34 +00001101 || SeltTy->hasPointerRepresentation())
Eli Friedmanee945342011-11-18 01:25:50 +00001102 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1103
1104 // FIXME: We should be able to narrow this integer in cases with dead
1105 // padding.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00001106 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001107 }
1108
John McCall7f416cc2015-09-08 08:05:57 +00001109 return getIndirectReturnResult(RetTy, State);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001110 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001111
Chris Lattner458b2aa2010-07-29 02:16:43 +00001112 // Treat an enum type as its underlying type.
1113 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1114 RetTy = EnumTy->getDecl()->getIntegerType();
1115
1116 return (RetTy->isPromotableIntegerType() ?
1117 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001118}
1119
Eli Friedman7919bea2012-06-05 19:40:46 +00001120static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1121 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1122}
1123
Daniel Dunbared23de32010-09-16 20:42:00 +00001124static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1125 const RecordType *RT = Ty->getAs<RecordType>();
1126 if (!RT)
1127 return 0;
1128 const RecordDecl *RD = RT->getDecl();
1129
1130 // If this is a C++ record, check the bases first.
1131 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00001132 for (const auto &I : CXXRD->bases())
1133 if (!isRecordWithSSEVectorType(Context, I.getType()))
Daniel Dunbared23de32010-09-16 20:42:00 +00001134 return false;
1135
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001136 for (const auto *i : RD->fields()) {
Daniel Dunbared23de32010-09-16 20:42:00 +00001137 QualType FT = i->getType();
1138
Eli Friedman7919bea2012-06-05 19:40:46 +00001139 if (isSSEVectorType(Context, FT))
Daniel Dunbared23de32010-09-16 20:42:00 +00001140 return true;
1141
1142 if (isRecordWithSSEVectorType(Context, FT))
1143 return true;
1144 }
1145
1146 return false;
1147}
1148
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001149unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1150 unsigned Align) const {
1151 // Otherwise, if the alignment is less than or equal to the minimum ABI
1152 // alignment, just use the default; the backend will handle this.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001153 if (Align <= MinABIStackAlignInBytes)
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001154 return 0; // Use default alignment.
1155
1156 // On non-Darwin, the stack type alignment is always 4.
1157 if (!IsDarwinVectorABI) {
1158 // Set explicit alignment, since we may need to realign the top.
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001159 return MinABIStackAlignInBytes;
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001160 }
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001161
Daniel Dunbared23de32010-09-16 20:42:00 +00001162 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
Eli Friedman7919bea2012-06-05 19:40:46 +00001163 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1164 isRecordWithSSEVectorType(getContext(), Ty)))
Daniel Dunbared23de32010-09-16 20:42:00 +00001165 return 16;
1166
1167 return MinABIStackAlignInBytes;
Daniel Dunbar8a6c91f2010-09-16 20:41:56 +00001168}
1169
Rafael Espindola703c47f2012-10-19 05:04:37 +00001170ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
Reid Kleckner661f35b2014-01-18 01:12:41 +00001171 CCState &State) const {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001172 if (!ByVal) {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001173 if (State.FreeRegs) {
1174 --State.FreeRegs; // Non-byval indirects just use one pointer.
John McCall7f416cc2015-09-08 08:05:57 +00001175 return getNaturalAlignIndirectInReg(Ty);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001176 }
John McCall7f416cc2015-09-08 08:05:57 +00001177 return getNaturalAlignIndirect(Ty, false);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001178 }
Daniel Dunbar53fac692010-04-21 19:49:55 +00001179
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001180 // Compute the byval alignment.
1181 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1182 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1183 if (StackAlign == 0)
John McCall7f416cc2015-09-08 08:05:57 +00001184 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
Daniel Dunbardd38fbc2010-09-16 20:42:06 +00001185
1186 // If the stack alignment is less than the type alignment, realign the
1187 // argument.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001188 bool Realign = TypeAlign > StackAlign;
John McCall7f416cc2015-09-08 08:05:57 +00001189 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1190 /*ByVal=*/true, Realign);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001191}
1192
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001193X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1194 const Type *T = isSingleElementStruct(Ty, getContext());
1195 if (!T)
1196 T = Ty.getTypePtr();
1197
1198 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1199 BuiltinType::Kind K = BT->getKind();
1200 if (K == BuiltinType::Float || K == BuiltinType::Double)
1201 return Float;
1202 }
1203 return Integer;
1204}
1205
Reid Kleckner661f35b2014-01-18 01:12:41 +00001206bool X86_32ABIInfo::shouldUseInReg(QualType Ty, CCState &State,
1207 bool &NeedsPadding) const {
Rafael Espindolafad28de2012-10-24 01:59:00 +00001208 NeedsPadding = false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001209 Class C = classify(Ty);
1210 if (C == Float)
Rafael Espindola703c47f2012-10-19 05:04:37 +00001211 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001212
Rafael Espindola077dd592012-10-24 01:58:58 +00001213 unsigned Size = getContext().getTypeSize(Ty);
1214 unsigned SizeInRegs = (Size + 31) / 32;
Rafael Espindolae2a9e902012-10-23 02:04:01 +00001215
1216 if (SizeInRegs == 0)
1217 return false;
1218
Reid Kleckner661f35b2014-01-18 01:12:41 +00001219 if (SizeInRegs > State.FreeRegs) {
1220 State.FreeRegs = 0;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001221 return false;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001222 }
Rafael Espindola703c47f2012-10-19 05:04:37 +00001223
Reid Kleckner661f35b2014-01-18 01:12:41 +00001224 State.FreeRegs -= SizeInRegs;
Rafael Espindola077dd592012-10-24 01:58:58 +00001225
Reid Kleckner80944df2014-10-31 22:00:51 +00001226 if (State.CC == llvm::CallingConv::X86_FastCall ||
1227 State.CC == llvm::CallingConv::X86_VectorCall) {
Rafael Espindola077dd592012-10-24 01:58:58 +00001228 if (Size > 32)
1229 return false;
1230
1231 if (Ty->isIntegralOrEnumerationType())
1232 return true;
1233
1234 if (Ty->isPointerType())
1235 return true;
1236
1237 if (Ty->isReferenceType())
1238 return true;
1239
Reid Kleckner661f35b2014-01-18 01:12:41 +00001240 if (State.FreeRegs)
Rafael Espindolafad28de2012-10-24 01:59:00 +00001241 NeedsPadding = true;
1242
Rafael Espindola077dd592012-10-24 01:58:58 +00001243 return false;
1244 }
1245
Rafael Espindola703c47f2012-10-19 05:04:37 +00001246 return true;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001247}
1248
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001249ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1250 CCState &State) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001251 // FIXME: Set alignment on indirect arguments.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001252
Reid Klecknerb1be6832014-11-15 01:41:41 +00001253 Ty = useFirstFieldIfTransparentUnion(Ty);
1254
Reid Kleckner80944df2014-10-31 22:00:51 +00001255 // Check with the C++ ABI first.
1256 const RecordType *RT = Ty->getAs<RecordType>();
1257 if (RT) {
1258 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1259 if (RAA == CGCXXABI::RAA_Indirect) {
1260 return getIndirectResult(Ty, false, State);
1261 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1262 // The field index doesn't matter, we'll fix it up later.
1263 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1264 }
1265 }
1266
1267 // vectorcall adds the concept of a homogenous vector aggregate, similar
1268 // to other targets.
1269 const Type *Base = nullptr;
1270 uint64_t NumElts = 0;
1271 if (State.CC == llvm::CallingConv::X86_VectorCall &&
1272 isHomogeneousAggregate(Ty, Base, NumElts)) {
1273 if (State.FreeSSERegs >= NumElts) {
1274 State.FreeSSERegs -= NumElts;
1275 if (Ty->isBuiltinType() || Ty->isVectorType())
1276 return ABIArgInfo::getDirect();
1277 return ABIArgInfo::getExpand();
1278 }
1279 return getIndirectResult(Ty, /*ByVal=*/false, State);
1280 }
1281
1282 if (isAggregateTypeForABI(Ty)) {
1283 if (RT) {
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001284 // Structs are always byval on win32, regardless of what they contain.
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001285 if (IsWin32StructABI)
Reid Kleckner661f35b2014-01-18 01:12:41 +00001286 return getIndirectResult(Ty, true, State);
Daniel Dunbar557893d2010-04-21 19:10:51 +00001287
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00001288 // Structures with flexible arrays are always indirect.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001289 if (RT->getDecl()->hasFlexibleArrayMember())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001290 return getIndirectResult(Ty, true, State);
Anders Carlsson40446e82010-01-27 03:25:19 +00001291 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001292
Eli Friedman9f061a32011-11-18 00:28:11 +00001293 // Ignore empty structs/unions.
Eli Friedmanf22fa9e2011-11-18 04:01:36 +00001294 if (isEmptyRecord(getContext(), Ty, true))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001295 return ABIArgInfo::getIgnore();
1296
Rafael Espindolafad28de2012-10-24 01:59:00 +00001297 llvm::LLVMContext &LLVMContext = getVMContext();
1298 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1299 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001300 if (shouldUseInReg(Ty, State, NeedsPadding)) {
Rafael Espindola703c47f2012-10-19 05:04:37 +00001301 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Craig Topperac9201a2013-07-08 04:47:18 +00001302 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001303 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1304 return ABIArgInfo::getDirectInReg(Result);
1305 }
Craig Topper8a13c412014-05-21 05:09:00 +00001306 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
Rafael Espindola703c47f2012-10-19 05:04:37 +00001307
Daniel Dunbar11c08c82009-11-09 01:33:53 +00001308 // Expand small (<= 128-bit) record types when we know that the stack layout
1309 // of those arguments will match the struct. This is important because the
1310 // LLVM backend isn't smart enough to remove byval, which inhibits many
1311 // optimizations.
Chris Lattner458b2aa2010-07-29 02:16:43 +00001312 if (getContext().getTypeSize(Ty) <= 4*32 &&
1313 canExpandIndirectArgument(Ty, getContext()))
Reid Kleckner661f35b2014-01-18 01:12:41 +00001314 return ABIArgInfo::getExpandWithPadding(
Reid Kleckner80944df2014-10-31 22:00:51 +00001315 State.CC == llvm::CallingConv::X86_FastCall ||
1316 State.CC == llvm::CallingConv::X86_VectorCall,
1317 PaddingType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001318
Reid Kleckner661f35b2014-01-18 01:12:41 +00001319 return getIndirectResult(Ty, true, State);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001320 }
1321
Chris Lattnerd774ae92010-08-26 20:05:13 +00001322 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattnerd7e54802010-08-26 20:08:43 +00001323 // On Darwin, some vectors are passed in memory, we handle this by passing
1324 // it as an i8/i16/i32/i64.
Chris Lattnerd774ae92010-08-26 20:05:13 +00001325 if (IsDarwinVectorABI) {
1326 uint64_t Size = getContext().getTypeSize(Ty);
Chris Lattnerd774ae92010-08-26 20:05:13 +00001327 if ((Size == 8 || Size == 16 || Size == 32) ||
1328 (Size == 64 && VT->getNumElements() == 1))
1329 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1330 Size));
Chris Lattnerd774ae92010-08-26 20:05:13 +00001331 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00001332
Chad Rosier651c1832013-03-25 21:00:27 +00001333 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1334 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001335
Chris Lattnerd774ae92010-08-26 20:05:13 +00001336 return ABIArgInfo::getDirect();
1337 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001338
1339
Chris Lattner458b2aa2010-07-29 02:16:43 +00001340 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1341 Ty = EnumTy->getDecl()->getIntegerType();
Douglas Gregora71cc152010-02-02 20:10:50 +00001342
Rafael Espindolafad28de2012-10-24 01:59:00 +00001343 bool NeedsPadding;
Reid Kleckner661f35b2014-01-18 01:12:41 +00001344 bool InReg = shouldUseInReg(Ty, State, NeedsPadding);
Rafael Espindola703c47f2012-10-19 05:04:37 +00001345
1346 if (Ty->isPromotableIntegerType()) {
1347 if (InReg)
1348 return ABIArgInfo::getExtendInReg();
1349 return ABIArgInfo::getExtend();
1350 }
1351 if (InReg)
1352 return ABIArgInfo::getDirectInReg();
1353 return ABIArgInfo::getDirect();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001354}
1355
Rafael Espindolaa6472962012-07-24 00:01:07 +00001356void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner661f35b2014-01-18 01:12:41 +00001357 CCState State(FI.getCallingConvention());
1358 if (State.CC == llvm::CallingConv::X86_FastCall)
1359 State.FreeRegs = 2;
Reid Kleckner80944df2014-10-31 22:00:51 +00001360 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1361 State.FreeRegs = 2;
1362 State.FreeSSERegs = 6;
1363 } else if (FI.getHasRegParm())
Reid Kleckner661f35b2014-01-18 01:12:41 +00001364 State.FreeRegs = FI.getRegParm();
Rafael Espindola077dd592012-10-24 01:58:58 +00001365 else
Reid Kleckner661f35b2014-01-18 01:12:41 +00001366 State.FreeRegs = DefaultNumRegisterParameters;
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001367
Reid Kleckner677539d2014-07-10 01:58:55 +00001368 if (!getCXXABI().classifyReturnType(FI)) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00001369 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
Reid Kleckner677539d2014-07-10 01:58:55 +00001370 } else if (FI.getReturnInfo().isIndirect()) {
1371 // The C++ ABI is not aware of register usage, so we have to check if the
1372 // return value was sret and put it in a register ourselves if appropriate.
1373 if (State.FreeRegs) {
1374 --State.FreeRegs; // The sret parameter consumes a register.
1375 FI.getReturnInfo().setInReg(true);
1376 }
1377 }
Rafael Espindola06b2b4a2012-07-31 02:44:24 +00001378
Peter Collingbournef7706832014-12-12 23:41:25 +00001379 // The chain argument effectively gives us another free register.
1380 if (FI.isChainCall())
1381 ++State.FreeRegs;
1382
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001383 bool UsedInAlloca = false;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00001384 for (auto &I : FI.arguments()) {
1385 I.info = classifyArgumentType(I.type, State);
1386 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001387 }
1388
1389 // If we needed to use inalloca for any argument, do a second pass and rewrite
1390 // all the memory arguments to use inalloca.
1391 if (UsedInAlloca)
1392 rewriteWithInAlloca(FI);
1393}
1394
1395void
1396X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001397 CharUnits &StackOffset, ABIArgInfo &Info,
1398 QualType Type) const {
1399 // Arguments are always 4-byte-aligned.
1400 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1401
1402 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
Reid Klecknerd378a712014-04-10 19:09:43 +00001403 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1404 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
John McCall7f416cc2015-09-08 08:05:57 +00001405 StackOffset += getContext().getTypeSizeInChars(Type);
Reid Klecknerd378a712014-04-10 19:09:43 +00001406
John McCall7f416cc2015-09-08 08:05:57 +00001407 // Insert padding bytes to respect alignment.
1408 CharUnits FieldEnd = StackOffset;
1409 StackOffset = FieldEnd.RoundUpToAlignment(FieldAlign);
1410 if (StackOffset != FieldEnd) {
1411 CharUnits NumBytes = StackOffset - FieldEnd;
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001412 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
John McCall7f416cc2015-09-08 08:05:57 +00001413 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001414 FrameFields.push_back(Ty);
1415 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001416}
1417
Reid Kleckner852361d2014-07-26 00:12:26 +00001418static bool isArgInAlloca(const ABIArgInfo &Info) {
1419 // Leave ignored and inreg arguments alone.
1420 switch (Info.getKind()) {
1421 case ABIArgInfo::InAlloca:
1422 return true;
1423 case ABIArgInfo::Indirect:
1424 assert(Info.getIndirectByVal());
1425 return true;
1426 case ABIArgInfo::Ignore:
1427 return false;
1428 case ABIArgInfo::Direct:
1429 case ABIArgInfo::Extend:
1430 case ABIArgInfo::Expand:
1431 if (Info.getInReg())
1432 return false;
1433 return true;
1434 }
1435 llvm_unreachable("invalid enum");
1436}
1437
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001438void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1439 assert(IsWin32StructABI && "inalloca only supported on win32");
1440
1441 // Build a packed struct type for all of the arguments in memory.
1442 SmallVector<llvm::Type *, 6> FrameFields;
1443
John McCall7f416cc2015-09-08 08:05:57 +00001444 // The stack alignment is always 4.
1445 CharUnits StackAlign = CharUnits::fromQuantity(4);
1446
1447 CharUnits StackOffset;
Reid Kleckner852361d2014-07-26 00:12:26 +00001448 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1449
1450 // Put 'this' into the struct before 'sret', if necessary.
1451 bool IsThisCall =
1452 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1453 ABIArgInfo &Ret = FI.getReturnInfo();
1454 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1455 isArgInAlloca(I->info)) {
1456 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1457 ++I;
1458 }
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001459
1460 // Put the sret parameter into the inalloca struct if it's in memory.
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001461 if (Ret.isIndirect() && !Ret.getInReg()) {
1462 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1463 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
Reid Klecknerfab1e892014-02-25 00:59:14 +00001464 // On Windows, the hidden sret parameter is always returned in eax.
1465 Ret.setInAllocaSRet(IsWin32StructABI);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001466 }
1467
1468 // Skip the 'this' parameter in ecx.
Reid Kleckner852361d2014-07-26 00:12:26 +00001469 if (IsThisCall)
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001470 ++I;
1471
1472 // Put arguments passed in memory into the struct.
1473 for (; I != E; ++I) {
Reid Kleckner852361d2014-07-26 00:12:26 +00001474 if (isArgInAlloca(I->info))
1475 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001476 }
1477
1478 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
John McCall7f416cc2015-09-08 08:05:57 +00001479 /*isPacked=*/true),
1480 StackAlign);
Rafael Espindolaa6472962012-07-24 00:01:07 +00001481}
1482
John McCall7f416cc2015-09-08 08:05:57 +00001483Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1484 Address VAListAddr, QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001485
John McCall7f416cc2015-09-08 08:05:57 +00001486 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001487
John McCall7f416cc2015-09-08 08:05:57 +00001488 // x86-32 changes the alignment of certain arguments on the stack.
1489 //
1490 // Just messing with TypeInfo like this works because we never pass
1491 // anything indirectly.
1492 TypeInfo.second = CharUnits::fromQuantity(
1493 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
Eli Friedman1d7dd3b2011-11-18 02:12:09 +00001494
John McCall7f416cc2015-09-08 08:05:57 +00001495 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1496 TypeInfo, CharUnits::fromQuantity(4),
1497 /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001498}
1499
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001500bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1501 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1502 assert(Triple.getArch() == llvm::Triple::x86);
1503
1504 switch (Opts.getStructReturnConvention()) {
1505 case CodeGenOptions::SRCK_Default:
1506 break;
1507 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1508 return false;
1509 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1510 return true;
1511 }
1512
1513 if (Triple.isOSDarwin())
1514 return true;
1515
1516 switch (Triple.getOS()) {
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001517 case llvm::Triple::DragonFly:
1518 case llvm::Triple::FreeBSD:
1519 case llvm::Triple::OpenBSD:
1520 case llvm::Triple::Bitrig:
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001521 case llvm::Triple::Win32:
Reid Kleckner2918fef2014-11-24 22:05:42 +00001522 return true;
Richard Sandiforddcb8d9c2014-07-08 11:10:34 +00001523 default:
1524 return false;
1525 }
1526}
1527
Eric Christopher162c91c2015-06-05 22:03:00 +00001528void X86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Charles Davis4ea31ab2010-02-13 15:54:06 +00001529 llvm::GlobalValue *GV,
1530 CodeGen::CodeGenModule &CGM) const {
1531 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1532 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1533 // Get the LLVM function.
1534 llvm::Function *Fn = cast<llvm::Function>(GV);
1535
1536 // Now add the 'alignstack' attribute with a value of 16.
Bill Wendlinga514ebc2012-10-15 20:36:26 +00001537 llvm::AttrBuilder B;
Bill Wendlingccf94c92012-10-14 03:28:14 +00001538 B.addStackAlignmentAttr(16);
Bill Wendling9a677922013-01-23 00:21:06 +00001539 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
1540 llvm::AttributeSet::get(CGM.getLLVMContext(),
1541 llvm::AttributeSet::FunctionIndex,
1542 B));
Charles Davis4ea31ab2010-02-13 15:54:06 +00001543 }
1544 }
1545}
1546
John McCallbeec5a02010-03-06 00:35:14 +00001547bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1548 CodeGen::CodeGenFunction &CGF,
1549 llvm::Value *Address) const {
1550 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallbeec5a02010-03-06 00:35:14 +00001551
Chris Lattnerece04092012-02-07 00:39:47 +00001552 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001553
John McCallbeec5a02010-03-06 00:35:14 +00001554 // 0-7 are the eight integer registers; the order is different
1555 // on Darwin (for EH), but the range is the same.
1556 // 8 is %eip.
John McCall943fae92010-05-27 06:19:26 +00001557 AssignToArrayRange(Builder, Address, Four8, 0, 8);
John McCallbeec5a02010-03-06 00:35:14 +00001558
John McCallc8e01702013-04-16 22:48:15 +00001559 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
John McCallbeec5a02010-03-06 00:35:14 +00001560 // 12-16 are st(0..4). Not sure why we stop at 4.
1561 // These have size 16, which is sizeof(long double) on
1562 // platforms with 8-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001563 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
John McCall943fae92010-05-27 06:19:26 +00001564 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001565
John McCallbeec5a02010-03-06 00:35:14 +00001566 } else {
1567 // 9 is %eflags, which doesn't get a size on Darwin for some
1568 // reason.
John McCall7f416cc2015-09-08 08:05:57 +00001569 Builder.CreateAlignedStore(
1570 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1571 CharUnits::One());
John McCallbeec5a02010-03-06 00:35:14 +00001572
1573 // 11-16 are st(0..5). Not sure why we stop at 5.
1574 // These have size 12, which is sizeof(long double) on
1575 // platforms with 4-byte alignment for that type.
Chris Lattnerece04092012-02-07 00:39:47 +00001576 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
John McCall943fae92010-05-27 06:19:26 +00001577 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1578 }
John McCallbeec5a02010-03-06 00:35:14 +00001579
1580 return false;
1581}
1582
Chris Lattner0cf24192010-06-28 20:05:43 +00001583//===----------------------------------------------------------------------===//
1584// X86-64 ABI Implementation
1585//===----------------------------------------------------------------------===//
1586
1587
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001588namespace {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001589/// The AVX ABI level for X86 targets.
1590enum class X86AVXABILevel {
1591 None,
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001592 AVX,
1593 AVX512
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001594};
1595
1596/// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
1597static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
1598 switch (AVXLevel) {
Ahmed Bougacha0b938282015-06-22 21:31:43 +00001599 case X86AVXABILevel::AVX512:
1600 return 512;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001601 case X86AVXABILevel::AVX:
1602 return 256;
1603 case X86AVXABILevel::None:
1604 return 128;
1605 }
Yaron Kerenb76cb042015-06-23 09:45:42 +00001606 llvm_unreachable("Unknown AVXLevel");
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001607}
1608
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001609/// X86_64ABIInfo - The X86_64 ABI information.
1610class X86_64ABIInfo : public ABIInfo {
1611 enum Class {
1612 Integer = 0,
1613 SSE,
1614 SSEUp,
1615 X87,
1616 X87Up,
1617 ComplexX87,
1618 NoClass,
1619 Memory
1620 };
1621
1622 /// merge - Implement the X86_64 ABI merging algorithm.
1623 ///
1624 /// Merge an accumulating classification \arg Accum with a field
1625 /// classification \arg Field.
1626 ///
1627 /// \param Accum - The accumulating classification. This should
1628 /// always be either NoClass or the result of a previous merge
1629 /// call. In addition, this should never be Memory (the caller
1630 /// should just return Memory for the aggregate).
Chris Lattnerd776fb12010-06-28 21:43:59 +00001631 static Class merge(Class Accum, Class Field);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001632
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001633 /// postMerge - Implement the X86_64 ABI post merging algorithm.
1634 ///
1635 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
1636 /// final MEMORY or SSE classes when necessary.
1637 ///
1638 /// \param AggregateSize - The size of the current aggregate in
1639 /// the classification process.
1640 ///
1641 /// \param Lo - The classification for the parts of the type
1642 /// residing in the low word of the containing object.
1643 ///
1644 /// \param Hi - The classification for the parts of the type
1645 /// residing in the higher words of the containing object.
1646 ///
1647 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
1648
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001649 /// classify - Determine the x86_64 register classes in which the
1650 /// given type T should be passed.
1651 ///
1652 /// \param Lo - The classification for the parts of the type
1653 /// residing in the low word of the containing object.
1654 ///
1655 /// \param Hi - The classification for the parts of the type
1656 /// residing in the high word of the containing object.
1657 ///
1658 /// \param OffsetBase - The bit offset of this type in the
1659 /// containing object. Some parameters are classified different
1660 /// depending on whether they straddle an eightbyte boundary.
1661 ///
Eli Friedman96fd2642013-06-12 00:13:45 +00001662 /// \param isNamedArg - Whether the argument in question is a "named"
1663 /// argument, as used in AMD64-ABI 3.5.7.
1664 ///
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001665 /// If a word is unused its result will be NoClass; if a type should
1666 /// be passed in Memory then at least the classification of \arg Lo
1667 /// will be Memory.
1668 ///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +00001669 /// The \arg Lo class will be NoClass iff the argument is ignored.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001670 ///
1671 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
1672 /// also be ComplexX87.
Eli Friedman96fd2642013-06-12 00:13:45 +00001673 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
1674 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001675
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001676 llvm::Type *GetByteVectorType(QualType Ty) const;
Chris Lattnera5f58b02011-07-09 17:41:47 +00001677 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
1678 unsigned IROffset, QualType SourceTy,
1679 unsigned SourceOffset) const;
1680 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
1681 unsigned IROffset, QualType SourceTy,
1682 unsigned SourceOffset) const;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001683
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001684 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Daniel Dunbar53fac692010-04-21 19:49:55 +00001685 /// such that the argument will be returned in memory.
Chris Lattner22a931e2010-06-29 06:01:59 +00001686 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
Daniel Dunbar53fac692010-04-21 19:49:55 +00001687
1688 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001689 /// such that the argument will be passed in memory.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001690 ///
1691 /// \param freeIntRegs - The number of free integer registers remaining
1692 /// available.
1693 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001694
Chris Lattner458b2aa2010-07-29 02:16:43 +00001695 ABIArgInfo classifyReturnType(QualType RetTy) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001696
Bill Wendling5cd41c42010-10-18 03:41:31 +00001697 ABIArgInfo classifyArgumentType(QualType Ty,
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001698 unsigned freeIntRegs,
Bill Wendling5cd41c42010-10-18 03:41:31 +00001699 unsigned &neededInt,
Eli Friedman96fd2642013-06-12 00:13:45 +00001700 unsigned &neededSSE,
1701 bool isNamedArg) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001702
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001703 bool IsIllegalVectorType(QualType Ty) const;
1704
John McCalle0fda732011-04-21 01:20:55 +00001705 /// The 0.98 ABI revision clarified a lot of ambiguities,
1706 /// unfortunately in ways that were not always consistent with
1707 /// certain previous compilers. In particular, platforms which
1708 /// required strict binary compatibility with older versions of GCC
1709 /// may need to exempt themselves.
1710 bool honorsRevision0_98() const {
John McCallc8e01702013-04-16 22:48:15 +00001711 return !getTarget().getTriple().isOSDarwin();
John McCalle0fda732011-04-21 01:20:55 +00001712 }
1713
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001714 X86AVXABILevel AVXLevel;
Derek Schuffc7dd7222012-10-11 15:52:22 +00001715 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
1716 // 64-bit hardware.
1717 bool Has64BitPointers;
Eli Friedmanbfd5add2011-12-02 00:11:43 +00001718
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001719public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001720 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
1721 ABIInfo(CGT), AVXLevel(AVXLevel),
Derek Schuff8a872f32012-10-11 18:21:13 +00001722 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
Derek Schuffc7dd7222012-10-11 15:52:22 +00001723 }
Chris Lattner22a931e2010-06-29 06:01:59 +00001724
John McCalla729c622012-02-17 03:33:10 +00001725 bool isPassedUsingAVXType(QualType type) const {
1726 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00001727 // The freeIntRegs argument doesn't matter here.
Eli Friedman96fd2642013-06-12 00:13:45 +00001728 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
1729 /*isNamedArg*/true);
John McCalla729c622012-02-17 03:33:10 +00001730 if (info.isDirect()) {
1731 llvm::Type *ty = info.getCoerceToType();
1732 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
1733 return (vectorTy->getBitWidth() > 128);
1734 }
1735 return false;
1736 }
1737
Craig Topper4f12f102014-03-12 06:41:41 +00001738 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001739
John McCall7f416cc2015-09-08 08:05:57 +00001740 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1741 QualType Ty) const override;
Charles Davisc7d5c942015-09-17 20:55:33 +00001742 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
1743 QualType Ty) const override;
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001744
1745 bool has64BitPointers() const {
1746 return Has64BitPointers;
1747 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001748};
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001749
Chris Lattner04dc9572010-08-31 16:44:54 +00001750/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001751class WinX86_64ABIInfo : public ABIInfo {
1752
Reid Kleckner80944df2014-10-31 22:00:51 +00001753 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs,
1754 bool IsReturnType) const;
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001755
Chris Lattner04dc9572010-08-31 16:44:54 +00001756public:
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00001757 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
1758
Craig Topper4f12f102014-03-12 06:41:41 +00001759 void computeInfo(CGFunctionInfo &FI) const override;
Chris Lattner04dc9572010-08-31 16:44:54 +00001760
John McCall7f416cc2015-09-08 08:05:57 +00001761 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1762 QualType Ty) const override;
Reid Kleckner80944df2014-10-31 22:00:51 +00001763
1764 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1765 // FIXME: Assumes vectorcall is in use.
1766 return isX86VectorTypeForVectorCall(getContext(), Ty);
1767 }
1768
1769 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1770 uint64_t NumMembers) const override {
1771 // FIXME: Assumes vectorcall is in use.
1772 return isX86VectorCallAggregateSmallEnough(NumMembers);
1773 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001774};
1775
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001776class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1777public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001778 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001779 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
John McCallbeec5a02010-03-06 00:35:14 +00001780
John McCalla729c622012-02-17 03:33:10 +00001781 const X86_64ABIInfo &getABIInfo() const {
1782 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
1783 }
1784
Craig Topper4f12f102014-03-12 06:41:41 +00001785 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCallbeec5a02010-03-06 00:35:14 +00001786 return 7;
1787 }
1788
1789 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001790 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001791 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00001792
John McCall943fae92010-05-27 06:19:26 +00001793 // 0-15 are the 16 integer registers.
1794 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001795 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
John McCallbeec5a02010-03-06 00:35:14 +00001796 return false;
1797 }
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001798
Jay Foad7c57be32011-07-11 09:56:20 +00001799 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001800 StringRef Constraint,
Craig Topper4f12f102014-03-12 06:41:41 +00001801 llvm::Type* Ty) const override {
Peter Collingbourne8f5cf742011-02-19 23:03:58 +00001802 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1803 }
1804
John McCalla729c622012-02-17 03:33:10 +00001805 bool isNoProtoCallVariadic(const CallArgList &args,
Craig Topper4f12f102014-03-12 06:41:41 +00001806 const FunctionNoProtoType *fnType) const override {
John McCallcbc038a2011-09-21 08:08:30 +00001807 // The default CC on x86-64 sets %al to the number of SSA
1808 // registers used, and GCC sets this when calling an unprototyped
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001809 // function, so we override the default behavior. However, don't do
Eli Friedmanb8e45b22011-12-06 03:08:26 +00001810 // that when AVX types are involved: the ABI explicitly states it is
1811 // undefined, and it doesn't work in practice because of how the ABI
1812 // defines varargs anyway.
Reid Kleckner78af0702013-08-27 23:08:25 +00001813 if (fnType->getCallConv() == CC_C) {
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001814 bool HasAVXType = false;
John McCalla729c622012-02-17 03:33:10 +00001815 for (CallArgList::const_iterator
1816 it = args.begin(), ie = args.end(); it != ie; ++it) {
1817 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
1818 HasAVXType = true;
1819 break;
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001820 }
1821 }
John McCalla729c622012-02-17 03:33:10 +00001822
Eli Friedmanf37bd2f2011-12-01 04:53:19 +00001823 if (!HasAVXType)
1824 return true;
1825 }
John McCallcbc038a2011-09-21 08:08:30 +00001826
John McCalla729c622012-02-17 03:33:10 +00001827 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
John McCallcbc038a2011-09-21 08:08:30 +00001828 }
1829
Craig Topper4f12f102014-03-12 06:41:41 +00001830 llvm::Constant *
1831 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
Peter Collingbourne69b004d2015-02-25 23:18:42 +00001832 unsigned Sig;
1833 if (getABIInfo().has64BitPointers())
1834 Sig = (0xeb << 0) | // jmp rel8
1835 (0x0a << 8) | // .+0x0c
1836 ('F' << 16) |
1837 ('T' << 24);
1838 else
1839 Sig = (0xeb << 0) | // jmp rel8
1840 (0x06 << 8) | // .+0x08
1841 ('F' << 16) |
1842 ('T' << 24);
Peter Collingbourneb453cd62013-10-20 21:29:19 +00001843 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1844 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00001845};
1846
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001847class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
1848public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001849 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
1850 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001851
1852 void getDependentLibraryOption(llvm::StringRef Lib,
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001853 llvm::SmallString<24> &Opt) const override {
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001854 Opt = "\01";
Yunzhong Gaod65200c2015-07-20 17:46:56 +00001855 // If the argument contains a space, enclose it in quotes.
1856 if (Lib.find(" ") != StringRef::npos)
1857 Opt += "\"" + Lib.str() + "\"";
1858 else
1859 Opt += Lib;
Alex Rosenberg12207fa2015-01-27 14:47:44 +00001860 }
1861};
1862
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001863static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001864 // If the argument does not end in .lib, automatically add the suffix.
1865 // If the argument contains a space, enclose it in quotes.
1866 // This matches the behavior of MSVC.
1867 bool Quote = (Lib.find(" ") != StringRef::npos);
1868 std::string ArgStr = Quote ? "\"" : "";
1869 ArgStr += Lib;
Rui Ueyama727025a2013-10-31 19:12:53 +00001870 if (!Lib.endswith_lower(".lib"))
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001871 ArgStr += ".lib";
Michael Kupersteinf0e4ccf2015-02-16 11:57:43 +00001872 ArgStr += Quote ? "\"" : "";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001873 return ArgStr;
1874}
1875
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001876class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
1877public:
John McCall1fe2a8c2013-06-18 02:46:29 +00001878 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1879 bool d, bool p, bool w, unsigned RegParms)
1880 : X86_32TargetCodeGenInfo(CGT, d, p, w, RegParms) {}
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001881
Eric Christopher162c91c2015-06-05 22:03:00 +00001882 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001883 CodeGen::CodeGenModule &CGM) const override;
1884
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001885 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001886 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001887 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001888 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001889 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001890
1891 void getDetectMismatchOption(llvm::StringRef Name,
1892 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001893 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001894 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001895 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001896};
1897
Hans Wennborg77dc2362015-01-20 19:45:50 +00001898static void addStackProbeSizeTargetAttribute(const Decl *D,
1899 llvm::GlobalValue *GV,
1900 CodeGen::CodeGenModule &CGM) {
1901 if (isa<FunctionDecl>(D)) {
1902 if (CGM.getCodeGenOpts().StackProbeSize != 4096) {
1903 llvm::Function *Fn = cast<llvm::Function>(GV);
1904
Eric Christopher7565e0d2015-05-29 23:09:49 +00001905 Fn->addFnAttr("stack-probe-size",
1906 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
Hans Wennborg77dc2362015-01-20 19:45:50 +00001907 }
1908 }
1909}
1910
Eric Christopher162c91c2015-06-05 22:03:00 +00001911void WinX86_32TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001912 llvm::GlobalValue *GV,
1913 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001914 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001915
1916 addStackProbeSizeTargetAttribute(D, GV, CGM);
1917}
1918
Chris Lattner04dc9572010-08-31 16:44:54 +00001919class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
1920public:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00001921 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
1922 X86AVXABILevel AVXLevel)
Alexey Bataev00396512015-07-02 03:40:19 +00001923 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
Chris Lattner04dc9572010-08-31 16:44:54 +00001924
Eric Christopher162c91c2015-06-05 22:03:00 +00001925 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001926 CodeGen::CodeGenModule &CGM) const override;
1927
Craig Topper4f12f102014-03-12 06:41:41 +00001928 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
Chris Lattner04dc9572010-08-31 16:44:54 +00001929 return 7;
1930 }
1931
1932 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00001933 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00001934 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00001935
Chris Lattner04dc9572010-08-31 16:44:54 +00001936 // 0-15 are the 16 integer registers.
1937 // 16 is %rip.
Chris Lattnerece04092012-02-07 00:39:47 +00001938 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
Chris Lattner04dc9572010-08-31 16:44:54 +00001939 return false;
1940 }
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001941
1942 void getDependentLibraryOption(llvm::StringRef Lib,
Craig Topper4f12f102014-03-12 06:41:41 +00001943 llvm::SmallString<24> &Opt) const override {
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001944 Opt = "/DEFAULTLIB:";
Aaron Ballmanef50ee92013-05-24 15:06:56 +00001945 Opt += qualifyWindowsLibrary(Lib);
Reid Klecknere43f0fe2013-05-08 13:44:39 +00001946 }
Aaron Ballman5d041be2013-06-04 02:07:14 +00001947
1948 void getDetectMismatchOption(llvm::StringRef Name,
1949 llvm::StringRef Value,
Craig Topper4f12f102014-03-12 06:41:41 +00001950 llvm::SmallString<32> &Opt) const override {
Eli Friedmanf60b8ce2013-06-07 22:42:22 +00001951 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
Aaron Ballman5d041be2013-06-04 02:07:14 +00001952 }
Chris Lattner04dc9572010-08-31 16:44:54 +00001953};
1954
Eric Christopher162c91c2015-06-05 22:03:00 +00001955void WinX86_64TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Hans Wennborg77dc2362015-01-20 19:45:50 +00001956 llvm::GlobalValue *GV,
1957 CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00001958 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Hans Wennborg77dc2362015-01-20 19:45:50 +00001959
1960 addStackProbeSizeTargetAttribute(D, GV, CGM);
1961}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001962}
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001963
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00001964void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
1965 Class &Hi) const {
1966 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
1967 //
1968 // (a) If one of the classes is Memory, the whole argument is passed in
1969 // memory.
1970 //
1971 // (b) If X87UP is not preceded by X87, the whole argument is passed in
1972 // memory.
1973 //
1974 // (c) If the size of the aggregate exceeds two eightbytes and the first
1975 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
1976 // argument is passed in memory. NOTE: This is necessary to keep the
1977 // ABI working for processors that don't support the __m256 type.
1978 //
1979 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
1980 //
1981 // Some of these are enforced by the merging logic. Others can arise
1982 // only with unions; for example:
1983 // union { _Complex double; unsigned; }
1984 //
1985 // Note that clauses (b) and (c) were added in 0.98.
1986 //
1987 if (Hi == Memory)
1988 Lo = Memory;
1989 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
1990 Lo = Memory;
1991 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
1992 Lo = Memory;
1993 if (Hi == SSEUp && Lo != SSE)
1994 Hi = SSE;
1995}
1996
Chris Lattnerd776fb12010-06-28 21:43:59 +00001997X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00001998 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
1999 // classified recursively so that always two fields are
2000 // considered. The resulting class is calculated according to
2001 // the classes of the fields in the eightbyte:
2002 //
2003 // (a) If both classes are equal, this is the resulting class.
2004 //
2005 // (b) If one of the classes is NO_CLASS, the resulting class is
2006 // the other class.
2007 //
2008 // (c) If one of the classes is MEMORY, the result is the MEMORY
2009 // class.
2010 //
2011 // (d) If one of the classes is INTEGER, the result is the
2012 // INTEGER.
2013 //
2014 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2015 // MEMORY is used as class.
2016 //
2017 // (f) Otherwise class SSE is used.
2018
2019 // Accum should never be memory (we should have returned) or
2020 // ComplexX87 (because this cannot be passed in a structure).
2021 assert((Accum != Memory && Accum != ComplexX87) &&
2022 "Invalid accumulated classification during merge.");
2023 if (Accum == Field || Field == NoClass)
2024 return Accum;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002025 if (Field == Memory)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002026 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002027 if (Accum == NoClass)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002028 return Field;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002029 if (Accum == Integer || Field == Integer)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002030 return Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002031 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2032 Accum == X87 || Accum == X87Up)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002033 return Memory;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002034 return SSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002035}
2036
Chris Lattner5c740f12010-06-30 19:14:05 +00002037void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Eli Friedman96fd2642013-06-12 00:13:45 +00002038 Class &Lo, Class &Hi, bool isNamedArg) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002039 // FIXME: This code can be simplified by introducing a simple value class for
2040 // Class pairs with appropriate constructor methods for the various
2041 // situations.
2042
2043 // FIXME: Some of the split computations are wrong; unaligned vectors
2044 // shouldn't be passed in registers for example, so there is no chance they
2045 // can straddle an eightbyte. Verify & simplify.
2046
2047 Lo = Hi = NoClass;
2048
2049 Class &Current = OffsetBase < 64 ? Lo : Hi;
2050 Current = Memory;
2051
John McCall9dd450b2009-09-21 23:43:11 +00002052 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002053 BuiltinType::Kind k = BT->getKind();
2054
2055 if (k == BuiltinType::Void) {
2056 Current = NoClass;
2057 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2058 Lo = Integer;
2059 Hi = Integer;
2060 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2061 Current = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002062 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002063 Current = SSE;
2064 } else if (k == BuiltinType::LongDouble) {
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002065 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2066 if (LDF == &llvm::APFloat::IEEEquad) {
2067 Lo = SSE;
2068 Hi = SSEUp;
2069 } else if (LDF == &llvm::APFloat::x87DoubleExtended) {
2070 Lo = X87;
2071 Hi = X87Up;
2072 } else if (LDF == &llvm::APFloat::IEEEdouble) {
2073 Current = SSE;
2074 } else
2075 llvm_unreachable("unexpected long double representation!");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002076 }
2077 // FIXME: _Decimal32 and _Decimal64 are SSE.
2078 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
Chris Lattnerd776fb12010-06-28 21:43:59 +00002079 return;
2080 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002081
Chris Lattnerd776fb12010-06-28 21:43:59 +00002082 if (const EnumType *ET = Ty->getAs<EnumType>()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002083 // Classify the underlying integer type.
Eli Friedman96fd2642013-06-12 00:13:45 +00002084 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
Chris Lattnerd776fb12010-06-28 21:43:59 +00002085 return;
2086 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002087
Chris Lattnerd776fb12010-06-28 21:43:59 +00002088 if (Ty->hasPointerRepresentation()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002089 Current = Integer;
Chris Lattnerd776fb12010-06-28 21:43:59 +00002090 return;
2091 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002092
Chris Lattnerd776fb12010-06-28 21:43:59 +00002093 if (Ty->isMemberPointerType()) {
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002094 if (Ty->isMemberFunctionPointerType()) {
2095 if (Has64BitPointers) {
2096 // If Has64BitPointers, this is an {i64, i64}, so classify both
2097 // Lo and Hi now.
2098 Lo = Hi = Integer;
2099 } else {
2100 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2101 // straddles an eightbyte boundary, Hi should be classified as well.
2102 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2103 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2104 if (EB_FuncPtr != EB_ThisAdj) {
2105 Lo = Hi = Integer;
2106 } else {
2107 Current = Integer;
2108 }
2109 }
2110 } else {
Daniel Dunbar36d4d152010-05-15 00:00:37 +00002111 Current = Integer;
Jan Wen Voung01c21e82014-10-02 16:56:57 +00002112 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002113 return;
2114 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002115
Chris Lattnerd776fb12010-06-28 21:43:59 +00002116 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002117 uint64_t Size = getContext().getTypeSize(VT);
David Majnemerf8d14db2015-07-17 05:49:13 +00002118 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2119 // gcc passes the following as integer:
2120 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2121 // 2 bytes - <2 x char>, <1 x short>
2122 // 1 byte - <1 x char>
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002123 Current = Integer;
2124
2125 // If this type crosses an eightbyte boundary, it should be
2126 // split.
David Majnemerf8d14db2015-07-17 05:49:13 +00002127 uint64_t EB_Lo = (OffsetBase) / 64;
2128 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2129 if (EB_Lo != EB_Hi)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002130 Hi = Lo;
2131 } else if (Size == 64) {
2132 // gcc passes <1 x double> in memory. :(
2133 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double))
2134 return;
2135
2136 // gcc passes <1 x long long> as INTEGER.
Chris Lattner46830f22010-08-26 18:03:20 +00002137 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::LongLong) ||
Chris Lattner69e683f2010-08-26 18:13:50 +00002138 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2139 VT->getElementType()->isSpecificBuiltinType(BuiltinType::Long) ||
2140 VT->getElementType()->isSpecificBuiltinType(BuiltinType::ULong))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002141 Current = Integer;
2142 else
2143 Current = SSE;
2144
2145 // If this type crosses an eightbyte boundary, it should be
2146 // split.
2147 if (OffsetBase && OffsetBase != 64)
2148 Hi = Lo;
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002149 } else if (Size == 128 ||
2150 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002151 // Arguments of 256-bits are split into four eightbyte chunks. The
2152 // least significant one belongs to class SSE and all the others to class
2153 // SSEUP. The original Lo and Hi design considers that types can't be
2154 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2155 // This design isn't correct for 256-bits, but since there're no cases
2156 // where the upper parts would need to be inspected, avoid adding
2157 // complexity and just consider Hi to match the 64-256 part.
Eli Friedman96fd2642013-06-12 00:13:45 +00002158 //
2159 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2160 // registers if they are "named", i.e. not part of the "..." of a
2161 // variadic function.
Ahmed Bougacha0b938282015-06-22 21:31:43 +00002162 //
2163 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2164 // split into eight eightbyte chunks, one SSE and seven SSEUP.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002165 Lo = SSE;
2166 Hi = SSEUp;
2167 }
Chris Lattnerd776fb12010-06-28 21:43:59 +00002168 return;
2169 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002170
Chris Lattnerd776fb12010-06-28 21:43:59 +00002171 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002172 QualType ET = getContext().getCanonicalType(CT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002173
Chris Lattner2b037972010-07-29 02:01:43 +00002174 uint64_t Size = getContext().getTypeSize(Ty);
Douglas Gregorb90df602010-06-16 00:17:44 +00002175 if (ET->isIntegralOrEnumerationType()) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002176 if (Size <= 64)
2177 Current = Integer;
2178 else if (Size <= 128)
2179 Lo = Hi = Integer;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002180 } else if (ET == getContext().FloatTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002181 Current = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002182 } else if (ET == getContext().DoubleTy) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002183 Lo = Hi = SSE;
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002184 } else if (ET == getContext().LongDoubleTy) {
2185 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2186 if (LDF == &llvm::APFloat::IEEEquad)
2187 Current = Memory;
2188 else if (LDF == &llvm::APFloat::x87DoubleExtended)
2189 Current = ComplexX87;
2190 else if (LDF == &llvm::APFloat::IEEEdouble)
2191 Lo = Hi = SSE;
2192 else
2193 llvm_unreachable("unexpected long double representation!");
2194 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002195
2196 // If this complex type crosses an eightbyte boundary then it
2197 // should be split.
2198 uint64_t EB_Real = (OffsetBase) / 64;
Chris Lattner2b037972010-07-29 02:01:43 +00002199 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002200 if (Hi == NoClass && EB_Real != EB_Imag)
2201 Hi = Lo;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002202
Chris Lattnerd776fb12010-06-28 21:43:59 +00002203 return;
2204 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002205
Chris Lattner2b037972010-07-29 02:01:43 +00002206 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002207 // Arrays are treated like structures.
2208
Chris Lattner2b037972010-07-29 02:01:43 +00002209 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002210
2211 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002212 // than four eightbytes, ..., it has class MEMORY.
2213 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002214 return;
2215
2216 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2217 // fields, it has class MEMORY.
2218 //
2219 // Only need to check alignment of array base.
Chris Lattner2b037972010-07-29 02:01:43 +00002220 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002221 return;
2222
2223 // Otherwise implement simplified merge. We could be smarter about
2224 // this, but it isn't worth it and would be harder to verify.
2225 Current = NoClass;
Chris Lattner2b037972010-07-29 02:01:43 +00002226 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002227 uint64_t ArraySize = AT->getSize().getZExtValue();
Bruno Cardoso Lopes75541d02011-07-12 01:27:38 +00002228
2229 // The only case a 256-bit wide vector could be used is when the array
2230 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2231 // to work for sizes wider than 128, early check and fallback to memory.
2232 if (Size > 128 && EltSize != 256)
2233 return;
2234
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002235 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2236 Class FieldLo, FieldHi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002237 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002238 Lo = merge(Lo, FieldLo);
2239 Hi = merge(Hi, FieldHi);
2240 if (Lo == Memory || Hi == Memory)
2241 break;
2242 }
2243
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002244 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002245 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
Chris Lattnerd776fb12010-06-28 21:43:59 +00002246 return;
2247 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002248
Chris Lattnerd776fb12010-06-28 21:43:59 +00002249 if (const RecordType *RT = Ty->getAs<RecordType>()) {
Chris Lattner2b037972010-07-29 02:01:43 +00002250 uint64_t Size = getContext().getTypeSize(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002251
2252 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002253 // than four eightbytes, ..., it has class MEMORY.
2254 if (Size > 256)
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002255 return;
2256
Anders Carlsson20759ad2009-09-16 15:53:40 +00002257 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2258 // copy constructor or a non-trivial destructor, it is passed by invisible
2259 // reference.
Mark Lacey3825e832013-10-06 01:33:34 +00002260 if (getRecordArgABI(RT, getCXXABI()))
Anders Carlsson20759ad2009-09-16 15:53:40 +00002261 return;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002262
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002263 const RecordDecl *RD = RT->getDecl();
2264
2265 // Assume variable sized types are passed in memory.
2266 if (RD->hasFlexibleArrayMember())
2267 return;
2268
Chris Lattner2b037972010-07-29 02:01:43 +00002269 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002270
2271 // Reset Lo class, this will be recomputed.
2272 Current = NoClass;
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002273
2274 // If this is a C++ record, classify the bases first.
2275 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002276 for (const auto &I : CXXRD->bases()) {
2277 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002278 "Unexpected base class!");
2279 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002280 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002281
2282 // Classify this field.
2283 //
2284 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2285 // single eightbyte, each is classified separately. Each eightbyte gets
2286 // initialized to class NO_CLASS.
2287 Class FieldLo, FieldHi;
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002288 uint64_t Offset =
2289 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
Aaron Ballman574705e2014-03-13 15:41:46 +00002290 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002291 Lo = merge(Lo, FieldLo);
2292 Hi = merge(Hi, FieldHi);
David Majnemercefbc7c2015-07-08 05:14:29 +00002293 if (Lo == Memory || Hi == Memory) {
2294 postMerge(Size, Lo, Hi);
2295 return;
2296 }
Daniel Dunbare1cd0152009-11-22 23:01:23 +00002297 }
2298 }
2299
2300 // Classify the fields one at a time, merging the results.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002301 unsigned idx = 0;
Bruno Cardoso Lopes0aadf832011-07-12 22:30:58 +00002302 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002303 i != e; ++i, ++idx) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002304 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2305 bool BitField = i->isBitField();
2306
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002307 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2308 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002309 //
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002310 // The only case a 256-bit wide vector could be used is when the struct
2311 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2312 // to work for sizes wider than 128, early check and fallback to memory.
2313 //
2314 if (Size > 128 && getContext().getTypeSize(i->getType()) != 256) {
2315 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002316 postMerge(Size, Lo, Hi);
Bruno Cardoso Lopes98154a72011-07-13 21:58:55 +00002317 return;
2318 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002319 // Note, skip this test for bit-fields, see below.
Chris Lattner2b037972010-07-29 02:01:43 +00002320 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002321 Lo = Memory;
David Majnemer699dd042015-07-08 05:07:05 +00002322 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002323 return;
2324 }
2325
2326 // Classify this field.
2327 //
2328 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2329 // exceeds a single eightbyte, each is classified
2330 // separately. Each eightbyte gets initialized to class
2331 // NO_CLASS.
2332 Class FieldLo, FieldHi;
2333
2334 // Bit-fields require special handling, they do not force the
2335 // structure to be passed in memory even if unaligned, and
2336 // therefore they can straddle an eightbyte.
2337 if (BitField) {
2338 // Ignore padding bit-fields.
2339 if (i->isUnnamedBitfield())
2340 continue;
2341
2342 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
Richard Smithcaf33902011-10-10 18:28:20 +00002343 uint64_t Size = i->getBitWidthValue(getContext());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002344
2345 uint64_t EB_Lo = Offset / 64;
2346 uint64_t EB_Hi = (Offset + Size - 1) / 64;
Sylvestre Ledru0c4813e2013-10-06 09:54:18 +00002347
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002348 if (EB_Lo) {
2349 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2350 FieldLo = NoClass;
2351 FieldHi = Integer;
2352 } else {
2353 FieldLo = Integer;
2354 FieldHi = EB_Hi ? Integer : NoClass;
2355 }
2356 } else
Eli Friedman96fd2642013-06-12 00:13:45 +00002357 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002358 Lo = merge(Lo, FieldLo);
2359 Hi = merge(Hi, FieldHi);
2360 if (Lo == Memory || Hi == Memory)
2361 break;
2362 }
2363
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002364 postMerge(Size, Lo, Hi);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002365 }
2366}
2367
Chris Lattner22a931e2010-06-29 06:01:59 +00002368ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002369 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2370 // place naturally.
John McCalla1dee5302010-08-22 10:59:02 +00002371 if (!isAggregateTypeForABI(Ty)) {
Daniel Dunbar53fac692010-04-21 19:49:55 +00002372 // Treat an enum type as its underlying type.
2373 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2374 Ty = EnumTy->getDecl()->getIntegerType();
2375
2376 return (Ty->isPromotableIntegerType() ?
2377 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
2378 }
2379
John McCall7f416cc2015-09-08 08:05:57 +00002380 return getNaturalAlignIndirect(Ty);
Daniel Dunbar53fac692010-04-21 19:49:55 +00002381}
2382
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002383bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2384 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2385 uint64_t Size = getContext().getTypeSize(VecTy);
Ahmed Bougachad39a4152015-06-22 21:30:39 +00002386 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002387 if (Size <= 64 || Size > LargestVector)
2388 return true;
2389 }
2390
2391 return false;
2392}
2393
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002394ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2395 unsigned freeIntRegs) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002396 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2397 // place naturally.
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002398 //
2399 // This assumption is optimistic, as there could be free registers available
2400 // when we need to pass this argument in memory, and LLVM could try to pass
2401 // the argument in the free register. This does not seem to happen currently,
2402 // but this code would be much safer if we could mark the argument with
2403 // 'onstack'. See PR12193.
Eli Friedmanbfd5add2011-12-02 00:11:43 +00002404 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00002405 // Treat an enum type as its underlying type.
2406 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2407 Ty = EnumTy->getDecl()->getIntegerType();
2408
Anton Korobeynikov18adbf52009-06-06 09:36:29 +00002409 return (Ty->isPromotableIntegerType() ?
2410 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00002411 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002412
Mark Lacey3825e832013-10-06 01:33:34 +00002413 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00002414 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Anders Carlsson20759ad2009-09-16 15:53:40 +00002415
Chris Lattner44c2b902011-05-22 23:21:23 +00002416 // Compute the byval alignment. We specify the alignment of the byval in all
2417 // cases so that the mid-level optimizer knows the alignment of the byval.
2418 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002419
2420 // Attempt to avoid passing indirect results using byval when possible. This
2421 // is important for good codegen.
2422 //
2423 // We do this by coercing the value into a scalar type which the backend can
2424 // handle naturally (i.e., without using byval).
2425 //
2426 // For simplicity, we currently only do this when we have exhausted all of the
2427 // free integer registers. Doing this when there are free integer registers
2428 // would require more care, as we would have to ensure that the coerced value
2429 // did not claim the unused register. That would require either reording the
2430 // arguments to the function (so that any subsequent inreg values came first),
2431 // or only doing this optimization when there were no following arguments that
2432 // might be inreg.
2433 //
2434 // We currently expect it to be rare (particularly in well written code) for
2435 // arguments to be passed on the stack when there are still free integer
2436 // registers available (this would typically imply large structs being passed
2437 // by value), so this seems like a fair tradeoff for now.
2438 //
2439 // We can revisit this if the backend grows support for 'onstack' parameter
2440 // attributes. See PR12193.
2441 if (freeIntRegs == 0) {
2442 uint64_t Size = getContext().getTypeSize(Ty);
2443
2444 // If this type fits in an eightbyte, coerce it into the matching integral
2445 // type, which will end up on the stack (with alignment 8).
2446 if (Align == 8 && Size <= 64)
2447 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2448 Size));
2449 }
2450
John McCall7f416cc2015-09-08 08:05:57 +00002451 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002452}
2453
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002454/// The ABI specifies that a value should be passed in a full vector XMM/YMM
2455/// register. Pick an LLVM IR type that will be passed as a vector register.
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002456llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002457 // Wrapper structs/arrays that only contain vectors are passed just like
2458 // vectors; strip them off if present.
2459 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2460 Ty = QualType(InnerTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002461
Sanjay Pateleb2af4e2015-02-16 17:26:51 +00002462 llvm::Type *IRType = CGT.ConvertType(Ty);
Chih-Hung Hsieh241a8902015-08-10 17:33:31 +00002463 if (isa<llvm::VectorType>(IRType) ||
2464 IRType->getTypeID() == llvm::Type::FP128TyID)
Andrea Di Biagioe7347c62015-06-02 19:34:40 +00002465 return IRType;
2466
2467 // We couldn't find the preferred IR vector type for 'Ty'.
2468 uint64_t Size = getContext().getTypeSize(Ty);
2469 assert((Size == 128 || Size == 256) && "Invalid type found!");
2470
2471 // Return a LLVM IR vector type based on the size of 'Ty'.
2472 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2473 Size / 64);
Chris Lattner4200fe42010-07-29 04:56:46 +00002474}
2475
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002476/// BitsContainNoUserData - Return true if the specified [start,end) bit range
2477/// is known to either be off the end of the specified type or being in
2478/// alignment padding. The user type specified is known to be at most 128 bits
2479/// in size, and have passed through X86_64ABIInfo::classify with a successful
2480/// classification that put one of the two halves in the INTEGER class.
2481///
2482/// It is conservatively correct to return false.
2483static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2484 unsigned EndBit, ASTContext &Context) {
2485 // If the bytes being queried are off the end of the type, there is no user
2486 // data hiding here. This handles analysis of builtins, vectors and other
2487 // types that don't contain interesting padding.
2488 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2489 if (TySize <= StartBit)
2490 return true;
2491
Chris Lattner98076a22010-07-29 07:43:55 +00002492 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2493 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2494 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2495
2496 // Check each element to see if the element overlaps with the queried range.
2497 for (unsigned i = 0; i != NumElts; ++i) {
2498 // If the element is after the span we care about, then we're done..
2499 unsigned EltOffset = i*EltSize;
2500 if (EltOffset >= EndBit) break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002501
Chris Lattner98076a22010-07-29 07:43:55 +00002502 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2503 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2504 EndBit-EltOffset, Context))
2505 return false;
2506 }
2507 // If it overlaps no elements, then it is safe to process as padding.
2508 return true;
2509 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002510
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002511 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2512 const RecordDecl *RD = RT->getDecl();
2513 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002514
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002515 // If this is a C++ record, check the bases first.
2516 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
Aaron Ballman574705e2014-03-13 15:41:46 +00002517 for (const auto &I : CXXRD->bases()) {
2518 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002519 "Unexpected base class!");
2520 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +00002521 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002522
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002523 // If the base is after the span we care about, ignore it.
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002524 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002525 if (BaseOffset >= EndBit) continue;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002526
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002527 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
Aaron Ballman574705e2014-03-13 15:41:46 +00002528 if (!BitsContainNoUserData(I.getType(), BaseStart,
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002529 EndBit-BaseOffset, Context))
2530 return false;
2531 }
2532 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002533
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002534 // Verify that no field has data that overlaps the region of interest. Yes
2535 // this could be sped up a lot by being smarter about queried fields,
2536 // however we're only looking at structs up to 16 bytes, so we don't care
2537 // much.
2538 unsigned idx = 0;
2539 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2540 i != e; ++i, ++idx) {
2541 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002542
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002543 // If we found a field after the region we care about, then we're done.
2544 if (FieldOffset >= EndBit) break;
2545
2546 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
2547 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
2548 Context))
2549 return false;
2550 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002551
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002552 // If nothing in this record overlapped the area of interest, then we're
2553 // clean.
2554 return true;
2555 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002556
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002557 return false;
2558}
2559
Chris Lattnere556a712010-07-29 18:39:32 +00002560/// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
2561/// float member at the specified offset. For example, {int,{float}} has a
2562/// float at offset 4. It is conservatively correct for this routine to return
2563/// false.
Chris Lattner2192fe52011-07-18 04:24:23 +00002564static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002565 const llvm::DataLayout &TD) {
Chris Lattnere556a712010-07-29 18:39:32 +00002566 // Base case if we find a float.
2567 if (IROffset == 0 && IRType->isFloatTy())
2568 return true;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002569
Chris Lattnere556a712010-07-29 18:39:32 +00002570 // If this is a struct, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002571 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnere556a712010-07-29 18:39:32 +00002572 const llvm::StructLayout *SL = TD.getStructLayout(STy);
2573 unsigned Elt = SL->getElementContainingOffset(IROffset);
2574 IROffset -= SL->getElementOffset(Elt);
2575 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
2576 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002577
Chris Lattnere556a712010-07-29 18:39:32 +00002578 // If this is an array, recurse into the field at the specified offset.
Chris Lattner2192fe52011-07-18 04:24:23 +00002579 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
2580 llvm::Type *EltTy = ATy->getElementType();
Chris Lattnere556a712010-07-29 18:39:32 +00002581 unsigned EltSize = TD.getTypeAllocSize(EltTy);
2582 IROffset -= IROffset/EltSize*EltSize;
2583 return ContainsFloatAtOffset(EltTy, IROffset, TD);
2584 }
2585
2586 return false;
2587}
2588
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002589
2590/// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
2591/// low 8 bytes of an XMM register, corresponding to the SSE class.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002592llvm::Type *X86_64ABIInfo::
2593GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002594 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattner50a357e2010-07-29 18:19:50 +00002595 // The only three choices we have are either double, <2 x float>, or float. We
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002596 // pass as float if the last 4 bytes is just padding. This happens for
2597 // structs that contain 3 floats.
2598 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
2599 SourceOffset*8+64, getContext()))
2600 return llvm::Type::getFloatTy(getVMContext());
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002601
Chris Lattnere556a712010-07-29 18:39:32 +00002602 // We want to pass as <2 x float> if the LLVM IR type contains a float at
2603 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
2604 // case.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002605 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
2606 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
Chris Lattner9f8b4512010-08-25 23:39:14 +00002607 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002608
Chris Lattner7f4b81a2010-07-29 18:13:09 +00002609 return llvm::Type::getDoubleTy(getVMContext());
2610}
2611
2612
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002613/// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
2614/// an 8-byte GPR. This means that we either have a scalar or we are talking
2615/// about the high or low part of an up-to-16-byte struct. This routine picks
2616/// the best LLVM IR type to represent this, which may be i64 or may be anything
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002617/// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
2618/// etc).
2619///
2620/// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
2621/// the source type. IROffset is an offset in bytes into the LLVM IR type that
2622/// the 8-byte value references. PrefType may be null.
2623///
Alp Toker9907f082014-07-09 14:06:35 +00002624/// SourceTy is the source-level type for the entire argument. SourceOffset is
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002625/// an offset into this that we're processing (which is always either 0 or 8).
2626///
Chris Lattnera5f58b02011-07-09 17:41:47 +00002627llvm::Type *X86_64ABIInfo::
2628GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002629 QualType SourceTy, unsigned SourceOffset) const {
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002630 // If we're dealing with an un-offset LLVM IR type, then it means that we're
2631 // returning an 8-byte unit starting with it. See if we can safely use it.
2632 if (IROffset == 0) {
2633 // Pointers and int64's always fill the 8-byte unit.
Derek Schuffc7dd7222012-10-11 15:52:22 +00002634 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
2635 IRType->isIntegerTy(64))
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002636 return IRType;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002637
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002638 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
2639 // goodness in the source type is just tail padding. This is allowed to
2640 // kick in for struct {double,int} on the int, but not on
2641 // struct{double,int,int} because we wouldn't return the second int. We
2642 // have to do this analysis on the source type because we can't depend on
2643 // unions being lowered a specific way etc.
2644 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
Derek Schuffc7dd7222012-10-11 15:52:22 +00002645 IRType->isIntegerTy(32) ||
2646 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
2647 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
2648 cast<llvm::IntegerType>(IRType)->getBitWidth();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002649
Chris Lattnerc8b7b532010-07-29 07:30:00 +00002650 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
2651 SourceOffset*8+64, getContext()))
2652 return IRType;
2653 }
2654 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002655
Chris Lattner2192fe52011-07-18 04:24:23 +00002656 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002657 // If this is a struct, recurse into the field at the specified offset.
Micah Villmowdd31ca12012-10-08 16:25:52 +00002658 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002659 if (IROffset < SL->getSizeInBytes()) {
2660 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
2661 IROffset -= SL->getElementOffset(FieldIdx);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002662
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002663 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
2664 SourceTy, SourceOffset);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002665 }
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002666 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002667
Chris Lattner2192fe52011-07-18 04:24:23 +00002668 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002669 llvm::Type *EltTy = ATy->getElementType();
Micah Villmowdd31ca12012-10-08 16:25:52 +00002670 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
Chris Lattner98076a22010-07-29 07:43:55 +00002671 unsigned EltOffset = IROffset/EltSize*EltSize;
Chris Lattner1c56d9a2010-07-29 17:40:35 +00002672 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
2673 SourceOffset);
Chris Lattner98076a22010-07-29 07:43:55 +00002674 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002675
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002676 // Okay, we don't have any better idea of what to pass, so we pass this in an
2677 // integer register that isn't too big to fit the rest of the struct.
Chris Lattner3f763422010-07-29 17:34:39 +00002678 unsigned TySizeInBytes =
2679 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002680
Chris Lattner3f763422010-07-29 17:34:39 +00002681 assert(TySizeInBytes != SourceOffset && "Empty field?");
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002682
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002683 // It is always safe to classify this as an integer type up to i64 that
2684 // isn't larger than the structure.
Chris Lattner3f763422010-07-29 17:34:39 +00002685 return llvm::IntegerType::get(getVMContext(),
2686 std::min(TySizeInBytes-SourceOffset, 8U)*8);
Chris Lattner22a931e2010-06-29 06:01:59 +00002687}
2688
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002689
2690/// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
2691/// be used as elements of a two register pair to pass or return, return a
2692/// first class aggregate to represent them. For example, if the low part of
2693/// a by-value argument should be passed as i32* and the high part as float,
2694/// return {i32*, float}.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002695static llvm::Type *
Jay Foad7c57be32011-07-11 09:56:20 +00002696GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
Micah Villmowdd31ca12012-10-08 16:25:52 +00002697 const llvm::DataLayout &TD) {
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002698 // In order to correctly satisfy the ABI, we need to the high part to start
2699 // at offset 8. If the high and low parts we inferred are both 4-byte types
2700 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
2701 // the second element at offset 8. Check for this:
2702 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
2703 unsigned HiAlign = TD.getABITypeAlignment(Hi);
David Majnemered684072014-10-20 06:13:36 +00002704 unsigned HiStart = llvm::RoundUpToAlignment(LoSize, HiAlign);
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002705 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002706
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002707 // To handle this, we have to increase the size of the low part so that the
2708 // second element will start at an 8 byte offset. We can't increase the size
2709 // of the second element because it might make us access off the end of the
2710 // struct.
2711 if (HiStart != 8) {
Derek Schuff5ec51282015-06-24 22:36:38 +00002712 // There are usually two sorts of types the ABI generation code can produce
2713 // for the low part of a pair that aren't 8 bytes in size: float or
2714 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
2715 // NaCl).
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002716 // Promote these to a larger type.
2717 if (Lo->isFloatTy())
2718 Lo = llvm::Type::getDoubleTy(Lo->getContext());
2719 else {
Derek Schuff3c6a48d2015-06-24 22:36:36 +00002720 assert((Lo->isIntegerTy() || Lo->isPointerTy())
2721 && "Invalid/unknown lo type");
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002722 Lo = llvm::Type::getInt64Ty(Lo->getContext());
2723 }
2724 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002725
Reid Kleckneree7cf842014-12-01 22:02:27 +00002726 llvm::StructType *Result = llvm::StructType::get(Lo, Hi, nullptr);
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002727
2728
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002729 // Verify that the second element is at an 8-byte offset.
2730 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
2731 "Invalid x86-64 argument pair!");
2732 return Result;
2733}
2734
Chris Lattner31faff52010-07-28 23:06:14 +00002735ABIArgInfo X86_64ABIInfo::
Chris Lattner458b2aa2010-07-29 02:16:43 +00002736classifyReturnType(QualType RetTy) const {
Chris Lattner31faff52010-07-28 23:06:14 +00002737 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
2738 // classification algorithm.
2739 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002740 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
Chris Lattner31faff52010-07-28 23:06:14 +00002741
2742 // Check some invariants.
2743 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Chris Lattner31faff52010-07-28 23:06:14 +00002744 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2745
Craig Topper8a13c412014-05-21 05:09:00 +00002746 llvm::Type *ResType = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002747 switch (Lo) {
2748 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002749 if (Hi == NoClass)
2750 return ABIArgInfo::getIgnore();
2751 // If the low part is just padding, it takes no register, leave ResType
2752 // null.
2753 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2754 "Unknown missing lo part");
2755 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002756
2757 case SSEUp:
2758 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002759 llvm_unreachable("Invalid classification for lo word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002760
2761 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
2762 // hidden argument.
2763 case Memory:
2764 return getIndirectReturnResult(RetTy);
2765
2766 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
2767 // available register of the sequence %rax, %rdx is used.
2768 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002769 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002770
Chris Lattner1f3a0632010-07-29 21:42:50 +00002771 // If we have a sign or zero extended integer, make sure to return Extend
2772 // so that the parameter gets the right LLVM IR attributes.
2773 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2774 // Treat an enum type as its underlying type.
2775 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
2776 RetTy = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002777
Chris Lattner1f3a0632010-07-29 21:42:50 +00002778 if (RetTy->isIntegralOrEnumerationType() &&
2779 RetTy->isPromotableIntegerType())
2780 return ABIArgInfo::getExtend();
2781 }
Chris Lattner31faff52010-07-28 23:06:14 +00002782 break;
2783
2784 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
2785 // available SSE register of the sequence %xmm0, %xmm1 is used.
2786 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002787 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002788 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002789
2790 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
2791 // returned on the X87 stack in %st0 as 80-bit x87 number.
2792 case X87:
Chris Lattner2b037972010-07-29 02:01:43 +00002793 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002794 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002795
2796 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
2797 // part of the value is returned in %st0 and the imaginary part in
2798 // %st1.
2799 case ComplexX87:
2800 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
Chris Lattner845511f2011-06-18 22:49:11 +00002801 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
Chris Lattner2b037972010-07-29 02:01:43 +00002802 llvm::Type::getX86_FP80Ty(getVMContext()),
Reid Kleckneree7cf842014-12-01 22:02:27 +00002803 nullptr);
Chris Lattner31faff52010-07-28 23:06:14 +00002804 break;
2805 }
2806
Craig Topper8a13c412014-05-21 05:09:00 +00002807 llvm::Type *HighPart = nullptr;
Chris Lattner31faff52010-07-28 23:06:14 +00002808 switch (Hi) {
2809 // Memory was handled previously and X87 should
2810 // never occur as a hi class.
2811 case Memory:
2812 case X87:
David Blaikie83d382b2011-09-23 05:06:16 +00002813 llvm_unreachable("Invalid classification for hi word.");
Chris Lattner31faff52010-07-28 23:06:14 +00002814
2815 case ComplexX87: // Previously handled.
Chris Lattnerfa560fe2010-07-28 23:12:33 +00002816 case NoClass:
2817 break;
Chris Lattner31faff52010-07-28 23:06:14 +00002818
Chris Lattner52b3c132010-09-01 00:20:33 +00002819 case Integer:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002820 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002821 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2822 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002823 break;
Chris Lattner52b3c132010-09-01 00:20:33 +00002824 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002825 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002826 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2827 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner31faff52010-07-28 23:06:14 +00002828 break;
2829
2830 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002831 // is passed in the next available eightbyte chunk if the last used
2832 // vector register.
Chris Lattner31faff52010-07-28 23:06:14 +00002833 //
Chris Lattner57540c52011-04-15 05:22:18 +00002834 // SSEUP should always be preceded by SSE, just widen.
Chris Lattner31faff52010-07-28 23:06:14 +00002835 case SSEUp:
2836 assert(Lo == SSE && "Unexpected SSEUp classification.");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002837 ResType = GetByteVectorType(RetTy);
Chris Lattner31faff52010-07-28 23:06:14 +00002838 break;
2839
2840 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
2841 // returned together with the previous X87 value in %st0.
2842 case X87Up:
Chris Lattner57540c52011-04-15 05:22:18 +00002843 // If X87Up is preceded by X87, we don't need to do
Chris Lattner31faff52010-07-28 23:06:14 +00002844 // anything. However, in some cases with unions it may not be
Chris Lattner57540c52011-04-15 05:22:18 +00002845 // preceded by X87. In such situations we follow gcc and pass the
Chris Lattner31faff52010-07-28 23:06:14 +00002846 // extra bits in an SSE reg.
Chris Lattnerc95a3982010-07-29 17:49:08 +00002847 if (Lo != X87) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002848 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
Chris Lattner52b3c132010-09-01 00:20:33 +00002849 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
2850 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattnerc95a3982010-07-29 17:49:08 +00002851 }
Chris Lattner31faff52010-07-28 23:06:14 +00002852 break;
2853 }
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002854
Chris Lattner52b3c132010-09-01 00:20:33 +00002855 // If a high part was specified, merge it together with the low part. It is
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002856 // known to pass in the high eightbyte of the result. We do this by forming a
2857 // first class struct aggregate with the high and low part: {low, high}
Chris Lattnerd426c8e2010-09-01 00:50:20 +00002858 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002859 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Chris Lattner31faff52010-07-28 23:06:14 +00002860
Chris Lattner1f3a0632010-07-29 21:42:50 +00002861 return ABIArgInfo::getDirect(ResType);
Chris Lattner31faff52010-07-28 23:06:14 +00002862}
2863
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002864ABIArgInfo X86_64ABIInfo::classifyArgumentType(
Eli Friedman96fd2642013-06-12 00:13:45 +00002865 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
2866 bool isNamedArg)
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002867 const
2868{
Reid Klecknerb1be6832014-11-15 01:41:41 +00002869 Ty = useFirstFieldIfTransparentUnion(Ty);
2870
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002871 X86_64ABIInfo::Class Lo, Hi;
Eli Friedman96fd2642013-06-12 00:13:45 +00002872 classify(Ty, 0, Lo, Hi, isNamedArg);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002873
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002874 // Check some invariants.
2875 // FIXME: Enforce these by construction.
2876 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002877 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
2878
2879 neededInt = 0;
2880 neededSSE = 0;
Craig Topper8a13c412014-05-21 05:09:00 +00002881 llvm::Type *ResType = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002882 switch (Lo) {
2883 case NoClass:
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002884 if (Hi == NoClass)
2885 return ABIArgInfo::getIgnore();
2886 // If the low part is just padding, it takes no register, leave ResType
2887 // null.
2888 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
2889 "Unknown missing lo part");
2890 break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002891
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002892 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
2893 // on the stack.
2894 case Memory:
2895
2896 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
2897 // COMPLEX_X87, it is passed in memory.
2898 case X87:
2899 case ComplexX87:
Mark Lacey3825e832013-10-06 01:33:34 +00002900 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
Eli Friedman4774b7e2011-06-29 07:04:55 +00002901 ++neededInt;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00002902 return getIndirectResult(Ty, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002903
2904 case SSEUp:
2905 case X87Up:
David Blaikie83d382b2011-09-23 05:06:16 +00002906 llvm_unreachable("Invalid classification for lo word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002907
2908 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
2909 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
2910 // and %r9 is used.
2911 case Integer:
Chris Lattner22a931e2010-06-29 06:01:59 +00002912 ++neededInt;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002913
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002914 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002915 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
Chris Lattner1f3a0632010-07-29 21:42:50 +00002916
2917 // If we have a sign or zero extended integer, make sure to return Extend
2918 // so that the parameter gets the right LLVM IR attributes.
2919 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
2920 // Treat an enum type as its underlying type.
2921 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2922 Ty = EnumTy->getDecl()->getIntegerType();
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002923
Chris Lattner1f3a0632010-07-29 21:42:50 +00002924 if (Ty->isIntegralOrEnumerationType() &&
2925 Ty->isPromotableIntegerType())
2926 return ABIArgInfo::getExtend();
2927 }
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002928
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002929 break;
2930
2931 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
2932 // available SSE register is used, the registers are taken in the
2933 // order from %xmm0 to %xmm7.
Bill Wendling5cd41c42010-10-18 03:41:31 +00002934 case SSE: {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002935 llvm::Type *IRType = CGT.ConvertType(Ty);
Eli Friedman1310c682011-07-02 00:57:27 +00002936 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
Bill Wendling9987c0e2010-10-18 23:51:38 +00002937 ++neededSSE;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002938 break;
2939 }
Bill Wendling5cd41c42010-10-18 03:41:31 +00002940 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002941
Craig Topper8a13c412014-05-21 05:09:00 +00002942 llvm::Type *HighPart = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002943 switch (Hi) {
2944 // Memory was handled previously, ComplexX87 and X87 should
Chris Lattner57540c52011-04-15 05:22:18 +00002945 // never occur as hi classes, and X87Up must be preceded by X87,
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002946 // which is passed in memory.
2947 case Memory:
2948 case X87:
2949 case ComplexX87:
David Blaikie83d382b2011-09-23 05:06:16 +00002950 llvm_unreachable("Invalid classification for hi word.");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002951
2952 case NoClass: break;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002953
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002954 case Integer:
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002955 ++neededInt;
Chris Lattnerb22f1c82010-07-28 22:44:07 +00002956 // Pick an 8-byte type based on the preferred type.
Chris Lattnera5f58b02011-07-09 17:41:47 +00002957 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002958
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002959 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2960 return ABIArgInfo::getDirect(HighPart, 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002961 break;
2962
2963 // X87Up generally doesn't occur here (long double is passed in
2964 // memory), except in situations involving unions.
2965 case X87Up:
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002966 case SSE:
Chris Lattnera5f58b02011-07-09 17:41:47 +00002967 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002968
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002969 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
2970 return ABIArgInfo::getDirect(HighPart, 8);
Chris Lattner8a2f3c72010-07-30 04:02:24 +00002971
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002972 ++neededSSE;
2973 break;
2974
2975 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
2976 // eightbyte is passed in the upper half of the last used SSE
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002977 // register. This only happens when 128-bit vectors are passed.
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002978 case SSEUp:
Chris Lattnerf4ba08a2010-07-28 23:47:21 +00002979 assert(Lo == SSE && "Unexpected SSEUp classification");
Bruno Cardoso Lopes21a41bb2011-07-11 22:41:29 +00002980 ResType = GetByteVectorType(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002981 break;
2982 }
2983
Chris Lattnerbe5eb172010-09-01 00:24:35 +00002984 // If a high part was specified, merge it together with the low part. It is
2985 // known to pass in the high eightbyte of the result. We do this by forming a
2986 // first class struct aggregate with the high and low part: {low, high}
2987 if (HighPart)
Micah Villmowdd31ca12012-10-08 16:25:52 +00002988 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
Michael J. Spencerf5a1fbc2010-10-19 06:39:39 +00002989
Chris Lattner1f3a0632010-07-29 21:42:50 +00002990 return ABIArgInfo::getDirect(ResType);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002991}
2992
Chris Lattner22326a12010-07-29 02:31:05 +00002993void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00002994
Reid Kleckner40ca9132014-05-13 22:05:45 +00002995 if (!getCXXABI().classifyReturnType(FI))
2996 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Anton Korobeynikov244360d2009-06-05 22:08:42 +00002997
2998 // Keep track of the number of assigned registers.
Bill Wendling9987c0e2010-10-18 23:51:38 +00002999 unsigned freeIntRegs = 6, freeSSERegs = 8;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003000
3001 // If the return value is indirect, then the hidden argument is consuming one
3002 // integer register.
3003 if (FI.getReturnInfo().isIndirect())
3004 --freeIntRegs;
3005
Peter Collingbournef7706832014-12-12 23:41:25 +00003006 // The chain argument effectively gives us another free register.
3007 if (FI.isChainCall())
3008 ++freeIntRegs;
3009
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003010 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003011 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3012 // get assigned (in left-to-right order) for passing as follows...
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003013 unsigned ArgNo = 0;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003014 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003015 it != ie; ++it, ++ArgNo) {
3016 bool IsNamedArg = ArgNo < NumRequiredArgs;
Eli Friedman96fd2642013-06-12 00:13:45 +00003017
Bill Wendling9987c0e2010-10-18 23:51:38 +00003018 unsigned neededInt, neededSSE;
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003019 it->info = classifyArgumentType(it->type, freeIntRegs, neededInt,
Alexey Samsonov34625dd2014-09-29 21:21:48 +00003020 neededSSE, IsNamedArg);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003021
3022 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3023 // eightbyte of an argument, the whole argument is passed on the
3024 // stack. If registers have already been assigned for some
3025 // eightbytes of such an argument, the assignments get reverted.
Bill Wendling9987c0e2010-10-18 23:51:38 +00003026 if (freeIntRegs >= neededInt && freeSSERegs >= neededSSE) {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003027 freeIntRegs -= neededInt;
3028 freeSSERegs -= neededSSE;
3029 } else {
Daniel Dunbarf07b5ec2012-03-10 01:03:58 +00003030 it->info = getIndirectResult(it->type, freeIntRegs);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003031 }
3032 }
3033}
3034
John McCall7f416cc2015-09-08 08:05:57 +00003035static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3036 Address VAListAddr, QualType Ty) {
3037 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3038 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003039 llvm::Value *overflow_arg_area =
3040 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3041
3042 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3043 // byte boundary if alignment needed by type exceeds 8 byte boundary.
Eli Friedmana1748562011-11-18 02:44:19 +00003044 // It isn't stated explicitly in the standard, but in practice we use
3045 // alignment greater than 16 where necessary.
John McCall7f416cc2015-09-08 08:05:57 +00003046 uint64_t Align = CGF.getContext().getTypeAlignInChars(Ty).getQuantity();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003047 if (Align > 8) {
Eli Friedmana1748562011-11-18 02:44:19 +00003048 // overflow_arg_area = (overflow_arg_area + align - 1) & -align;
Owen Anderson41a75022009-08-13 21:57:51 +00003049 llvm::Value *Offset =
Eli Friedmana1748562011-11-18 02:44:19 +00003050 llvm::ConstantInt::get(CGF.Int64Ty, Align - 1);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003051 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset);
3052 llvm::Value *AsInt = CGF.Builder.CreatePtrToInt(overflow_arg_area,
Chris Lattner5e016ae2010-06-27 07:15:29 +00003053 CGF.Int64Ty);
Eli Friedmana1748562011-11-18 02:44:19 +00003054 llvm::Value *Mask = llvm::ConstantInt::get(CGF.Int64Ty, -(uint64_t)Align);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003055 overflow_arg_area =
3056 CGF.Builder.CreateIntToPtr(CGF.Builder.CreateAnd(AsInt, Mask),
3057 overflow_arg_area->getType(),
3058 "overflow_arg_area.align");
3059 }
3060
3061 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
Chris Lattner2192fe52011-07-18 04:24:23 +00003062 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003063 llvm::Value *Res =
3064 CGF.Builder.CreateBitCast(overflow_arg_area,
Owen Anderson9793f0e2009-07-29 22:16:19 +00003065 llvm::PointerType::getUnqual(LTy));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003066
3067 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3068 // l->overflow_arg_area + sizeof(type).
3069 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3070 // an 8 byte boundary.
3071
3072 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
Owen Anderson41a75022009-08-13 21:57:51 +00003073 llvm::Value *Offset =
Chris Lattner5e016ae2010-06-27 07:15:29 +00003074 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003075 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3076 "overflow_arg_area.next");
3077 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3078
3079 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
John McCall7f416cc2015-09-08 08:05:57 +00003080 return Address(Res, CharUnits::fromQuantity(Align));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003081}
3082
John McCall7f416cc2015-09-08 08:05:57 +00003083Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3084 QualType Ty) const {
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003085 // Assume that va_list type is correct; should be pointer to LLVM type:
3086 // struct {
3087 // i32 gp_offset;
3088 // i32 fp_offset;
3089 // i8* overflow_arg_area;
3090 // i8* reg_save_area;
3091 // };
Bill Wendling9987c0e2010-10-18 23:51:38 +00003092 unsigned neededInt, neededSSE;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003093
John McCall7f416cc2015-09-08 08:05:57 +00003094 Ty = getContext().getCanonicalType(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00003095 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
Eli Friedman96fd2642013-06-12 00:13:45 +00003096 /*isNamedArg*/false);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003097
3098 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3099 // in the registers. If not go to step 7.
3100 if (!neededInt && !neededSSE)
John McCall7f416cc2015-09-08 08:05:57 +00003101 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003102
3103 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3104 // general purpose registers needed to pass type and num_fp to hold
3105 // the number of floating point registers needed.
3106
3107 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3108 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3109 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3110 //
3111 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3112 // register save space).
3113
Craig Topper8a13c412014-05-21 05:09:00 +00003114 llvm::Value *InRegs = nullptr;
John McCall7f416cc2015-09-08 08:05:57 +00003115 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3116 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003117 if (neededInt) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003118 gp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003119 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3120 "gp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003121 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
Chris Lattnerd776fb12010-06-28 21:43:59 +00003122 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3123 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003124 }
3125
3126 if (neededSSE) {
David Blaikie1ed728c2015-04-05 22:45:47 +00003127 fp_offset_p =
John McCall7f416cc2015-09-08 08:05:57 +00003128 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3129 "fp_offset_p");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003130 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3131 llvm::Value *FitsInFP =
Chris Lattnerd776fb12010-06-28 21:43:59 +00003132 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3133 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003134 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3135 }
3136
3137 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3138 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3139 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3140 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3141
3142 // Emit code to load the value if it was passed in registers.
3143
3144 CGF.EmitBlock(InRegBlock);
3145
3146 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3147 // an offset of l->gp_offset and/or l->fp_offset. This may require
3148 // copying to a temporary location in case the parameter is passed
3149 // in different register classes or requires an alignment greater
3150 // than 8 for general purpose registers and 16 for XMM registers.
3151 //
3152 // FIXME: This really results in shameful code when we end up needing to
3153 // collect arguments from different places; often what should result in a
3154 // simple assembling of a structure from scattered addresses has many more
3155 // loads than necessary. Can we clean this up?
Chris Lattner2192fe52011-07-18 04:24:23 +00003156 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00003157 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3158 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3159 "reg_save_area");
3160
3161 Address RegAddr = Address::invalid();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003162 if (neededInt && neededSSE) {
3163 // FIXME: Cleanup.
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00003164 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003165 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
John McCall7f416cc2015-09-08 08:05:57 +00003166 Address Tmp = CGF.CreateMemTemp(Ty);
3167 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003168 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003169 llvm::Type *TyLo = ST->getElementType(0);
3170 llvm::Type *TyHi = ST->getElementType(1);
Chris Lattner51e1cc22010-08-26 06:28:35 +00003171 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003172 "Unexpected ABI info for mixed regs");
Chris Lattner2192fe52011-07-18 04:24:23 +00003173 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3174 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
John McCall7f416cc2015-09-08 08:05:57 +00003175 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3176 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
Rafael Espindola0a500af2014-06-24 20:01:50 +00003177 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3178 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003179
John McCall7f416cc2015-09-08 08:05:57 +00003180 // Copy the first element.
3181 llvm::Value *V =
3182 CGF.Builder.CreateDefaultAlignedLoad(
3183 CGF.Builder.CreateBitCast(RegLoAddr, PTyLo));
3184 CGF.Builder.CreateStore(V,
3185 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3186
3187 // Copy the second element.
3188 V = CGF.Builder.CreateDefaultAlignedLoad(
3189 CGF.Builder.CreateBitCast(RegHiAddr, PTyHi));
3190 CharUnits Offset = CharUnits::fromQuantity(
3191 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3192 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3193
3194 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003195 } else if (neededInt) {
John McCall7f416cc2015-09-08 08:05:57 +00003196 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3197 CharUnits::fromQuantity(8));
3198 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003199
3200 // Copy to a temporary if necessary to ensure the appropriate alignment.
3201 std::pair<CharUnits, CharUnits> SizeAlign =
John McCall7f416cc2015-09-08 08:05:57 +00003202 getContext().getTypeInfoInChars(Ty);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003203 uint64_t TySize = SizeAlign.first.getQuantity();
John McCall7f416cc2015-09-08 08:05:57 +00003204 CharUnits TyAlign = SizeAlign.second;
3205
3206 // Copy into a temporary if the type is more aligned than the
3207 // register save area.
3208 if (TyAlign.getQuantity() > 8) {
3209 Address Tmp = CGF.CreateMemTemp(Ty);
3210 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
Eli Friedmanc11c1692013-06-07 23:20:55 +00003211 RegAddr = Tmp;
3212 }
John McCall7f416cc2015-09-08 08:05:57 +00003213
Chris Lattner0cf24192010-06-28 20:05:43 +00003214 } else if (neededSSE == 1) {
John McCall7f416cc2015-09-08 08:05:57 +00003215 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3216 CharUnits::fromQuantity(16));
3217 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003218 } else {
Chris Lattner0cf24192010-06-28 20:05:43 +00003219 assert(neededSSE == 2 && "Invalid number of needed registers!");
3220 // SSE registers are spaced 16 bytes apart in the register save
3221 // area, we need to collect the two eightbytes together.
John McCall7f416cc2015-09-08 08:05:57 +00003222 // The ABI isn't explicit about this, but it seems reasonable
3223 // to assume that the slots are 16-byte aligned, since the stack is
3224 // naturally 16-byte aligned and the prologue is expected to store
3225 // all the SSE registers to the RSA.
3226 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3227 CharUnits::fromQuantity(16));
3228 Address RegAddrHi =
3229 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3230 CharUnits::fromQuantity(16));
Chris Lattnerece04092012-02-07 00:39:47 +00003231 llvm::Type *DoubleTy = CGF.DoubleTy;
Reid Kleckneree7cf842014-12-01 22:02:27 +00003232 llvm::StructType *ST = llvm::StructType::get(DoubleTy, DoubleTy, nullptr);
John McCall7f416cc2015-09-08 08:05:57 +00003233 llvm::Value *V;
3234 Address Tmp = CGF.CreateMemTemp(Ty);
3235 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3236 V = CGF.Builder.CreateLoad(
3237 CGF.Builder.CreateElementBitCast(RegAddrLo, DoubleTy));
3238 CGF.Builder.CreateStore(V,
3239 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3240 V = CGF.Builder.CreateLoad(
3241 CGF.Builder.CreateElementBitCast(RegAddrHi, DoubleTy));
3242 CGF.Builder.CreateStore(V,
3243 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3244
3245 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003246 }
3247
3248 // AMD64-ABI 3.5.7p5: Step 5. Set:
3249 // l->gp_offset = l->gp_offset + num_gp * 8
3250 // l->fp_offset = l->fp_offset + num_fp * 16.
3251 if (neededInt) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003252 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003253 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3254 gp_offset_p);
3255 }
3256 if (neededSSE) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00003257 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003258 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3259 fp_offset_p);
3260 }
3261 CGF.EmitBranch(ContBlock);
3262
3263 // Emit code to load the value if it was passed in memory.
3264
3265 CGF.EmitBlock(InMemBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003266 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003267
3268 // Return the appropriate result.
3269
3270 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00003271 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3272 "vaarg.addr");
Anton Korobeynikov244360d2009-06-05 22:08:42 +00003273 return ResAddr;
3274}
3275
Charles Davisc7d5c942015-09-17 20:55:33 +00003276Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3277 QualType Ty) const {
3278 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3279 CGF.getContext().getTypeInfoInChars(Ty),
3280 CharUnits::fromQuantity(8),
3281 /*allowHigherAlign*/ false);
3282}
3283
Reid Kleckner80944df2014-10-31 22:00:51 +00003284ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3285 bool IsReturnType) const {
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003286
3287 if (Ty->isVoidType())
3288 return ABIArgInfo::getIgnore();
3289
3290 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3291 Ty = EnumTy->getDecl()->getIntegerType();
3292
Reid Kleckner80944df2014-10-31 22:00:51 +00003293 TypeInfo Info = getContext().getTypeInfo(Ty);
3294 uint64_t Width = Info.Width;
3295 unsigned Align = getContext().toCharUnitsFromBits(Info.Align).getQuantity();
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003296
Reid Kleckner9005f412014-05-02 00:51:20 +00003297 const RecordType *RT = Ty->getAs<RecordType>();
3298 if (RT) {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003299 if (!IsReturnType) {
Mark Lacey3825e832013-10-06 01:33:34 +00003300 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003301 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Timur Iskhodzhanov8fe501d2013-04-17 12:54:10 +00003302 }
3303
3304 if (RT->getDecl()->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00003305 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003306
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003307 // FIXME: mingw-w64-gcc emits 128-bit struct as i128
Reid Kleckner80944df2014-10-31 22:00:51 +00003308 if (Width == 128 && getTarget().getTriple().isWindowsGNUEnvironment())
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003309 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Reid Kleckner80944df2014-10-31 22:00:51 +00003310 Width));
Reid Kleckner9005f412014-05-02 00:51:20 +00003311 }
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003312
Reid Kleckner80944df2014-10-31 22:00:51 +00003313 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3314 // other targets.
3315 const Type *Base = nullptr;
3316 uint64_t NumElts = 0;
3317 if (FreeSSERegs && isHomogeneousAggregate(Ty, Base, NumElts)) {
3318 if (FreeSSERegs >= NumElts) {
3319 FreeSSERegs -= NumElts;
3320 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3321 return ABIArgInfo::getDirect();
3322 return ABIArgInfo::getExpand();
3323 }
John McCall7f416cc2015-09-08 08:05:57 +00003324 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align),
3325 /*ByVal=*/false);
Reid Kleckner80944df2014-10-31 22:00:51 +00003326 }
3327
3328
Reid Klecknerec87fec2014-05-02 01:17:12 +00003329 if (Ty->isMemberPointerType()) {
Reid Kleckner7f5f0f32014-05-02 01:14:59 +00003330 // If the member pointer is represented by an LLVM int or ptr, pass it
3331 // directly.
3332 llvm::Type *LLTy = CGT.ConvertType(Ty);
3333 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3334 return ABIArgInfo::getDirect();
Reid Kleckner9005f412014-05-02 00:51:20 +00003335 }
3336
Michael Kuperstein4f818702015-02-24 09:35:58 +00003337 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
NAKAMURA Takumif8a6e802011-02-22 03:56:57 +00003338 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3339 // not 1, 2, 4, or 8 bytes, must be passed by reference."
Reid Kleckner80944df2014-10-31 22:00:51 +00003340 if (Width > 64 || !llvm::isPowerOf2_64(Width))
John McCall7f416cc2015-09-08 08:05:57 +00003341 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003342
Reid Kleckner9005f412014-05-02 00:51:20 +00003343 // Otherwise, coerce it to a small integer.
Reid Kleckner80944df2014-10-31 22:00:51 +00003344 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003345 }
3346
Julien Lerouge10dcff82014-08-27 00:36:55 +00003347 // Bool type is always extended to the ABI, other builtin types are not
3348 // extended.
3349 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3350 if (BT && BT->getKind() == BuiltinType::Bool)
Julien Lerougee8d34fa2014-08-26 22:11:53 +00003351 return ABIArgInfo::getExtend();
3352
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003353 return ABIArgInfo::getDirect();
3354}
3355
3356void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner80944df2014-10-31 22:00:51 +00003357 bool IsVectorCall =
3358 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
Reid Kleckner37abaca2014-05-09 22:46:15 +00003359
Reid Kleckner80944df2014-10-31 22:00:51 +00003360 // We can use up to 4 SSE return registers with vectorcall.
3361 unsigned FreeSSERegs = IsVectorCall ? 4 : 0;
3362 if (!getCXXABI().classifyReturnType(FI))
3363 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true);
3364
3365 // We can use up to 6 SSE register parameters with vectorcall.
3366 FreeSSERegs = IsVectorCall ? 6 : 0;
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003367 for (auto &I : FI.arguments())
Reid Kleckner80944df2014-10-31 22:00:51 +00003368 I.info = classify(I.type, FreeSSERegs, false);
NAKAMURA Takumibd91f502011-01-17 22:56:31 +00003369}
3370
John McCall7f416cc2015-09-08 08:05:57 +00003371Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3372 QualType Ty) const {
3373 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3374 CGF.getContext().getTypeInfoInChars(Ty),
3375 CharUnits::fromQuantity(8),
3376 /*allowHigherAlign*/ false);
Chris Lattner04dc9572010-08-31 16:44:54 +00003377}
Chris Lattner0cf24192010-06-28 20:05:43 +00003378
John McCallea8d8bb2010-03-11 00:10:12 +00003379// PowerPC-32
John McCallea8d8bb2010-03-11 00:10:12 +00003380namespace {
Roman Divacky8a12d842014-11-03 18:32:54 +00003381/// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
3382class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
John McCallea8d8bb2010-03-11 00:10:12 +00003383public:
Roman Divacky8a12d842014-11-03 18:32:54 +00003384 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
3385
John McCall7f416cc2015-09-08 08:05:57 +00003386 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3387 QualType Ty) const override;
Roman Divacky8a12d842014-11-03 18:32:54 +00003388};
3389
3390class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
3391public:
Eric Christopher7565e0d2015-05-29 23:09:49 +00003392 PPC32TargetCodeGenInfo(CodeGenTypes &CGT)
3393 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT)) {}
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003394
Craig Topper4f12f102014-03-12 06:41:41 +00003395 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallea8d8bb2010-03-11 00:10:12 +00003396 // This is recovered from gcc output.
3397 return 1; // r1 is the dedicated stack pointer
3398 }
3399
3400 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003401 llvm::Value *Address) const override;
John McCallea8d8bb2010-03-11 00:10:12 +00003402};
3403
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003404}
John McCallea8d8bb2010-03-11 00:10:12 +00003405
John McCall7f416cc2015-09-08 08:05:57 +00003406Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
3407 QualType Ty) const {
Roman Divacky8a12d842014-11-03 18:32:54 +00003408 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
3409 // TODO: Implement this. For now ignore.
3410 (void)CTy;
John McCall7f416cc2015-09-08 08:05:57 +00003411 return Address::invalid();
Roman Divacky8a12d842014-11-03 18:32:54 +00003412 }
3413
John McCall7f416cc2015-09-08 08:05:57 +00003414 // struct __va_list_tag {
3415 // unsigned char gpr;
3416 // unsigned char fpr;
3417 // unsigned short reserved;
3418 // void *overflow_arg_area;
3419 // void *reg_save_area;
3420 // };
3421
Roman Divacky8a12d842014-11-03 18:32:54 +00003422 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
Eric Christopher7565e0d2015-05-29 23:09:49 +00003423 bool isInt =
3424 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
John McCall7f416cc2015-09-08 08:05:57 +00003425
3426 // All aggregates are passed indirectly? That doesn't seem consistent
3427 // with the argument-lowering code.
3428 bool isIndirect = Ty->isAggregateType();
Roman Divacky8a12d842014-11-03 18:32:54 +00003429
3430 CGBuilderTy &Builder = CGF.Builder;
John McCall7f416cc2015-09-08 08:05:57 +00003431
3432 // The calling convention either uses 1-2 GPRs or 1 FPR.
3433 Address NumRegsAddr = Address::invalid();
3434 if (isInt) {
3435 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
3436 } else {
3437 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003438 }
John McCall7f416cc2015-09-08 08:05:57 +00003439
3440 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
3441
3442 // "Align" the register count when TY is i64.
3443 if (isI64) {
3444 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
3445 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
3446 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003447
Eric Christopher7565e0d2015-05-29 23:09:49 +00003448 llvm::Value *CC =
John McCall7f416cc2015-09-08 08:05:57 +00003449 Builder.CreateICmpULT(NumRegs, Builder.getInt8(8), "cond");
Roman Divacky8a12d842014-11-03 18:32:54 +00003450
3451 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
3452 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
3453 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
3454
3455 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
3456
John McCall7f416cc2015-09-08 08:05:57 +00003457 llvm::Type *DirectTy = CGF.ConvertType(Ty);
3458 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
Roman Divacky8a12d842014-11-03 18:32:54 +00003459
John McCall7f416cc2015-09-08 08:05:57 +00003460 // Case 1: consume registers.
3461 Address RegAddr = Address::invalid();
3462 {
3463 CGF.EmitBlock(UsingRegs);
3464
3465 Address RegSaveAreaPtr =
3466 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
3467 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
3468 CharUnits::fromQuantity(8));
3469 assert(RegAddr.getElementType() == CGF.Int8Ty);
3470
3471 // Floating-point registers start after the general-purpose registers.
3472 if (!isInt) {
3473 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
3474 CharUnits::fromQuantity(32));
3475 }
3476
3477 // Get the address of the saved value by scaling the number of
3478 // registers we've used by the number of
3479 CharUnits RegSize = CharUnits::fromQuantity(isInt ? 4 : 8);
3480 llvm::Value *RegOffset =
3481 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
3482 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
3483 RegAddr.getPointer(), RegOffset),
3484 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
3485 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
3486
3487 // Increase the used-register count.
3488 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(isI64 ? 2 : 1));
3489 Builder.CreateStore(NumRegs, NumRegsAddr);
3490
3491 CGF.EmitBranch(Cont);
Roman Divacky8a12d842014-11-03 18:32:54 +00003492 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003493
John McCall7f416cc2015-09-08 08:05:57 +00003494 // Case 2: consume space in the overflow area.
3495 Address MemAddr = Address::invalid();
3496 {
3497 CGF.EmitBlock(UsingOverflow);
Roman Divacky8a12d842014-11-03 18:32:54 +00003498
John McCall7f416cc2015-09-08 08:05:57 +00003499 // Everything in the overflow area is rounded up to a size of at least 4.
3500 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
3501
3502 CharUnits Size;
3503 if (!isIndirect) {
3504 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
3505 Size = TypeInfo.first.RoundUpToAlignment(OverflowAreaAlign);
3506 } else {
3507 Size = CGF.getPointerSize();
3508 }
3509
3510 Address OverflowAreaAddr =
3511 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
3512 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr),
3513 OverflowAreaAlign);
3514
3515 // The current address is the address of the varargs element.
3516 // FIXME: do we not need to round up to alignment?
3517 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
3518
3519 // Increase the overflow area.
3520 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
3521 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
3522 CGF.EmitBranch(Cont);
3523 }
Roman Divacky8a12d842014-11-03 18:32:54 +00003524
3525 CGF.EmitBlock(Cont);
3526
John McCall7f416cc2015-09-08 08:05:57 +00003527 // Merge the cases with a phi.
3528 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
3529 "vaarg.addr");
Roman Divacky8a12d842014-11-03 18:32:54 +00003530
John McCall7f416cc2015-09-08 08:05:57 +00003531 // Load the pointer if the argument was passed indirectly.
3532 if (isIndirect) {
3533 Result = Address(Builder.CreateLoad(Result, "aggr"),
3534 getContext().getTypeAlignInChars(Ty));
Roman Divacky8a12d842014-11-03 18:32:54 +00003535 }
3536
3537 return Result;
3538}
3539
John McCallea8d8bb2010-03-11 00:10:12 +00003540bool
3541PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
3542 llvm::Value *Address) const {
3543 // This is calculated from the LLVM and GCC tables and verified
3544 // against gcc output. AFAIK all ABIs use the same encoding.
3545
3546 CodeGen::CGBuilderTy &Builder = CGF.Builder;
John McCallea8d8bb2010-03-11 00:10:12 +00003547
Chris Lattnerece04092012-02-07 00:39:47 +00003548 llvm::IntegerType *i8 = CGF.Int8Ty;
John McCallea8d8bb2010-03-11 00:10:12 +00003549 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
3550 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
3551 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
3552
3553 // 0-31: r0-31, the 4-byte general-purpose registers
John McCall943fae92010-05-27 06:19:26 +00003554 AssignToArrayRange(Builder, Address, Four8, 0, 31);
John McCallea8d8bb2010-03-11 00:10:12 +00003555
3556 // 32-63: fp0-31, the 8-byte floating-point registers
John McCall943fae92010-05-27 06:19:26 +00003557 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
John McCallea8d8bb2010-03-11 00:10:12 +00003558
3559 // 64-76 are various 4-byte special-purpose registers:
3560 // 64: mq
3561 // 65: lr
3562 // 66: ctr
3563 // 67: ap
3564 // 68-75 cr0-7
3565 // 76: xer
John McCall943fae92010-05-27 06:19:26 +00003566 AssignToArrayRange(Builder, Address, Four8, 64, 76);
John McCallea8d8bb2010-03-11 00:10:12 +00003567
3568 // 77-108: v0-31, the 16-byte vector registers
John McCall943fae92010-05-27 06:19:26 +00003569 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
John McCallea8d8bb2010-03-11 00:10:12 +00003570
3571 // 109: vrsave
3572 // 110: vscr
3573 // 111: spe_acc
3574 // 112: spefscr
3575 // 113: sfp
John McCall943fae92010-05-27 06:19:26 +00003576 AssignToArrayRange(Builder, Address, Four8, 109, 113);
John McCallea8d8bb2010-03-11 00:10:12 +00003577
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00003578 return false;
John McCallea8d8bb2010-03-11 00:10:12 +00003579}
3580
Roman Divackyd966e722012-05-09 18:22:46 +00003581// PowerPC-64
3582
3583namespace {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003584/// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
3585class PPC64_SVR4_ABIInfo : public DefaultABIInfo {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003586public:
3587 enum ABIKind {
3588 ELFv1 = 0,
3589 ELFv2
3590 };
3591
3592private:
3593 static const unsigned GPRBits = 64;
3594 ABIKind Kind;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003595 bool HasQPX;
3596
3597 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
3598 // will be passed in a QPX register.
3599 bool IsQPXVectorTy(const Type *Ty) const {
3600 if (!HasQPX)
3601 return false;
3602
3603 if (const VectorType *VT = Ty->getAs<VectorType>()) {
3604 unsigned NumElements = VT->getNumElements();
3605 if (NumElements == 1)
3606 return false;
3607
3608 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
3609 if (getContext().getTypeSize(Ty) <= 256)
3610 return true;
3611 } else if (VT->getElementType()->
3612 isSpecificBuiltinType(BuiltinType::Float)) {
3613 if (getContext().getTypeSize(Ty) <= 128)
3614 return true;
3615 }
3616 }
3617
3618 return false;
3619 }
3620
3621 bool IsQPXVectorTy(QualType Ty) const {
3622 return IsQPXVectorTy(Ty.getTypePtr());
3623 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003624
3625public:
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003626 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX)
3627 : DefaultABIInfo(CGT), Kind(Kind), HasQPX(HasQPX) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003628
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003629 bool isPromotableTypeForABI(QualType Ty) const;
John McCall7f416cc2015-09-08 08:05:57 +00003630 CharUnits getParamTypeAlignment(QualType Ty) const;
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003631
3632 ABIArgInfo classifyReturnType(QualType RetTy) const;
3633 ABIArgInfo classifyArgumentType(QualType Ty) const;
3634
Reid Klecknere9f6a712014-10-31 17:10:41 +00003635 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
3636 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
3637 uint64_t Members) const override;
3638
Bill Schmidt84d37792012-10-12 19:26:17 +00003639 // TODO: We can add more logic to computeInfo to improve performance.
3640 // Example: For aggregate arguments that fit in a register, we could
3641 // use getDirectInReg (as is done below for structs containing a single
3642 // floating-point value) to avoid pushing them to memory on function
3643 // entry. This would require changing the logic in PPCISelLowering
3644 // when lowering the parameters in the caller and args in the callee.
Craig Topper4f12f102014-03-12 06:41:41 +00003645 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00003646 if (!getCXXABI().classifyReturnType(FI))
3647 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003648 for (auto &I : FI.arguments()) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003649 // We rely on the default argument classification for the most part.
3650 // One exception: An aggregate containing a single floating-point
Bill Schmidt179afae2013-07-23 22:15:57 +00003651 // or vector item must be passed in a register if one is available.
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003652 const Type *T = isSingleElementStruct(I.type, getContext());
Bill Schmidt84d37792012-10-12 19:26:17 +00003653 if (T) {
3654 const BuiltinType *BT = T->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003655 if (IsQPXVectorTy(T) ||
3656 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003657 (BT && BT->isFloatingPoint())) {
Bill Schmidt84d37792012-10-12 19:26:17 +00003658 QualType QT(T, 0);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003659 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
Bill Schmidt84d37792012-10-12 19:26:17 +00003660 continue;
3661 }
3662 }
Aaron Ballmanec47bc22014-03-17 18:10:01 +00003663 I.info = classifyArgumentType(I.type);
Bill Schmidt84d37792012-10-12 19:26:17 +00003664 }
3665 }
Bill Schmidt25cb3492012-10-03 19:18:57 +00003666
John McCall7f416cc2015-09-08 08:05:57 +00003667 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3668 QualType Ty) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003669};
3670
3671class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003672
Bill Schmidt25cb3492012-10-03 19:18:57 +00003673public:
Ulrich Weigandb7122372014-07-21 00:48:09 +00003674 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003675 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX)
Alexey Bataev00396512015-07-02 03:40:19 +00003676 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX)) {}
Bill Schmidt25cb3492012-10-03 19:18:57 +00003677
Craig Topper4f12f102014-03-12 06:41:41 +00003678 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Bill Schmidt25cb3492012-10-03 19:18:57 +00003679 // This is recovered from gcc output.
3680 return 1; // r1 is the dedicated stack pointer
3681 }
3682
3683 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003684 llvm::Value *Address) const override;
Bill Schmidt25cb3492012-10-03 19:18:57 +00003685};
3686
Roman Divackyd966e722012-05-09 18:22:46 +00003687class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
3688public:
3689 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
3690
Craig Topper4f12f102014-03-12 06:41:41 +00003691 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyd966e722012-05-09 18:22:46 +00003692 // This is recovered from gcc output.
3693 return 1; // r1 is the dedicated stack pointer
3694 }
3695
3696 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00003697 llvm::Value *Address) const override;
Roman Divackyd966e722012-05-09 18:22:46 +00003698};
3699
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003700}
Roman Divackyd966e722012-05-09 18:22:46 +00003701
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003702// Return true if the ABI requires Ty to be passed sign- or zero-
3703// extended to 64 bits.
3704bool
3705PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
3706 // Treat an enum type as its underlying type.
3707 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3708 Ty = EnumTy->getDecl()->getIntegerType();
3709
3710 // Promotable integer types are required to be promoted by the ABI.
3711 if (Ty->isPromotableIntegerType())
3712 return true;
3713
3714 // In addition to the usual promotable integer types, we also need to
3715 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
3716 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
3717 switch (BT->getKind()) {
3718 case BuiltinType::Int:
3719 case BuiltinType::UInt:
3720 return true;
3721 default:
3722 break;
3723 }
3724
3725 return false;
3726}
3727
John McCall7f416cc2015-09-08 08:05:57 +00003728/// isAlignedParamType - Determine whether a type requires 16-byte or
3729/// higher alignment in the parameter area. Always returns at least 8.
3730CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
Ulrich Weigand581badc2014-07-10 17:20:07 +00003731 // Complex types are passed just like their elements.
3732 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
3733 Ty = CTy->getElementType();
3734
3735 // Only vector types of size 16 bytes need alignment (larger types are
3736 // passed via reference, smaller types are not aligned).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003737 if (IsQPXVectorTy(Ty)) {
3738 if (getContext().getTypeSize(Ty) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003739 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003740
John McCall7f416cc2015-09-08 08:05:57 +00003741 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003742 } else if (Ty->isVectorType()) {
John McCall7f416cc2015-09-08 08:05:57 +00003743 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003744 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003745
3746 // For single-element float/vector structs, we consider the whole type
3747 // to have the same alignment requirements as its single element.
3748 const Type *AlignAsType = nullptr;
3749 const Type *EltType = isSingleElementStruct(Ty, getContext());
3750 if (EltType) {
3751 const BuiltinType *BT = EltType->getAs<BuiltinType>();
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003752 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
Ulrich Weigand581badc2014-07-10 17:20:07 +00003753 getContext().getTypeSize(EltType) == 128) ||
3754 (BT && BT->isFloatingPoint()))
3755 AlignAsType = EltType;
3756 }
3757
Ulrich Weigandb7122372014-07-21 00:48:09 +00003758 // Likewise for ELFv2 homogeneous aggregates.
3759 const Type *Base = nullptr;
3760 uint64_t Members = 0;
3761 if (!AlignAsType && Kind == ELFv2 &&
3762 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
3763 AlignAsType = Base;
3764
Ulrich Weigand581badc2014-07-10 17:20:07 +00003765 // With special case aggregates, only vector base types need alignment.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003766 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
3767 if (getContext().getTypeSize(AlignAsType) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003768 return CharUnits::fromQuantity(32);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003769
John McCall7f416cc2015-09-08 08:05:57 +00003770 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003771 } else if (AlignAsType) {
John McCall7f416cc2015-09-08 08:05:57 +00003772 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003773 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003774
3775 // Otherwise, we only need alignment for any aggregate type that
3776 // has an alignment requirement of >= 16 bytes.
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003777 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
3778 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
John McCall7f416cc2015-09-08 08:05:57 +00003779 return CharUnits::fromQuantity(32);
3780 return CharUnits::fromQuantity(16);
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003781 }
Ulrich Weigand581badc2014-07-10 17:20:07 +00003782
John McCall7f416cc2015-09-08 08:05:57 +00003783 return CharUnits::fromQuantity(8);
Ulrich Weigand581badc2014-07-10 17:20:07 +00003784}
3785
Ulrich Weigandb7122372014-07-21 00:48:09 +00003786/// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
3787/// aggregate. Base is set to the base element type, and Members is set
3788/// to the number of base elements.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003789bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
3790 uint64_t &Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003791 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
3792 uint64_t NElements = AT->getSize().getZExtValue();
3793 if (NElements == 0)
3794 return false;
3795 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
3796 return false;
3797 Members *= NElements;
3798 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
3799 const RecordDecl *RD = RT->getDecl();
3800 if (RD->hasFlexibleArrayMember())
3801 return false;
3802
3803 Members = 0;
Ulrich Weiganda094f042014-10-29 13:23:20 +00003804
3805 // If this is a C++ record, check the bases first.
3806 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3807 for (const auto &I : CXXRD->bases()) {
3808 // Ignore empty records.
3809 if (isEmptyRecord(getContext(), I.getType(), true))
3810 continue;
3811
3812 uint64_t FldMembers;
3813 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
3814 return false;
3815
3816 Members += FldMembers;
3817 }
3818 }
3819
Ulrich Weigandb7122372014-07-21 00:48:09 +00003820 for (const auto *FD : RD->fields()) {
3821 // Ignore (non-zero arrays of) empty records.
3822 QualType FT = FD->getType();
3823 while (const ConstantArrayType *AT =
3824 getContext().getAsConstantArrayType(FT)) {
3825 if (AT->getSize().getZExtValue() == 0)
3826 return false;
3827 FT = AT->getElementType();
3828 }
3829 if (isEmptyRecord(getContext(), FT, true))
3830 continue;
3831
3832 // For compatibility with GCC, ignore empty bitfields in C++ mode.
3833 if (getContext().getLangOpts().CPlusPlus &&
3834 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
3835 continue;
3836
3837 uint64_t FldMembers;
3838 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
3839 return false;
3840
3841 Members = (RD->isUnion() ?
3842 std::max(Members, FldMembers) : Members + FldMembers);
3843 }
3844
3845 if (!Base)
3846 return false;
3847
3848 // Ensure there is no padding.
3849 if (getContext().getTypeSize(Base) * Members !=
3850 getContext().getTypeSize(Ty))
3851 return false;
3852 } else {
3853 Members = 1;
3854 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
3855 Members = 2;
3856 Ty = CT->getElementType();
3857 }
3858
Reid Klecknere9f6a712014-10-31 17:10:41 +00003859 // Most ABIs only support float, double, and some vector type widths.
3860 if (!isHomogeneousAggregateBaseType(Ty))
Ulrich Weigandb7122372014-07-21 00:48:09 +00003861 return false;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003862
3863 // The base type must be the same for all members. Types that
3864 // agree in both total size and mode (float vs. vector) are
3865 // treated as being equivalent here.
3866 const Type *TyPtr = Ty.getTypePtr();
3867 if (!Base)
3868 Base = TyPtr;
3869
3870 if (Base->isVectorType() != TyPtr->isVectorType() ||
3871 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
3872 return false;
3873 }
Reid Klecknere9f6a712014-10-31 17:10:41 +00003874 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
3875}
Ulrich Weigandb7122372014-07-21 00:48:09 +00003876
Reid Klecknere9f6a712014-10-31 17:10:41 +00003877bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
3878 // Homogeneous aggregates for ELFv2 must have base types of float,
3879 // double, long double, or 128-bit vectors.
3880 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3881 if (BT->getKind() == BuiltinType::Float ||
3882 BT->getKind() == BuiltinType::Double ||
3883 BT->getKind() == BuiltinType::LongDouble)
3884 return true;
3885 }
3886 if (const VectorType *VT = Ty->getAs<VectorType>()) {
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003887 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
Reid Klecknere9f6a712014-10-31 17:10:41 +00003888 return true;
3889 }
3890 return false;
3891}
3892
3893bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
3894 const Type *Base, uint64_t Members) const {
Ulrich Weigandb7122372014-07-21 00:48:09 +00003895 // Vector types require one register, floating point types require one
3896 // or two registers depending on their size.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003897 uint32_t NumRegs =
3898 Base->isVectorType() ? 1 : (getContext().getTypeSize(Base) + 63) / 64;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003899
3900 // Homogeneous Aggregates may occupy at most 8 registers.
Reid Klecknere9f6a712014-10-31 17:10:41 +00003901 return Members * NumRegs <= 8;
Ulrich Weigandb7122372014-07-21 00:48:09 +00003902}
3903
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003904ABIArgInfo
3905PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00003906 Ty = useFirstFieldIfTransparentUnion(Ty);
3907
Bill Schmidt90b22c92012-11-27 02:46:43 +00003908 if (Ty->isAnyComplexType())
3909 return ABIArgInfo::getDirect();
3910
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003911 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
3912 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003913 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003914 uint64_t Size = getContext().getTypeSize(Ty);
3915 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003916 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003917 else if (Size < 128) {
3918 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3919 return ABIArgInfo::getDirect(CoerceTy);
3920 }
3921 }
3922
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003923 if (isAggregateTypeForABI(Ty)) {
Mark Lacey3825e832013-10-06 01:33:34 +00003924 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00003925 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003926
John McCall7f416cc2015-09-08 08:05:57 +00003927 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
3928 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
Ulrich Weigandb7122372014-07-21 00:48:09 +00003929
3930 // ELFv2 homogeneous aggregates are passed as array types.
3931 const Type *Base = nullptr;
3932 uint64_t Members = 0;
3933 if (Kind == ELFv2 &&
3934 isHomogeneousAggregate(Ty, Base, Members)) {
3935 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
3936 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
3937 return ABIArgInfo::getDirect(CoerceTy);
3938 }
3939
Ulrich Weigand601957f2014-07-21 00:56:36 +00003940 // If an aggregate may end up fully in registers, we do not
3941 // use the ByVal method, but pass the aggregate as array.
3942 // This is usually beneficial since we avoid forcing the
3943 // back-end to store the argument to memory.
3944 uint64_t Bits = getContext().getTypeSize(Ty);
3945 if (Bits > 0 && Bits <= 8 * GPRBits) {
3946 llvm::Type *CoerceTy;
3947
3948 // Types up to 8 bytes are passed as integer type (which will be
3949 // properly aligned in the argument save area doubleword).
3950 if (Bits <= GPRBits)
3951 CoerceTy = llvm::IntegerType::get(getVMContext(),
3952 llvm::RoundUpToAlignment(Bits, 8));
3953 // Larger types are passed as arrays, with the base type selected
3954 // according to the required alignment in the save area.
3955 else {
3956 uint64_t RegBits = ABIAlign * 8;
3957 uint64_t NumRegs = llvm::RoundUpToAlignment(Bits, RegBits) / RegBits;
3958 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
3959 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
3960 }
3961
3962 return ABIArgInfo::getDirect(CoerceTy);
3963 }
3964
Ulrich Weigandb7122372014-07-21 00:48:09 +00003965 // All other aggregates are passed ByVal.
John McCall7f416cc2015-09-08 08:05:57 +00003966 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
3967 /*ByVal=*/true,
Ulrich Weigand581badc2014-07-10 17:20:07 +00003968 /*Realign=*/TyAlign > ABIAlign);
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00003969 }
3970
3971 return (isPromotableTypeForABI(Ty) ?
3972 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
3973}
3974
3975ABIArgInfo
3976PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
3977 if (RetTy->isVoidType())
3978 return ABIArgInfo::getIgnore();
3979
Bill Schmidta3d121c2012-12-17 04:20:17 +00003980 if (RetTy->isAnyComplexType())
3981 return ABIArgInfo::getDirect();
3982
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003983 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
3984 // or via reference (larger than 16 bytes).
Hal Finkel0d0a1a52015-03-11 19:14:15 +00003985 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003986 uint64_t Size = getContext().getTypeSize(RetTy);
3987 if (Size > 128)
John McCall7f416cc2015-09-08 08:05:57 +00003988 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandf4eba982014-07-10 16:39:01 +00003989 else if (Size < 128) {
3990 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
3991 return ABIArgInfo::getDirect(CoerceTy);
3992 }
3993 }
3994
Ulrich Weigandb7122372014-07-21 00:48:09 +00003995 if (isAggregateTypeForABI(RetTy)) {
3996 // ELFv2 homogeneous aggregates are returned as array types.
3997 const Type *Base = nullptr;
3998 uint64_t Members = 0;
3999 if (Kind == ELFv2 &&
4000 isHomogeneousAggregate(RetTy, Base, Members)) {
4001 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4002 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4003 return ABIArgInfo::getDirect(CoerceTy);
4004 }
4005
4006 // ELFv2 small aggregates are returned in up to two registers.
4007 uint64_t Bits = getContext().getTypeSize(RetTy);
4008 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4009 if (Bits == 0)
4010 return ABIArgInfo::getIgnore();
4011
4012 llvm::Type *CoerceTy;
4013 if (Bits > GPRBits) {
4014 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
Reid Kleckneree7cf842014-12-01 22:02:27 +00004015 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy, nullptr);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004016 } else
4017 CoerceTy = llvm::IntegerType::get(getVMContext(),
4018 llvm::RoundUpToAlignment(Bits, 8));
4019 return ABIArgInfo::getDirect(CoerceTy);
4020 }
4021
4022 // All other aggregates are returned indirectly.
John McCall7f416cc2015-09-08 08:05:57 +00004023 return getNaturalAlignIndirect(RetTy);
Ulrich Weigandb7122372014-07-21 00:48:09 +00004024 }
Ulrich Weigand77ed89d2012-11-05 19:13:42 +00004025
4026 return (isPromotableTypeForABI(RetTy) ?
4027 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
4028}
4029
Bill Schmidt25cb3492012-10-03 19:18:57 +00004030// Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
John McCall7f416cc2015-09-08 08:05:57 +00004031Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4032 QualType Ty) const {
4033 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4034 TypeInfo.second = getParamTypeAlignment(Ty);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004035
John McCall7f416cc2015-09-08 08:05:57 +00004036 CharUnits SlotSize = CharUnits::fromQuantity(8);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004037
Bill Schmidt924c4782013-01-14 17:45:36 +00004038 // If we have a complex type and the base type is smaller than 8 bytes,
4039 // the ABI calls for the real and imaginary parts to be right-adjusted
4040 // in separate doublewords. However, Clang expects us to produce a
4041 // pointer to a structure with the two parts packed tightly. So generate
4042 // loads of the real and imaginary parts relative to the va_list pointer,
4043 // and store them to a temporary structure.
John McCall7f416cc2015-09-08 08:05:57 +00004044 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4045 CharUnits EltSize = TypeInfo.first / 2;
4046 if (EltSize < SlotSize) {
4047 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4048 SlotSize * 2, SlotSize,
4049 SlotSize, /*AllowHigher*/ true);
4050
4051 Address RealAddr = Addr;
4052 Address ImagAddr = RealAddr;
4053 if (CGF.CGM.getDataLayout().isBigEndian()) {
4054 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4055 SlotSize - EltSize);
4056 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4057 2 * SlotSize - EltSize);
4058 } else {
4059 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4060 }
4061
4062 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4063 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4064 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4065 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4066 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4067
4068 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4069 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4070 /*init*/ true);
4071 return Temp;
Ulrich Weigandbebc55b2014-06-20 16:37:40 +00004072 }
Bill Schmidt924c4782013-01-14 17:45:36 +00004073 }
4074
John McCall7f416cc2015-09-08 08:05:57 +00004075 // Otherwise, just use the general rule.
4076 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4077 TypeInfo, SlotSize, /*AllowHigher*/ true);
Bill Schmidt25cb3492012-10-03 19:18:57 +00004078}
4079
4080static bool
4081PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4082 llvm::Value *Address) {
Roman Divackyd966e722012-05-09 18:22:46 +00004083 // This is calculated from the LLVM and GCC tables and verified
4084 // against gcc output. AFAIK all ABIs use the same encoding.
4085
4086 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4087
4088 llvm::IntegerType *i8 = CGF.Int8Ty;
4089 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4090 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4091 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4092
4093 // 0-31: r0-31, the 8-byte general-purpose registers
4094 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4095
4096 // 32-63: fp0-31, the 8-byte floating-point registers
4097 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4098
4099 // 64-76 are various 4-byte special-purpose registers:
4100 // 64: mq
4101 // 65: lr
4102 // 66: ctr
4103 // 67: ap
4104 // 68-75 cr0-7
4105 // 76: xer
4106 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4107
4108 // 77-108: v0-31, the 16-byte vector registers
4109 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4110
4111 // 109: vrsave
4112 // 110: vscr
4113 // 111: spe_acc
4114 // 112: spefscr
4115 // 113: sfp
4116 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4117
4118 return false;
4119}
John McCallea8d8bb2010-03-11 00:10:12 +00004120
Bill Schmidt25cb3492012-10-03 19:18:57 +00004121bool
4122PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4123 CodeGen::CodeGenFunction &CGF,
4124 llvm::Value *Address) const {
4125
4126 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4127}
4128
4129bool
4130PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4131 llvm::Value *Address) const {
4132
4133 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4134}
4135
Chris Lattner0cf24192010-06-28 20:05:43 +00004136//===----------------------------------------------------------------------===//
Tim Northover573cbee2014-05-24 12:52:07 +00004137// AArch64 ABI Implementation
Tim Northovera2ee4332014-03-29 15:09:45 +00004138//===----------------------------------------------------------------------===//
4139
4140namespace {
4141
Tim Northover573cbee2014-05-24 12:52:07 +00004142class AArch64ABIInfo : public ABIInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004143public:
4144 enum ABIKind {
4145 AAPCS = 0,
4146 DarwinPCS
4147 };
4148
4149private:
4150 ABIKind Kind;
4151
4152public:
Tim Northover573cbee2014-05-24 12:52:07 +00004153 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind) : ABIInfo(CGT), Kind(Kind) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004154
4155private:
4156 ABIKind getABIKind() const { return Kind; }
4157 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4158
4159 ABIArgInfo classifyReturnType(QualType RetTy) const;
Tim Northoverb047bfa2014-11-27 21:02:49 +00004160 ABIArgInfo classifyArgumentType(QualType RetTy) const;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004161 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4162 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4163 uint64_t Members) const override;
4164
Tim Northovera2ee4332014-03-29 15:09:45 +00004165 bool isIllegalVectorType(QualType Ty) const;
4166
David Blaikie1cbb9712014-11-14 19:09:44 +00004167 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00004168 if (!getCXXABI().classifyReturnType(FI))
4169 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Tim Northover5ffc0922014-04-17 10:20:38 +00004170
Tim Northoverb047bfa2014-11-27 21:02:49 +00004171 for (auto &it : FI.arguments())
4172 it.info = classifyArgumentType(it.type);
Tim Northovera2ee4332014-03-29 15:09:45 +00004173 }
4174
John McCall7f416cc2015-09-08 08:05:57 +00004175 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4176 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004177
John McCall7f416cc2015-09-08 08:05:57 +00004178 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4179 CodeGenFunction &CGF) const;
Tim Northovera2ee4332014-03-29 15:09:45 +00004180
John McCall7f416cc2015-09-08 08:05:57 +00004181 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4182 QualType Ty) const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004183 return isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4184 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4185 }
4186};
4187
Tim Northover573cbee2014-05-24 12:52:07 +00004188class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
Tim Northovera2ee4332014-03-29 15:09:45 +00004189public:
Tim Northover573cbee2014-05-24 12:52:07 +00004190 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4191 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
Tim Northovera2ee4332014-03-29 15:09:45 +00004192
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004193 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
Tim Northovera2ee4332014-03-29 15:09:45 +00004194 return "mov\tfp, fp\t\t; marker for objc_retainAutoreleaseReturnValue";
4195 }
4196
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004197 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4198 return 31;
4199 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004200
Alexander Kornienko34eb2072015-04-11 02:00:23 +00004201 bool doesReturnSlotInterfereWithArgs() const override { return false; }
Tim Northovera2ee4332014-03-29 15:09:45 +00004202};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004203}
Tim Northovera2ee4332014-03-29 15:09:45 +00004204
Tim Northoverb047bfa2014-11-27 21:02:49 +00004205ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
Reid Klecknerb1be6832014-11-15 01:41:41 +00004206 Ty = useFirstFieldIfTransparentUnion(Ty);
4207
Tim Northovera2ee4332014-03-29 15:09:45 +00004208 // Handle illegal vector types here.
4209 if (isIllegalVectorType(Ty)) {
4210 uint64_t Size = getContext().getTypeSize(Ty);
4211 if (Size <= 32) {
4212 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
Tim Northovera2ee4332014-03-29 15:09:45 +00004213 return ABIArgInfo::getDirect(ResType);
4214 }
4215 if (Size == 64) {
4216 llvm::Type *ResType =
4217 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northovera2ee4332014-03-29 15:09:45 +00004218 return ABIArgInfo::getDirect(ResType);
4219 }
4220 if (Size == 128) {
4221 llvm::Type *ResType =
4222 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northovera2ee4332014-03-29 15:09:45 +00004223 return ABIArgInfo::getDirect(ResType);
4224 }
John McCall7f416cc2015-09-08 08:05:57 +00004225 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004226 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004227
4228 if (!isAggregateTypeForABI(Ty)) {
4229 // Treat an enum type as its underlying type.
4230 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4231 Ty = EnumTy->getDecl()->getIntegerType();
4232
Tim Northovera2ee4332014-03-29 15:09:45 +00004233 return (Ty->isPromotableIntegerType() && isDarwinPCS()
4234 ? ABIArgInfo::getExtend()
4235 : ABIArgInfo::getDirect());
4236 }
4237
4238 // Structures with either a non-trivial destructor or a non-trivial
4239 // copy constructor are always indirect.
Reid Kleckner40ca9132014-05-13 22:05:45 +00004240 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004241 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
4242 CGCXXABI::RAA_DirectInMemory);
Tim Northovera2ee4332014-03-29 15:09:45 +00004243 }
4244
4245 // Empty records are always ignored on Darwin, but actually passed in C++ mode
4246 // elsewhere for GNU compatibility.
4247 if (isEmptyRecord(getContext(), Ty, true)) {
4248 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
4249 return ABIArgInfo::getIgnore();
4250
Tim Northovera2ee4332014-03-29 15:09:45 +00004251 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
4252 }
4253
4254 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
Craig Topper8a13c412014-05-21 05:09:00 +00004255 const Type *Base = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004256 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004257 if (isHomogeneousAggregate(Ty, Base, Members)) {
Tim Northoverb047bfa2014-11-27 21:02:49 +00004258 return ABIArgInfo::getDirect(
4259 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
Tim Northovera2ee4332014-03-29 15:09:45 +00004260 }
4261
4262 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
4263 uint64_t Size = getContext().getTypeSize(Ty);
4264 if (Size <= 128) {
Tim Northoverc801b4a2014-04-15 14:55:11 +00004265 unsigned Alignment = getContext().getTypeAlign(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004266 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Tim Northoverb047bfa2014-11-27 21:02:49 +00004267
Tim Northovera2ee4332014-03-29 15:09:45 +00004268 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4269 // For aggregates with 16-byte alignment, we use i128.
Tim Northoverc801b4a2014-04-15 14:55:11 +00004270 if (Alignment < 128 && Size == 128) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004271 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4272 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4273 }
4274 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4275 }
4276
John McCall7f416cc2015-09-08 08:05:57 +00004277 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Tim Northovera2ee4332014-03-29 15:09:45 +00004278}
4279
Tim Northover573cbee2014-05-24 12:52:07 +00004280ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004281 if (RetTy->isVoidType())
4282 return ABIArgInfo::getIgnore();
4283
4284 // Large vector types should be returned via memory.
4285 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
John McCall7f416cc2015-09-08 08:05:57 +00004286 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004287
4288 if (!isAggregateTypeForABI(RetTy)) {
4289 // Treat an enum type as its underlying type.
4290 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
4291 RetTy = EnumTy->getDecl()->getIntegerType();
4292
Tim Northover4dab6982014-04-18 13:46:08 +00004293 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
4294 ? ABIArgInfo::getExtend()
4295 : ABIArgInfo::getDirect());
Tim Northovera2ee4332014-03-29 15:09:45 +00004296 }
4297
Tim Northovera2ee4332014-03-29 15:09:45 +00004298 if (isEmptyRecord(getContext(), RetTy, true))
4299 return ABIArgInfo::getIgnore();
4300
Craig Topper8a13c412014-05-21 05:09:00 +00004301 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004302 uint64_t Members = 0;
4303 if (isHomogeneousAggregate(RetTy, Base, Members))
Tim Northovera2ee4332014-03-29 15:09:45 +00004304 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
4305 return ABIArgInfo::getDirect();
4306
4307 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
4308 uint64_t Size = getContext().getTypeSize(RetTy);
4309 if (Size <= 128) {
Pete Cooper635b5092015-04-17 22:16:24 +00004310 unsigned Alignment = getContext().getTypeAlign(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004311 Size = 64 * ((Size + 63) / 64); // round up to multiple of 8 bytes
Pete Cooper635b5092015-04-17 22:16:24 +00004312
4313 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
4314 // For aggregates with 16-byte alignment, we use i128.
4315 if (Alignment < 128 && Size == 128) {
4316 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
4317 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
4318 }
Tim Northovera2ee4332014-03-29 15:09:45 +00004319 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
4320 }
4321
John McCall7f416cc2015-09-08 08:05:57 +00004322 return getNaturalAlignIndirect(RetTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004323}
4324
Tim Northover573cbee2014-05-24 12:52:07 +00004325/// isIllegalVectorType - check whether the vector type is legal for AArch64.
4326bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
Tim Northovera2ee4332014-03-29 15:09:45 +00004327 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4328 // Check whether VT is legal.
4329 unsigned NumElements = VT->getNumElements();
4330 uint64_t Size = getContext().getTypeSize(VT);
4331 // NumElements should be power of 2 between 1 and 16.
4332 if ((NumElements & (NumElements - 1)) != 0 || NumElements > 16)
4333 return true;
4334 return Size != 64 && (Size != 128 || NumElements == 1);
4335 }
4336 return false;
4337}
4338
Reid Klecknere9f6a712014-10-31 17:10:41 +00004339bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4340 // Homogeneous aggregates for AAPCS64 must have base types of a floating
4341 // point type or a short-vector type. This is the same as the 32-bit ABI,
4342 // but with the difference that any floating-point type is allowed,
4343 // including __fp16.
4344 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4345 if (BT->isFloatingPoint())
4346 return true;
4347 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
4348 unsigned VecSize = getContext().getTypeSize(VT);
4349 if (VecSize == 64 || VecSize == 128)
4350 return true;
4351 }
4352 return false;
4353}
4354
4355bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
4356 uint64_t Members) const {
4357 return Members <= 4;
4358}
4359
John McCall7f416cc2015-09-08 08:05:57 +00004360Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
Tim Northoverb047bfa2014-11-27 21:02:49 +00004361 QualType Ty,
4362 CodeGenFunction &CGF) const {
4363 ABIArgInfo AI = classifyArgumentType(Ty);
Reid Klecknere9f6a712014-10-31 17:10:41 +00004364 bool IsIndirect = AI.isIndirect();
4365
Tim Northoverb047bfa2014-11-27 21:02:49 +00004366 llvm::Type *BaseTy = CGF.ConvertType(Ty);
4367 if (IsIndirect)
4368 BaseTy = llvm::PointerType::getUnqual(BaseTy);
4369 else if (AI.getCoerceToType())
4370 BaseTy = AI.getCoerceToType();
4371
4372 unsigned NumRegs = 1;
4373 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
4374 BaseTy = ArrTy->getElementType();
4375 NumRegs = ArrTy->getNumElements();
4376 }
4377 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
4378
Tim Northovera2ee4332014-03-29 15:09:45 +00004379 // The AArch64 va_list type and handling is specified in the Procedure Call
4380 // Standard, section B.4:
4381 //
4382 // struct {
4383 // void *__stack;
4384 // void *__gr_top;
4385 // void *__vr_top;
4386 // int __gr_offs;
4387 // int __vr_offs;
4388 // };
4389
4390 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
4391 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
4392 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
4393 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
Tim Northovera2ee4332014-03-29 15:09:45 +00004394
John McCall7f416cc2015-09-08 08:05:57 +00004395 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4396 CharUnits TyAlign = TyInfo.second;
4397
4398 Address reg_offs_p = Address::invalid();
4399 llvm::Value *reg_offs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004400 int reg_top_index;
John McCall7f416cc2015-09-08 08:05:57 +00004401 CharUnits reg_top_offset;
4402 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
Tim Northoverb047bfa2014-11-27 21:02:49 +00004403 if (!IsFPR) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004404 // 3 is the field number of __gr_offs
David Blaikie2e804282015-04-05 22:47:07 +00004405 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004406 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
4407 "gr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004408 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
4409 reg_top_index = 1; // field number for __gr_top
John McCall7f416cc2015-09-08 08:05:57 +00004410 reg_top_offset = CharUnits::fromQuantity(8);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004411 RegSize = llvm::RoundUpToAlignment(RegSize, 8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004412 } else {
Tim Northovera2ee4332014-03-29 15:09:45 +00004413 // 4 is the field number of __vr_offs.
David Blaikie2e804282015-04-05 22:47:07 +00004414 reg_offs_p =
John McCall7f416cc2015-09-08 08:05:57 +00004415 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
4416 "vr_offs_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004417 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
4418 reg_top_index = 2; // field number for __vr_top
John McCall7f416cc2015-09-08 08:05:57 +00004419 reg_top_offset = CharUnits::fromQuantity(16);
Tim Northoverb047bfa2014-11-27 21:02:49 +00004420 RegSize = 16 * NumRegs;
Tim Northovera2ee4332014-03-29 15:09:45 +00004421 }
4422
4423 //=======================================
4424 // Find out where argument was passed
4425 //=======================================
4426
4427 // If reg_offs >= 0 we're already using the stack for this type of
4428 // argument. We don't want to keep updating reg_offs (in case it overflows,
4429 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
4430 // whatever they get).
Craig Topper8a13c412014-05-21 05:09:00 +00004431 llvm::Value *UsingStack = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004432 UsingStack = CGF.Builder.CreateICmpSGE(
4433 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
4434
4435 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
4436
4437 // Otherwise, at least some kind of argument could go in these registers, the
Bob Wilson3abf1692014-04-21 01:23:36 +00004438 // question is whether this particular type is too big.
Tim Northovera2ee4332014-03-29 15:09:45 +00004439 CGF.EmitBlock(MaybeRegBlock);
4440
4441 // Integer arguments may need to correct register alignment (for example a
4442 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
4443 // align __gr_offs to calculate the potential address.
John McCall7f416cc2015-09-08 08:05:57 +00004444 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
4445 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004446
4447 reg_offs = CGF.Builder.CreateAdd(
4448 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
4449 "align_regoffs");
4450 reg_offs = CGF.Builder.CreateAnd(
4451 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
4452 "aligned_regoffs");
4453 }
4454
4455 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
John McCall7f416cc2015-09-08 08:05:57 +00004456 // The fact that this is done unconditionally reflects the fact that
4457 // allocating an argument to the stack also uses up all the remaining
4458 // registers of the appropriate kind.
Craig Topper8a13c412014-05-21 05:09:00 +00004459 llvm::Value *NewOffset = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004460 NewOffset = CGF.Builder.CreateAdd(
4461 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
4462 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
4463
4464 // Now we're in a position to decide whether this argument really was in
4465 // registers or not.
Craig Topper8a13c412014-05-21 05:09:00 +00004466 llvm::Value *InRegs = nullptr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004467 InRegs = CGF.Builder.CreateICmpSLE(
4468 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
4469
4470 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
4471
4472 //=======================================
4473 // Argument was in registers
4474 //=======================================
4475
4476 // Now we emit the code for if the argument was originally passed in
4477 // registers. First start the appropriate block:
4478 CGF.EmitBlock(InRegBlock);
4479
John McCall7f416cc2015-09-08 08:05:57 +00004480 llvm::Value *reg_top = nullptr;
4481 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
4482 reg_top_offset, "reg_top_p");
Tim Northovera2ee4332014-03-29 15:09:45 +00004483 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
John McCall7f416cc2015-09-08 08:05:57 +00004484 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
4485 CharUnits::fromQuantity(IsFPR ? 16 : 8));
4486 Address RegAddr = Address::invalid();
4487 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004488
4489 if (IsIndirect) {
4490 // If it's been passed indirectly (actually a struct), whatever we find from
4491 // stored registers or on the stack will actually be a struct **.
4492 MemTy = llvm::PointerType::getUnqual(MemTy);
4493 }
4494
Craig Topper8a13c412014-05-21 05:09:00 +00004495 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004496 uint64_t NumMembers = 0;
4497 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
James Molloy467be602014-05-07 14:45:55 +00004498 if (IsHFA && NumMembers > 1) {
Tim Northovera2ee4332014-03-29 15:09:45 +00004499 // Homogeneous aggregates passed in registers will have their elements split
4500 // and stored 16-bytes apart regardless of size (they're notionally in qN,
4501 // qN+1, ...). We reload and store into a temporary local variable
4502 // contiguously.
4503 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
John McCall7f416cc2015-09-08 08:05:57 +00004504 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
Tim Northovera2ee4332014-03-29 15:09:45 +00004505 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
4506 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
John McCall7f416cc2015-09-08 08:05:57 +00004507 Address Tmp = CGF.CreateTempAlloca(HFATy,
4508 std::max(TyAlign, BaseTyInfo.second));
Tim Northovera2ee4332014-03-29 15:09:45 +00004509
John McCall7f416cc2015-09-08 08:05:57 +00004510 // On big-endian platforms, the value will be right-aligned in its slot.
4511 int Offset = 0;
4512 if (CGF.CGM.getDataLayout().isBigEndian() &&
4513 BaseTyInfo.first.getQuantity() < 16)
4514 Offset = 16 - BaseTyInfo.first.getQuantity();
4515
Tim Northovera2ee4332014-03-29 15:09:45 +00004516 for (unsigned i = 0; i < NumMembers; ++i) {
John McCall7f416cc2015-09-08 08:05:57 +00004517 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
4518 Address LoadAddr =
4519 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
4520 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
4521
4522 Address StoreAddr =
4523 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
Tim Northovera2ee4332014-03-29 15:09:45 +00004524
4525 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
4526 CGF.Builder.CreateStore(Elem, StoreAddr);
4527 }
4528
John McCall7f416cc2015-09-08 08:05:57 +00004529 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004530 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004531 // Otherwise the object is contiguous in memory.
4532
4533 // It might be right-aligned in its slot.
4534 CharUnits SlotSize = BaseAddr.getAlignment();
4535 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
James Molloy467be602014-05-07 14:45:55 +00004536 (IsHFA || !isAggregateTypeForABI(Ty)) &&
John McCall7f416cc2015-09-08 08:05:57 +00004537 TyInfo.first < SlotSize) {
4538 CharUnits Offset = SlotSize - TyInfo.first;
4539 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004540 }
4541
John McCall7f416cc2015-09-08 08:05:57 +00004542 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004543 }
4544
4545 CGF.EmitBranch(ContBlock);
4546
4547 //=======================================
4548 // Argument was on the stack
4549 //=======================================
4550 CGF.EmitBlock(OnStackBlock);
4551
John McCall7f416cc2015-09-08 08:05:57 +00004552 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
4553 CharUnits::Zero(), "stack_p");
4554 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004555
John McCall7f416cc2015-09-08 08:05:57 +00004556 // Again, stack arguments may need realignment. In this case both integer and
Tim Northovera2ee4332014-03-29 15:09:45 +00004557 // floating-point ones might be affected.
John McCall7f416cc2015-09-08 08:05:57 +00004558 if (!IsIndirect && TyAlign.getQuantity() > 8) {
4559 int Align = TyAlign.getQuantity();
Tim Northovera2ee4332014-03-29 15:09:45 +00004560
John McCall7f416cc2015-09-08 08:05:57 +00004561 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
Tim Northovera2ee4332014-03-29 15:09:45 +00004562
John McCall7f416cc2015-09-08 08:05:57 +00004563 OnStackPtr = CGF.Builder.CreateAdd(
4564 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
Tim Northovera2ee4332014-03-29 15:09:45 +00004565 "align_stack");
John McCall7f416cc2015-09-08 08:05:57 +00004566 OnStackPtr = CGF.Builder.CreateAnd(
4567 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
Tim Northovera2ee4332014-03-29 15:09:45 +00004568 "align_stack");
4569
John McCall7f416cc2015-09-08 08:05:57 +00004570 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004571 }
John McCall7f416cc2015-09-08 08:05:57 +00004572 Address OnStackAddr(OnStackPtr,
4573 std::max(CharUnits::fromQuantity(8), TyAlign));
Tim Northovera2ee4332014-03-29 15:09:45 +00004574
John McCall7f416cc2015-09-08 08:05:57 +00004575 // All stack slots are multiples of 8 bytes.
4576 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
4577 CharUnits StackSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004578 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004579 StackSize = StackSlotSize;
Tim Northovera2ee4332014-03-29 15:09:45 +00004580 else
John McCall7f416cc2015-09-08 08:05:57 +00004581 StackSize = TyInfo.first.RoundUpToAlignment(StackSlotSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004582
John McCall7f416cc2015-09-08 08:05:57 +00004583 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
Tim Northovera2ee4332014-03-29 15:09:45 +00004584 llvm::Value *NewStack =
John McCall7f416cc2015-09-08 08:05:57 +00004585 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
Tim Northovera2ee4332014-03-29 15:09:45 +00004586
4587 // Write the new value of __stack for the next call to va_arg
4588 CGF.Builder.CreateStore(NewStack, stack_p);
4589
4590 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
John McCall7f416cc2015-09-08 08:05:57 +00004591 TyInfo.first < StackSlotSize) {
4592 CharUnits Offset = StackSlotSize - TyInfo.first;
4593 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
Tim Northovera2ee4332014-03-29 15:09:45 +00004594 }
4595
John McCall7f416cc2015-09-08 08:05:57 +00004596 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
Tim Northovera2ee4332014-03-29 15:09:45 +00004597
4598 CGF.EmitBranch(ContBlock);
4599
4600 //=======================================
4601 // Tidy up
4602 //=======================================
4603 CGF.EmitBlock(ContBlock);
4604
John McCall7f416cc2015-09-08 08:05:57 +00004605 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
4606 OnStackAddr, OnStackBlock, "vaargs.addr");
Tim Northovera2ee4332014-03-29 15:09:45 +00004607
4608 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00004609 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
4610 TyInfo.second);
Tim Northovera2ee4332014-03-29 15:09:45 +00004611
4612 return ResAddr;
4613}
4614
John McCall7f416cc2015-09-08 08:05:57 +00004615Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4616 CodeGenFunction &CGF) const {
4617 // The backend's lowering doesn't support va_arg for aggregates or
4618 // illegal vector types. Lower VAArg here for these cases and use
4619 // the LLVM va_arg instruction for everything else.
Tim Northovera2ee4332014-03-29 15:09:45 +00004620 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00004621 return Address::invalid();
Tim Northovera2ee4332014-03-29 15:09:45 +00004622
John McCall7f416cc2015-09-08 08:05:57 +00004623 CharUnits SlotSize = CharUnits::fromQuantity(8);
Tim Northovera2ee4332014-03-29 15:09:45 +00004624
John McCall7f416cc2015-09-08 08:05:57 +00004625 // Empty records are ignored for parameter passing purposes.
Tim Northovera2ee4332014-03-29 15:09:45 +00004626 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00004627 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
4628 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
4629 return Addr;
Tim Northovera2ee4332014-03-29 15:09:45 +00004630 }
4631
John McCall7f416cc2015-09-08 08:05:57 +00004632 // The size of the actual thing passed, which might end up just
4633 // being a pointer for indirect types.
4634 auto TyInfo = getContext().getTypeInfoInChars(Ty);
4635
4636 // Arguments bigger than 16 bytes which aren't homogeneous
4637 // aggregates should be passed indirectly.
4638 bool IsIndirect = false;
4639 if (TyInfo.first.getQuantity() > 16) {
4640 const Type *Base = nullptr;
4641 uint64_t Members = 0;
4642 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
Tim Northovera2ee4332014-03-29 15:09:45 +00004643 }
4644
John McCall7f416cc2015-09-08 08:05:57 +00004645 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4646 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
Tim Northovera2ee4332014-03-29 15:09:45 +00004647}
4648
4649//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004650// ARM ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00004651//===----------------------------------------------------------------------===//
Daniel Dunbard59655c2009-09-12 00:59:49 +00004652
4653namespace {
4654
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004655class ARMABIInfo : public ABIInfo {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004656public:
4657 enum ABIKind {
4658 APCS = 0,
4659 AAPCS = 1,
4660 AAPCS_VFP
4661 };
4662
4663private:
4664 ABIKind Kind;
4665
4666public:
Tim Northoverbc784d12015-02-24 17:22:40 +00004667 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind) : ABIInfo(CGT), Kind(_Kind) {
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004668 setCCs();
John McCall882987f2013-02-28 19:01:20 +00004669 }
Daniel Dunbar020daa92009-09-12 01:00:39 +00004670
John McCall3480ef22011-08-30 01:42:09 +00004671 bool isEABI() const {
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004672 switch (getTarget().getTriple().getEnvironment()) {
4673 case llvm::Triple::Android:
4674 case llvm::Triple::EABI:
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004675 case llvm::Triple::EABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004676 case llvm::Triple::GNUEABI:
Joerg Sonnenberger0c1652d2013-12-16 18:30:28 +00004677 case llvm::Triple::GNUEABIHF:
Joerg Sonnenberger782e6aa2013-12-12 21:29:27 +00004678 return true;
4679 default:
4680 return false;
4681 }
John McCall3480ef22011-08-30 01:42:09 +00004682 }
4683
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004684 bool isEABIHF() const {
4685 switch (getTarget().getTriple().getEnvironment()) {
4686 case llvm::Triple::EABIHF:
4687 case llvm::Triple::GNUEABIHF:
4688 return true;
4689 default:
4690 return false;
4691 }
4692 }
4693
Daniel Dunbar020daa92009-09-12 01:00:39 +00004694 ABIKind getABIKind() const { return Kind; }
4695
Tim Northovera484bc02013-10-01 14:34:25 +00004696private:
Amara Emerson9dc78782014-01-28 10:56:36 +00004697 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
Tim Northoverbc784d12015-02-24 17:22:40 +00004698 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
Manman Renfef9e312012-10-16 19:18:39 +00004699 bool isIllegalVectorType(QualType Ty) const;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004700
Reid Klecknere9f6a712014-10-31 17:10:41 +00004701 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4702 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4703 uint64_t Members) const override;
4704
Craig Topper4f12f102014-03-12 06:41:41 +00004705 void computeInfo(CGFunctionInfo &FI) const override;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004706
John McCall7f416cc2015-09-08 08:05:57 +00004707 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4708 QualType Ty) const override;
John McCall882987f2013-02-28 19:01:20 +00004709
4710 llvm::CallingConv::ID getLLVMDefaultCC() const;
4711 llvm::CallingConv::ID getABIDefaultCC() const;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004712 void setCCs();
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004713};
4714
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004715class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
4716public:
Chris Lattner2b037972010-07-29 02:01:43 +00004717 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4718 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
John McCallbeec5a02010-03-06 00:35:14 +00004719
John McCall3480ef22011-08-30 01:42:09 +00004720 const ARMABIInfo &getABIInfo() const {
4721 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
4722 }
4723
Craig Topper4f12f102014-03-12 06:41:41 +00004724 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
John McCallbeec5a02010-03-06 00:35:14 +00004725 return 13;
4726 }
Roman Divackyc1617352011-05-18 19:36:54 +00004727
Craig Topper4f12f102014-03-12 06:41:41 +00004728 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
John McCall31168b02011-06-15 23:02:42 +00004729 return "mov\tr7, r7\t\t@ marker for objc_retainAutoreleaseReturnValue";
4730 }
4731
Roman Divackyc1617352011-05-18 19:36:54 +00004732 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00004733 llvm::Value *Address) const override {
Chris Lattnerece04092012-02-07 00:39:47 +00004734 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
Roman Divackyc1617352011-05-18 19:36:54 +00004735
4736 // 0-15 are the 16 integer registers.
Chris Lattnerece04092012-02-07 00:39:47 +00004737 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
Roman Divackyc1617352011-05-18 19:36:54 +00004738 return false;
4739 }
John McCall3480ef22011-08-30 01:42:09 +00004740
Craig Topper4f12f102014-03-12 06:41:41 +00004741 unsigned getSizeOfUnwindException() const override {
John McCall3480ef22011-08-30 01:42:09 +00004742 if (getABIInfo().isEABI()) return 88;
4743 return TargetCodeGenInfo::getSizeOfUnwindException();
4744 }
Tim Northovera484bc02013-10-01 14:34:25 +00004745
Eric Christopher162c91c2015-06-05 22:03:00 +00004746 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00004747 CodeGen::CodeGenModule &CGM) const override {
Tim Northovera484bc02013-10-01 14:34:25 +00004748 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
4749 if (!FD)
4750 return;
4751
4752 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
4753 if (!Attr)
4754 return;
4755
4756 const char *Kind;
4757 switch (Attr->getInterrupt()) {
4758 case ARMInterruptAttr::Generic: Kind = ""; break;
4759 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
4760 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
4761 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
4762 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
4763 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
4764 }
4765
4766 llvm::Function *Fn = cast<llvm::Function>(GV);
4767
4768 Fn->addFnAttr("interrupt", Kind);
4769
4770 if (cast<ARMABIInfo>(getABIInfo()).getABIKind() == ARMABIInfo::APCS)
4771 return;
4772
4773 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
4774 // however this is not necessarily true on taking any interrupt. Instruct
4775 // the backend to perform a realignment as part of the function prologue.
4776 llvm::AttrBuilder B;
4777 B.addStackAlignmentAttr(8);
4778 Fn->addAttributes(llvm::AttributeSet::FunctionIndex,
4779 llvm::AttributeSet::get(CGM.getLLVMContext(),
4780 llvm::AttributeSet::FunctionIndex,
4781 B));
4782 }
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00004783};
4784
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004785class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
4786 void addStackProbeSizeTargetAttribute(const Decl *D, llvm::GlobalValue *GV,
4787 CodeGen::CodeGenModule &CGM) const;
4788
4789public:
4790 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
4791 : ARMTargetCodeGenInfo(CGT, K) {}
4792
Eric Christopher162c91c2015-06-05 22:03:00 +00004793 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004794 CodeGen::CodeGenModule &CGM) const override;
4795};
4796
4797void WindowsARMTargetCodeGenInfo::addStackProbeSizeTargetAttribute(
4798 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
4799 if (!isa<FunctionDecl>(D))
4800 return;
4801 if (CGM.getCodeGenOpts().StackProbeSize == 4096)
4802 return;
4803
4804 llvm::Function *F = cast<llvm::Function>(GV);
4805 F->addFnAttr("stack-probe-size",
4806 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
4807}
4808
Eric Christopher162c91c2015-06-05 22:03:00 +00004809void WindowsARMTargetCodeGenInfo::setTargetAttributes(
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004810 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
Eric Christopher162c91c2015-06-05 22:03:00 +00004811 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00004812 addStackProbeSizeTargetAttribute(D, GV, CGM);
4813}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004814}
Daniel Dunbard59655c2009-09-12 00:59:49 +00004815
Chris Lattner22326a12010-07-29 02:31:05 +00004816void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
Tim Northoverbc784d12015-02-24 17:22:40 +00004817 if (!getCXXABI().classifyReturnType(FI))
Eric Christopher7565e0d2015-05-29 23:09:49 +00004818 FI.getReturnInfo() =
4819 classifyReturnType(FI.getReturnType(), FI.isVariadic());
Oliver Stannard405bded2014-02-11 09:25:50 +00004820
Tim Northoverbc784d12015-02-24 17:22:40 +00004821 for (auto &I : FI.arguments())
4822 I.info = classifyArgumentType(I.type, FI.isVariadic());
Daniel Dunbar020daa92009-09-12 01:00:39 +00004823
Anton Korobeynikov231e8752011-04-14 20:06:49 +00004824 // Always honor user-specified calling convention.
4825 if (FI.getCallingConvention() != llvm::CallingConv::C)
4826 return;
4827
John McCall882987f2013-02-28 19:01:20 +00004828 llvm::CallingConv::ID cc = getRuntimeCC();
4829 if (cc != llvm::CallingConv::C)
Tim Northoverbc784d12015-02-24 17:22:40 +00004830 FI.setEffectiveCallingConvention(cc);
John McCall882987f2013-02-28 19:01:20 +00004831}
Rafael Espindolaa92c4422010-06-16 16:13:39 +00004832
John McCall882987f2013-02-28 19:01:20 +00004833/// Return the default calling convention that LLVM will use.
4834llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
4835 // The default calling convention that LLVM will infer.
Joerg Sonnenbergerd75a1f82013-12-16 19:16:04 +00004836 if (isEABIHF())
John McCall882987f2013-02-28 19:01:20 +00004837 return llvm::CallingConv::ARM_AAPCS_VFP;
4838 else if (isEABI())
4839 return llvm::CallingConv::ARM_AAPCS;
4840 else
4841 return llvm::CallingConv::ARM_APCS;
4842}
4843
4844/// Return the calling convention that our ABI would like us to use
4845/// as the C calling convention.
4846llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
Daniel Dunbar020daa92009-09-12 01:00:39 +00004847 switch (getABIKind()) {
John McCall882987f2013-02-28 19:01:20 +00004848 case APCS: return llvm::CallingConv::ARM_APCS;
4849 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
4850 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
Daniel Dunbar020daa92009-09-12 01:00:39 +00004851 }
John McCall882987f2013-02-28 19:01:20 +00004852 llvm_unreachable("bad ABI kind");
4853}
4854
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004855void ARMABIInfo::setCCs() {
John McCall882987f2013-02-28 19:01:20 +00004856 assert(getRuntimeCC() == llvm::CallingConv::C);
4857
4858 // Don't muddy up the IR with a ton of explicit annotations if
4859 // they'd just match what LLVM will infer from the triple.
4860 llvm::CallingConv::ID abiCC = getABIDefaultCC();
4861 if (abiCC != getLLVMDefaultCC())
4862 RuntimeCC = abiCC;
Anton Korobeynikovd90dd792014-12-02 16:04:58 +00004863
4864 BuiltinCC = (getABIKind() == APCS ?
4865 llvm::CallingConv::ARM_APCS : llvm::CallingConv::ARM_AAPCS);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004866}
4867
Tim Northoverbc784d12015-02-24 17:22:40 +00004868ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
4869 bool isVariadic) const {
Manman Ren2a523d82012-10-30 23:21:41 +00004870 // 6.1.2.1 The following argument types are VFP CPRCs:
4871 // A single-precision floating-point type (including promoted
4872 // half-precision types); A double-precision floating-point type;
4873 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
4874 // with a Base Type of a single- or double-precision floating-point type,
4875 // 64-bit containerized vectors or 128-bit containerized vectors with one
4876 // to four Elements.
Tim Northover5a1558e2014-11-07 22:30:50 +00004877 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00004878
Reid Klecknerb1be6832014-11-15 01:41:41 +00004879 Ty = useFirstFieldIfTransparentUnion(Ty);
4880
Manman Renfef9e312012-10-16 19:18:39 +00004881 // Handle illegal vector types here.
4882 if (isIllegalVectorType(Ty)) {
4883 uint64_t Size = getContext().getTypeSize(Ty);
4884 if (Size <= 32) {
4885 llvm::Type *ResType =
4886 llvm::Type::getInt32Ty(getVMContext());
Tim Northover5a1558e2014-11-07 22:30:50 +00004887 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004888 }
4889 if (Size == 64) {
4890 llvm::Type *ResType = llvm::VectorType::get(
4891 llvm::Type::getInt32Ty(getVMContext()), 2);
Tim Northover5a1558e2014-11-07 22:30:50 +00004892 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004893 }
4894 if (Size == 128) {
4895 llvm::Type *ResType = llvm::VectorType::get(
4896 llvm::Type::getInt32Ty(getVMContext()), 4);
Tim Northover5a1558e2014-11-07 22:30:50 +00004897 return ABIArgInfo::getDirect(ResType);
Manman Renfef9e312012-10-16 19:18:39 +00004898 }
John McCall7f416cc2015-09-08 08:05:57 +00004899 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Manman Renfef9e312012-10-16 19:18:39 +00004900 }
4901
Oliver Stannarddc2854c2015-09-03 12:40:58 +00004902 // __fp16 gets passed as if it were an int or float, but with the top 16 bits
4903 // unspecified. This is not done for OpenCL as it handles the half type
4904 // natively, and does not need to interwork with AAPCS code.
4905 if (Ty->isHalfType() && !getContext().getLangOpts().OpenCL) {
4906 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
4907 llvm::Type::getFloatTy(getVMContext()) :
4908 llvm::Type::getInt32Ty(getVMContext());
4909 return ABIArgInfo::getDirect(ResType);
4910 }
4911
John McCalla1dee5302010-08-22 10:59:02 +00004912 if (!isAggregateTypeForABI(Ty)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004913 // Treat an enum type as its underlying type.
Oliver Stannard405bded2014-02-11 09:25:50 +00004914 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
Douglas Gregora71cc152010-02-02 20:10:50 +00004915 Ty = EnumTy->getDecl()->getIntegerType();
Oliver Stannard405bded2014-02-11 09:25:50 +00004916 }
Douglas Gregora71cc152010-02-02 20:10:50 +00004917
Tim Northover5a1558e2014-11-07 22:30:50 +00004918 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend()
4919 : ABIArgInfo::getDirect());
Douglas Gregora71cc152010-02-02 20:10:50 +00004920 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004921
Oliver Stannard405bded2014-02-11 09:25:50 +00004922 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
John McCall7f416cc2015-09-08 08:05:57 +00004923 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Oliver Stannard405bded2014-02-11 09:25:50 +00004924 }
Tim Northover1060eae2013-06-21 22:49:34 +00004925
Daniel Dunbar09d33622009-09-14 21:54:03 +00004926 // Ignore empty records.
Chris Lattner458b2aa2010-07-29 02:16:43 +00004927 if (isEmptyRecord(getContext(), Ty, true))
Daniel Dunbar09d33622009-09-14 21:54:03 +00004928 return ABIArgInfo::getIgnore();
4929
Tim Northover5a1558e2014-11-07 22:30:50 +00004930 if (IsEffectivelyAAPCS_VFP) {
Manman Ren2a523d82012-10-30 23:21:41 +00004931 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
4932 // into VFP registers.
Craig Topper8a13c412014-05-21 05:09:00 +00004933 const Type *Base = nullptr;
Manman Ren2a523d82012-10-30 23:21:41 +00004934 uint64_t Members = 0;
Reid Klecknere9f6a712014-10-31 17:10:41 +00004935 if (isHomogeneousAggregate(Ty, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004936 assert(Base && "Base class should be set for homogeneous aggregate");
Manman Ren2a523d82012-10-30 23:21:41 +00004937 // Base can be a floating-point or a vector.
Tim Northover5a1558e2014-11-07 22:30:50 +00004938 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00004939 }
Bob Wilsone826a2a2011-08-03 05:58:22 +00004940 }
4941
Manman Ren6c30e132012-08-13 21:23:55 +00004942 // Support byval for ARM.
Manman Ren77b02382012-11-06 19:05:29 +00004943 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
4944 // most 8-byte. We realign the indirect argument if type alignment is bigger
4945 // than ABI alignment.
Manman Ren505d68f2012-11-05 22:42:46 +00004946 uint64_t ABIAlign = 4;
4947 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
4948 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
Tim Northoverd157e192015-03-09 21:40:42 +00004949 getABIKind() == ARMABIInfo::AAPCS)
Manman Ren505d68f2012-11-05 22:42:46 +00004950 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
Tim Northoverd157e192015-03-09 21:40:42 +00004951
Manman Ren8cd99812012-11-06 04:58:01 +00004952 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
John McCall7f416cc2015-09-08 08:05:57 +00004953 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4954 /*ByVal=*/true,
4955 /*Realign=*/TyAlign > ABIAlign);
Eli Friedmane66abda2012-08-09 00:31:40 +00004956 }
4957
Daniel Dunbarb34b0802010-09-23 01:54:28 +00004958 // Otherwise, pass by coercing to a structure of the appropriate size.
Chris Lattner2192fe52011-07-18 04:24:23 +00004959 llvm::Type* ElemTy;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004960 unsigned SizeRegs;
Eli Friedmane66abda2012-08-09 00:31:40 +00004961 // FIXME: Try to match the types of the arguments more accurately where
4962 // we can.
4963 if (getContext().getTypeAlign(Ty) <= 32) {
Bob Wilson8e2b75d2011-08-01 23:39:04 +00004964 ElemTy = llvm::Type::getInt32Ty(getVMContext());
4965 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
Manman Ren6fdb1582012-06-25 22:04:00 +00004966 } else {
Manman Ren6fdb1582012-06-25 22:04:00 +00004967 ElemTy = llvm::Type::getInt64Ty(getVMContext());
4968 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
Stuart Hastingsf2752a32011-04-27 17:24:02 +00004969 }
Stuart Hastings4b214952011-04-28 18:16:06 +00004970
Tim Northover5a1558e2014-11-07 22:30:50 +00004971 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00004972}
4973
Chris Lattner458b2aa2010-07-29 02:16:43 +00004974static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004975 llvm::LLVMContext &VMContext) {
4976 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
4977 // is called integer-like if its size is less than or equal to one word, and
4978 // the offset of each of its addressable sub-fields is zero.
4979
4980 uint64_t Size = Context.getTypeSize(Ty);
4981
4982 // Check that the type fits in a word.
4983 if (Size > 32)
4984 return false;
4985
4986 // FIXME: Handle vector types!
4987 if (Ty->isVectorType())
4988 return false;
4989
Daniel Dunbard53bac72009-09-14 02:20:34 +00004990 // Float types are never treated as "integer like".
4991 if (Ty->isRealFloatingType())
4992 return false;
4993
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004994 // If this is a builtin or pointer type then it is ok.
John McCall9dd450b2009-09-21 23:43:11 +00004995 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
Daniel Dunbar626f1d82009-09-13 08:03:58 +00004996 return true;
4997
Daniel Dunbar96ebba52010-02-01 23:31:26 +00004998 // Small complex integer types are "integer like".
4999 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5000 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005001
5002 // Single element and zero sized arrays should be allowed, by the definition
5003 // above, but they are not.
5004
5005 // Otherwise, it must be a record type.
5006 const RecordType *RT = Ty->getAs<RecordType>();
5007 if (!RT) return false;
5008
5009 // Ignore records with flexible arrays.
5010 const RecordDecl *RD = RT->getDecl();
5011 if (RD->hasFlexibleArrayMember())
5012 return false;
5013
5014 // Check that all sub-fields are at offset 0, and are themselves "integer
5015 // like".
5016 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5017
5018 bool HadField = false;
5019 unsigned idx = 0;
5020 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5021 i != e; ++i, ++idx) {
David Blaikie40ed2972012-06-06 20:45:41 +00005022 const FieldDecl *FD = *i;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005023
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005024 // Bit-fields are not addressable, we only need to verify they are "integer
5025 // like". We still have to disallow a subsequent non-bitfield, for example:
5026 // struct { int : 0; int x }
5027 // is non-integer like according to gcc.
5028 if (FD->isBitField()) {
5029 if (!RD->isUnion())
5030 HadField = true;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005031
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005032 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5033 return false;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005034
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005035 continue;
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005036 }
5037
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005038 // Check if this field is at offset 0.
5039 if (Layout.getFieldOffset(idx) != 0)
5040 return false;
5041
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005042 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5043 return false;
Michael J. Spencerb2f376b2010-08-25 18:17:27 +00005044
Daniel Dunbar45c7ff12010-01-29 03:22:29 +00005045 // Only allow at most one field in a structure. This doesn't match the
5046 // wording above, but follows gcc in situations with a field following an
5047 // empty structure.
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005048 if (!RD->isUnion()) {
5049 if (HadField)
5050 return false;
5051
5052 HadField = true;
5053 }
5054 }
5055
5056 return true;
5057}
5058
Oliver Stannard405bded2014-02-11 09:25:50 +00005059ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5060 bool isVariadic) const {
Tim Northover5a1558e2014-11-07 22:30:50 +00005061 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005062
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005063 if (RetTy->isVoidType())
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005064 return ABIArgInfo::getIgnore();
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005065
Daniel Dunbar19964db2010-09-23 01:54:32 +00005066 // Large vector types should be returned via memory.
Oliver Stannard405bded2014-02-11 09:25:50 +00005067 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
John McCall7f416cc2015-09-08 08:05:57 +00005068 return getNaturalAlignIndirect(RetTy);
Oliver Stannard405bded2014-02-11 09:25:50 +00005069 }
Daniel Dunbar19964db2010-09-23 01:54:32 +00005070
Oliver Stannarddc2854c2015-09-03 12:40:58 +00005071 // __fp16 gets returned as if it were an int or float, but with the top 16
5072 // bits unspecified. This is not done for OpenCL as it handles the half type
5073 // natively, and does not need to interwork with AAPCS code.
5074 if (RetTy->isHalfType() && !getContext().getLangOpts().OpenCL) {
5075 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5076 llvm::Type::getFloatTy(getVMContext()) :
5077 llvm::Type::getInt32Ty(getVMContext());
5078 return ABIArgInfo::getDirect(ResType);
5079 }
5080
John McCalla1dee5302010-08-22 10:59:02 +00005081 if (!isAggregateTypeForABI(RetTy)) {
Douglas Gregora71cc152010-02-02 20:10:50 +00005082 // Treat an enum type as its underlying type.
5083 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5084 RetTy = EnumTy->getDecl()->getIntegerType();
5085
Tim Northover5a1558e2014-11-07 22:30:50 +00005086 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend()
5087 : ABIArgInfo::getDirect();
Douglas Gregora71cc152010-02-02 20:10:50 +00005088 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005089
5090 // Are we following APCS?
5091 if (getABIKind() == APCS) {
Chris Lattner458b2aa2010-07-29 02:16:43 +00005092 if (isEmptyRecord(getContext(), RetTy, false))
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005093 return ABIArgInfo::getIgnore();
5094
Daniel Dunbareedf1512010-02-01 23:31:19 +00005095 // Complex types are all returned as packed integers.
5096 //
5097 // FIXME: Consider using 2 x vector types if the back end handles them
5098 // correctly.
5099 if (RetTy->isAnyComplexType())
Oliver Stannard2bfdc5b2014-08-27 10:43:15 +00005100 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5101 getVMContext(), getContext().getTypeSize(RetTy)));
Daniel Dunbareedf1512010-02-01 23:31:19 +00005102
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005103 // Integer like structures are returned in r0.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005104 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005105 // Return in the smallest viable integer type.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005106 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005107 if (Size <= 8)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005108 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005109 if (Size <= 16)
Chris Lattnerfe34c1d2010-07-29 06:26:06 +00005110 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5111 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005112 }
5113
5114 // Otherwise return in memory.
John McCall7f416cc2015-09-08 08:05:57 +00005115 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005116 }
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005117
5118 // Otherwise this is an AAPCS variant.
5119
Chris Lattner458b2aa2010-07-29 02:16:43 +00005120 if (isEmptyRecord(getContext(), RetTy, true))
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005121 return ABIArgInfo::getIgnore();
5122
Bob Wilson1d9269a2011-11-02 04:51:36 +00005123 // Check for homogeneous aggregates with AAPCS-VFP.
Tim Northover5a1558e2014-11-07 22:30:50 +00005124 if (IsEffectivelyAAPCS_VFP) {
Craig Topper8a13c412014-05-21 05:09:00 +00005125 const Type *Base = nullptr;
Reid Klecknere9f6a712014-10-31 17:10:41 +00005126 uint64_t Members;
5127 if (isHomogeneousAggregate(RetTy, Base, Members)) {
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005128 assert(Base && "Base class should be set for homogeneous aggregate");
Bob Wilson1d9269a2011-11-02 04:51:36 +00005129 // Homogeneous Aggregates are returned directly.
Tim Northover5a1558e2014-11-07 22:30:50 +00005130 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
Anton Korobeynikov4215ca72012-04-13 11:22:00 +00005131 }
Bob Wilson1d9269a2011-11-02 04:51:36 +00005132 }
5133
Daniel Dunbar626f1d82009-09-13 08:03:58 +00005134 // Aggregates <= 4 bytes are returned in r0; other aggregates
5135 // are returned indirectly.
Chris Lattner458b2aa2010-07-29 02:16:43 +00005136 uint64_t Size = getContext().getTypeSize(RetTy);
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005137 if (Size <= 32) {
Christian Pirkerc3d32172014-07-03 09:28:12 +00005138 if (getDataLayout().isBigEndian())
5139 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
Tim Northover5a1558e2014-11-07 22:30:50 +00005140 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Christian Pirkerc3d32172014-07-03 09:28:12 +00005141
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005142 // Return in the smallest viable integer type.
5143 if (Size <= 8)
Tim Northover5a1558e2014-11-07 22:30:50 +00005144 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005145 if (Size <= 16)
Tim Northover5a1558e2014-11-07 22:30:50 +00005146 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5147 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
Daniel Dunbar1ce72512009-09-14 00:56:55 +00005148 }
5149
John McCall7f416cc2015-09-08 08:05:57 +00005150 return getNaturalAlignIndirect(RetTy);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005151}
5152
Manman Renfef9e312012-10-16 19:18:39 +00005153/// isIllegalVector - check whether Ty is an illegal vector type.
5154bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
5155 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5156 // Check whether VT is legal.
5157 unsigned NumElements = VT->getNumElements();
5158 uint64_t Size = getContext().getTypeSize(VT);
5159 // NumElements should be power of 2.
5160 if ((NumElements & (NumElements - 1)) != 0)
5161 return true;
5162 // Size should be greater than 32 bits.
5163 return Size <= 32;
5164 }
5165 return false;
5166}
5167
Reid Klecknere9f6a712014-10-31 17:10:41 +00005168bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5169 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
5170 // double, or 64-bit or 128-bit vectors.
5171 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5172 if (BT->getKind() == BuiltinType::Float ||
5173 BT->getKind() == BuiltinType::Double ||
5174 BT->getKind() == BuiltinType::LongDouble)
5175 return true;
5176 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5177 unsigned VecSize = getContext().getTypeSize(VT);
5178 if (VecSize == 64 || VecSize == 128)
5179 return true;
5180 }
5181 return false;
5182}
5183
5184bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5185 uint64_t Members) const {
5186 return Members <= 4;
5187}
5188
John McCall7f416cc2015-09-08 08:05:57 +00005189Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5190 QualType Ty) const {
5191 CharUnits SlotSize = CharUnits::fromQuantity(4);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005192
John McCall7f416cc2015-09-08 08:05:57 +00005193 // Empty records are ignored for parameter passing purposes.
Tim Northover1711cc92013-06-21 23:05:33 +00005194 if (isEmptyRecord(getContext(), Ty, true)) {
John McCall7f416cc2015-09-08 08:05:57 +00005195 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
5196 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5197 return Addr;
Tim Northover1711cc92013-06-21 23:05:33 +00005198 }
5199
John McCall7f416cc2015-09-08 08:05:57 +00005200 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5201 CharUnits TyAlignForABI = TyInfo.second;
Manman Rencca54d02012-10-16 19:01:37 +00005202
John McCall7f416cc2015-09-08 08:05:57 +00005203 // Use indirect if size of the illegal vector is bigger than 16 bytes.
5204 bool IsIndirect = false;
5205 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
5206 IsIndirect = true;
5207
5208 // Otherwise, bound the type's ABI alignment.
Manman Rencca54d02012-10-16 19:01:37 +00005209 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
5210 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
John McCall7f416cc2015-09-08 08:05:57 +00005211 // Our callers should be prepared to handle an under-aligned address.
5212 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5213 getABIKind() == ARMABIInfo::AAPCS) {
5214 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
5215 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
5216 } else {
5217 TyAlignForABI = CharUnits::fromQuantity(4);
Manman Renfef9e312012-10-16 19:18:39 +00005218 }
John McCall7f416cc2015-09-08 08:05:57 +00005219 TyInfo.second = TyAlignForABI;
Manman Rencca54d02012-10-16 19:01:37 +00005220
John McCall7f416cc2015-09-08 08:05:57 +00005221 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
5222 SlotSize, /*AllowHigherAlign*/ true);
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005223}
5224
Chris Lattner0cf24192010-06-28 20:05:43 +00005225//===----------------------------------------------------------------------===//
Justin Holewinski83e96682012-05-24 17:43:12 +00005226// NVPTX ABI Implementation
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005227//===----------------------------------------------------------------------===//
5228
5229namespace {
5230
Justin Holewinski83e96682012-05-24 17:43:12 +00005231class NVPTXABIInfo : public ABIInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005232public:
Justin Holewinski36837432013-03-30 14:38:24 +00005233 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005234
5235 ABIArgInfo classifyReturnType(QualType RetTy) const;
5236 ABIArgInfo classifyArgumentType(QualType Ty) const;
5237
Craig Topper4f12f102014-03-12 06:41:41 +00005238 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005239 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5240 QualType Ty) const override;
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005241};
5242
Justin Holewinski83e96682012-05-24 17:43:12 +00005243class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005244public:
Justin Holewinski83e96682012-05-24 17:43:12 +00005245 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
5246 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
Craig Topper4f12f102014-03-12 06:41:41 +00005247
Eric Christopher162c91c2015-06-05 22:03:00 +00005248 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005249 CodeGen::CodeGenModule &M) const override;
Justin Holewinski36837432013-03-30 14:38:24 +00005250private:
Eli Benderskye06a2c42014-04-15 16:57:05 +00005251 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
5252 // resulting MDNode to the nvvm.annotations MDNode.
5253 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005254};
5255
Justin Holewinski83e96682012-05-24 17:43:12 +00005256ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005257 if (RetTy->isVoidType())
5258 return ABIArgInfo::getIgnore();
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005259
5260 // note: this is different from default ABI
5261 if (!RetTy->isScalarType())
5262 return ABIArgInfo::getDirect();
5263
5264 // Treat an enum type as its underlying type.
5265 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5266 RetTy = EnumTy->getDecl()->getIntegerType();
5267
5268 return (RetTy->isPromotableIntegerType() ?
5269 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005270}
5271
Justin Holewinski83e96682012-05-24 17:43:12 +00005272ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005273 // Treat an enum type as its underlying type.
5274 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5275 Ty = EnumTy->getDecl()->getIntegerType();
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005276
Eli Bendersky95338a02014-10-29 13:43:21 +00005277 // Return aggregates type as indirect by value
5278 if (isAggregateTypeForABI(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005279 return getNaturalAlignIndirect(Ty, /* byval */ true);
Eli Bendersky95338a02014-10-29 13:43:21 +00005280
Justin Holewinskif9329ff2013-11-20 20:35:34 +00005281 return (Ty->isPromotableIntegerType() ?
5282 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005283}
5284
Justin Holewinski83e96682012-05-24 17:43:12 +00005285void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005286 if (!getCXXABI().classifyReturnType(FI))
5287 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005288 for (auto &I : FI.arguments())
5289 I.info = classifyArgumentType(I.type);
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005290
5291 // Always honor user-specified calling convention.
5292 if (FI.getCallingConvention() != llvm::CallingConv::C)
5293 return;
5294
John McCall882987f2013-02-28 19:01:20 +00005295 FI.setEffectiveCallingConvention(getRuntimeCC());
5296}
5297
John McCall7f416cc2015-09-08 08:05:57 +00005298Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5299 QualType Ty) const {
Justin Holewinski83e96682012-05-24 17:43:12 +00005300 llvm_unreachable("NVPTX does not support varargs");
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005301}
5302
Justin Holewinski83e96682012-05-24 17:43:12 +00005303void NVPTXTargetCodeGenInfo::
Eric Christopher162c91c2015-06-05 22:03:00 +00005304setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Justin Holewinski83e96682012-05-24 17:43:12 +00005305 CodeGen::CodeGenModule &M) const{
Justin Holewinski38031972011-10-05 17:58:44 +00005306 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5307 if (!FD) return;
5308
5309 llvm::Function *F = cast<llvm::Function>(GV);
5310
5311 // Perform special handling in OpenCL mode
David Blaikiebbafb8a2012-03-11 07:00:24 +00005312 if (M.getLangOpts().OpenCL) {
Justin Holewinski36837432013-03-30 14:38:24 +00005313 // Use OpenCL function attributes to check for kernel functions
Justin Holewinski38031972011-10-05 17:58:44 +00005314 // By default, all functions are device functions
Justin Holewinski38031972011-10-05 17:58:44 +00005315 if (FD->hasAttr<OpenCLKernelAttr>()) {
Justin Holewinski36837432013-03-30 14:38:24 +00005316 // OpenCL __kernel functions get kernel metadata
Eli Benderskye06a2c42014-04-15 16:57:05 +00005317 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5318 addNVVMMetadata(F, "kernel", 1);
Justin Holewinski38031972011-10-05 17:58:44 +00005319 // And kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00005320 F->addFnAttr(llvm::Attribute::NoInline);
Justin Holewinski38031972011-10-05 17:58:44 +00005321 }
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005322 }
Justin Holewinski38031972011-10-05 17:58:44 +00005323
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005324 // Perform special handling in CUDA mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005325 if (M.getLangOpts().CUDA) {
Justin Holewinski36837432013-03-30 14:38:24 +00005326 // CUDA __global__ functions get a kernel metadata entry. Since
Peter Collingbourne5bad4af2011-10-06 16:49:54 +00005327 // __global__ functions cannot be called from the device, we do not
5328 // need to set the noinline attribute.
Eli Benderskye06a2c42014-04-15 16:57:05 +00005329 if (FD->hasAttr<CUDAGlobalAttr>()) {
5330 // Create !{<func-ref>, metadata !"kernel", i32 1} node
5331 addNVVMMetadata(F, "kernel", 1);
5332 }
Artem Belevich7093e402015-04-21 22:55:54 +00005333 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
Eli Benderskye06a2c42014-04-15 16:57:05 +00005334 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
Artem Belevich7093e402015-04-21 22:55:54 +00005335 llvm::APSInt MaxThreads(32);
5336 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
5337 if (MaxThreads > 0)
5338 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
5339
5340 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
5341 // not specified in __launch_bounds__ or if the user specified a 0 value,
5342 // we don't have to add a PTX directive.
5343 if (Attr->getMinBlocks()) {
5344 llvm::APSInt MinBlocks(32);
5345 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
5346 if (MinBlocks > 0)
5347 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
5348 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
Eli Benderskye06a2c42014-04-15 16:57:05 +00005349 }
5350 }
Justin Holewinski38031972011-10-05 17:58:44 +00005351 }
5352}
5353
Eli Benderskye06a2c42014-04-15 16:57:05 +00005354void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
5355 int Operand) {
Justin Holewinski36837432013-03-30 14:38:24 +00005356 llvm::Module *M = F->getParent();
5357 llvm::LLVMContext &Ctx = M->getContext();
5358
5359 // Get "nvvm.annotations" metadata node
5360 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
5361
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00005362 llvm::Metadata *MDVals[] = {
5363 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
5364 llvm::ConstantAsMetadata::get(
5365 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
Justin Holewinski36837432013-03-30 14:38:24 +00005366 // Append metadata to nvvm.annotations
5367 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
5368}
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005369}
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00005370
5371//===----------------------------------------------------------------------===//
Ulrich Weigand47445072013-05-06 16:26:41 +00005372// SystemZ ABI Implementation
5373//===----------------------------------------------------------------------===//
5374
5375namespace {
5376
5377class SystemZABIInfo : public ABIInfo {
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005378 bool HasVector;
5379
Ulrich Weigand47445072013-05-06 16:26:41 +00005380public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005381 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
5382 : ABIInfo(CGT), HasVector(HV) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005383
5384 bool isPromotableIntegerType(QualType Ty) const;
5385 bool isCompoundType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005386 bool isVectorArgumentType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005387 bool isFPArgumentType(QualType Ty) const;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005388 QualType GetSingleElementType(QualType Ty) const;
Ulrich Weigand47445072013-05-06 16:26:41 +00005389
5390 ABIArgInfo classifyReturnType(QualType RetTy) const;
5391 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
5392
Craig Topper4f12f102014-03-12 06:41:41 +00005393 void computeInfo(CGFunctionInfo &FI) const override {
Reid Kleckner40ca9132014-05-13 22:05:45 +00005394 if (!getCXXABI().classifyReturnType(FI))
5395 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00005396 for (auto &I : FI.arguments())
5397 I.info = classifyArgumentType(I.type);
Ulrich Weigand47445072013-05-06 16:26:41 +00005398 }
5399
John McCall7f416cc2015-09-08 08:05:57 +00005400 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5401 QualType Ty) const override;
Ulrich Weigand47445072013-05-06 16:26:41 +00005402};
5403
5404class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
5405public:
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005406 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
5407 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
Ulrich Weigand47445072013-05-06 16:26:41 +00005408};
5409
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005410}
Ulrich Weigand47445072013-05-06 16:26:41 +00005411
5412bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
5413 // Treat an enum type as its underlying type.
5414 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5415 Ty = EnumTy->getDecl()->getIntegerType();
5416
5417 // Promotable integer types are required to be promoted by the ABI.
5418 if (Ty->isPromotableIntegerType())
5419 return true;
5420
5421 // 32-bit values must also be promoted.
5422 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5423 switch (BT->getKind()) {
5424 case BuiltinType::Int:
5425 case BuiltinType::UInt:
5426 return true;
5427 default:
5428 return false;
5429 }
5430 return false;
5431}
5432
5433bool SystemZABIInfo::isCompoundType(QualType Ty) const {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005434 return (Ty->isAnyComplexType() ||
5435 Ty->isVectorType() ||
5436 isAggregateTypeForABI(Ty));
Ulrich Weigand47445072013-05-06 16:26:41 +00005437}
5438
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005439bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
5440 return (HasVector &&
5441 Ty->isVectorType() &&
5442 getContext().getTypeSize(Ty) <= 128);
5443}
5444
Ulrich Weigand47445072013-05-06 16:26:41 +00005445bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
5446 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
5447 switch (BT->getKind()) {
5448 case BuiltinType::Float:
5449 case BuiltinType::Double:
5450 return true;
5451 default:
5452 return false;
5453 }
5454
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005455 return false;
5456}
5457
5458QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005459 if (const RecordType *RT = Ty->getAsStructureType()) {
5460 const RecordDecl *RD = RT->getDecl();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005461 QualType Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005462
5463 // If this is a C++ record, check the bases first.
5464 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Aaron Ballman574705e2014-03-13 15:41:46 +00005465 for (const auto &I : CXXRD->bases()) {
5466 QualType Base = I.getType();
Ulrich Weigand47445072013-05-06 16:26:41 +00005467
5468 // Empty bases don't affect things either way.
5469 if (isEmptyRecord(getContext(), Base, true))
5470 continue;
5471
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005472 if (!Found.isNull())
5473 return Ty;
5474 Found = GetSingleElementType(Base);
Ulrich Weigand47445072013-05-06 16:26:41 +00005475 }
5476
5477 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005478 for (const auto *FD : RD->fields()) {
Ulrich Weigand759449c2015-03-30 13:49:01 +00005479 // For compatibility with GCC, ignore empty bitfields in C++ mode.
Ulrich Weigand47445072013-05-06 16:26:41 +00005480 // Unlike isSingleElementStruct(), empty structure and array fields
5481 // do count. So do anonymous bitfields that aren't zero-sized.
Ulrich Weigand759449c2015-03-30 13:49:01 +00005482 if (getContext().getLangOpts().CPlusPlus &&
5483 FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
5484 continue;
Ulrich Weigand47445072013-05-06 16:26:41 +00005485
5486 // Unlike isSingleElementStruct(), arrays do not count.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005487 // Nested structures still do though.
5488 if (!Found.isNull())
5489 return Ty;
5490 Found = GetSingleElementType(FD->getType());
Ulrich Weigand47445072013-05-06 16:26:41 +00005491 }
5492
5493 // Unlike isSingleElementStruct(), trailing padding is allowed.
5494 // An 8-byte aligned struct s { float f; } is passed as a double.
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005495 if (!Found.isNull())
5496 return Found;
Ulrich Weigand47445072013-05-06 16:26:41 +00005497 }
5498
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005499 return Ty;
Ulrich Weigand47445072013-05-06 16:26:41 +00005500}
5501
John McCall7f416cc2015-09-08 08:05:57 +00005502Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5503 QualType Ty) const {
Ulrich Weigand47445072013-05-06 16:26:41 +00005504 // Assume that va_list type is correct; should be pointer to LLVM type:
5505 // struct {
5506 // i64 __gpr;
5507 // i64 __fpr;
5508 // i8 *__overflow_arg_area;
5509 // i8 *__reg_save_area;
5510 // };
5511
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005512 // Every non-vector argument occupies 8 bytes and is passed by preference
5513 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
5514 // always passed on the stack.
John McCall7f416cc2015-09-08 08:05:57 +00005515 Ty = getContext().getCanonicalType(Ty);
5516 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005517 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00005518 llvm::Type *DirectTy = ArgTy;
Ulrich Weigand47445072013-05-06 16:26:41 +00005519 ABIArgInfo AI = classifyArgumentType(Ty);
Ulrich Weigand47445072013-05-06 16:26:41 +00005520 bool IsIndirect = AI.isIndirect();
Ulrich Weigand759449c2015-03-30 13:49:01 +00005521 bool InFPRs = false;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005522 bool IsVector = false;
John McCall7f416cc2015-09-08 08:05:57 +00005523 CharUnits UnpaddedSize;
5524 CharUnits DirectAlign;
Ulrich Weigand47445072013-05-06 16:26:41 +00005525 if (IsIndirect) {
John McCall7f416cc2015-09-08 08:05:57 +00005526 DirectTy = llvm::PointerType::getUnqual(DirectTy);
5527 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
Ulrich Weigand759449c2015-03-30 13:49:01 +00005528 } else {
5529 if (AI.getCoerceToType())
5530 ArgTy = AI.getCoerceToType();
5531 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005532 IsVector = ArgTy->isVectorTy();
John McCall7f416cc2015-09-08 08:05:57 +00005533 UnpaddedSize = TyInfo.first;
5534 DirectAlign = TyInfo.second;
Ulrich Weigand759449c2015-03-30 13:49:01 +00005535 }
John McCall7f416cc2015-09-08 08:05:57 +00005536 CharUnits PaddedSize = CharUnits::fromQuantity(8);
5537 if (IsVector && UnpaddedSize > PaddedSize)
5538 PaddedSize = CharUnits::fromQuantity(16);
5539 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
Ulrich Weigand47445072013-05-06 16:26:41 +00005540
John McCall7f416cc2015-09-08 08:05:57 +00005541 CharUnits Padding = (PaddedSize - UnpaddedSize);
Ulrich Weigand47445072013-05-06 16:26:41 +00005542
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005543 llvm::Type *IndexTy = CGF.Int64Ty;
John McCall7f416cc2015-09-08 08:05:57 +00005544 llvm::Value *PaddedSizeV =
5545 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005546
5547 if (IsVector) {
5548 // Work out the address of a vector argument on the stack.
5549 // Vector arguments are always passed in the high bits of a
5550 // single (8 byte) or double (16 byte) stack slot.
John McCall7f416cc2015-09-08 08:05:57 +00005551 Address OverflowArgAreaPtr =
5552 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005553 "overflow_arg_area_ptr");
John McCall7f416cc2015-09-08 08:05:57 +00005554 Address OverflowArgArea =
5555 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5556 TyInfo.second);
5557 Address MemAddr =
5558 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005559
5560 // Update overflow_arg_area_ptr pointer
5561 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005562 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5563 "overflow_arg_area");
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005564 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5565
5566 return MemAddr;
5567 }
5568
John McCall7f416cc2015-09-08 08:05:57 +00005569 assert(PaddedSize.getQuantity() == 8);
5570
5571 unsigned MaxRegs, RegCountField, RegSaveIndex;
5572 CharUnits RegPadding;
Ulrich Weigand47445072013-05-06 16:26:41 +00005573 if (InFPRs) {
5574 MaxRegs = 4; // Maximum of 4 FPR arguments
5575 RegCountField = 1; // __fpr
5576 RegSaveIndex = 16; // save offset for f0
John McCall7f416cc2015-09-08 08:05:57 +00005577 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
Ulrich Weigand47445072013-05-06 16:26:41 +00005578 } else {
5579 MaxRegs = 5; // Maximum of 5 GPR arguments
5580 RegCountField = 0; // __gpr
5581 RegSaveIndex = 2; // save offset for r2
5582 RegPadding = Padding; // values are passed in the low bits of a GPR
5583 }
5584
John McCall7f416cc2015-09-08 08:05:57 +00005585 Address RegCountPtr = CGF.Builder.CreateStructGEP(
5586 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
5587 "reg_count_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005588 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
Ulrich Weigand47445072013-05-06 16:26:41 +00005589 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
5590 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
Oliver Stannard405bded2014-02-11 09:25:50 +00005591 "fits_in_regs");
Ulrich Weigand47445072013-05-06 16:26:41 +00005592
5593 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5594 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
5595 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5596 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
5597
5598 // Emit code to load the value if it was passed in registers.
5599 CGF.EmitBlock(InRegBlock);
5600
5601 // Work out the address of an argument register.
Ulrich Weigand47445072013-05-06 16:26:41 +00005602 llvm::Value *ScaledRegCount =
5603 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
5604 llvm::Value *RegBase =
John McCall7f416cc2015-09-08 08:05:57 +00005605 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
5606 + RegPadding.getQuantity());
Ulrich Weigand47445072013-05-06 16:26:41 +00005607 llvm::Value *RegOffset =
5608 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
John McCall7f416cc2015-09-08 08:05:57 +00005609 Address RegSaveAreaPtr =
5610 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5611 "reg_save_area_ptr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005612 llvm::Value *RegSaveArea =
5613 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
John McCall7f416cc2015-09-08 08:05:57 +00005614 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
5615 "raw_reg_addr"),
5616 PaddedSize);
5617 Address RegAddr =
5618 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005619
5620 // Update the register count
5621 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
5622 llvm::Value *NewRegCount =
5623 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
5624 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
5625 CGF.EmitBranch(ContBlock);
5626
5627 // Emit code to load the value if it was passed in memory.
5628 CGF.EmitBlock(InMemBlock);
5629
5630 // Work out the address of a stack argument.
John McCall7f416cc2015-09-08 08:05:57 +00005631 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
5632 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
5633 Address OverflowArgArea =
5634 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
5635 PaddedSize);
5636 Address RawMemAddr =
5637 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
5638 Address MemAddr =
5639 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005640
5641 // Update overflow_arg_area_ptr pointer
5642 llvm::Value *NewOverflowArgArea =
John McCall7f416cc2015-09-08 08:05:57 +00005643 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
5644 "overflow_arg_area");
Ulrich Weigand47445072013-05-06 16:26:41 +00005645 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
5646 CGF.EmitBranch(ContBlock);
5647
5648 // Return the appropriate result.
5649 CGF.EmitBlock(ContBlock);
John McCall7f416cc2015-09-08 08:05:57 +00005650 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5651 MemAddr, InMemBlock, "va_arg.addr");
Ulrich Weigand47445072013-05-06 16:26:41 +00005652
5653 if (IsIndirect)
John McCall7f416cc2015-09-08 08:05:57 +00005654 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
5655 TyInfo.second);
Ulrich Weigand47445072013-05-06 16:26:41 +00005656
5657 return ResAddr;
5658}
5659
Ulrich Weigand47445072013-05-06 16:26:41 +00005660ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
5661 if (RetTy->isVoidType())
5662 return ABIArgInfo::getIgnore();
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005663 if (isVectorArgumentType(RetTy))
5664 return ABIArgInfo::getDirect();
Ulrich Weigand47445072013-05-06 16:26:41 +00005665 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00005666 return getNaturalAlignIndirect(RetTy);
Ulrich Weigand47445072013-05-06 16:26:41 +00005667 return (isPromotableIntegerType(RetTy) ?
5668 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
5669}
5670
5671ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
5672 // Handle the generic C++ ABI.
Mark Lacey3825e832013-10-06 01:33:34 +00005673 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00005674 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Ulrich Weigand47445072013-05-06 16:26:41 +00005675
5676 // Integers and enums are extended to full register width.
5677 if (isPromotableIntegerType(Ty))
5678 return ABIArgInfo::getExtend();
5679
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005680 // Handle vector types and vector-like structure types. Note that
5681 // as opposed to float-like structure types, we do not allow any
5682 // padding for vector-like structures, so verify the sizes match.
Ulrich Weigand47445072013-05-06 16:26:41 +00005683 uint64_t Size = getContext().getTypeSize(Ty);
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005684 QualType SingleElementTy = GetSingleElementType(Ty);
5685 if (isVectorArgumentType(SingleElementTy) &&
5686 getContext().getTypeSize(SingleElementTy) == Size)
5687 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
5688
5689 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
Ulrich Weigand47445072013-05-06 16:26:41 +00005690 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
John McCall7f416cc2015-09-08 08:05:57 +00005691 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005692
5693 // Handle small structures.
5694 if (const RecordType *RT = Ty->getAs<RecordType>()) {
5695 // Structures with flexible arrays have variable length, so really
5696 // fail the size test above.
5697 const RecordDecl *RD = RT->getDecl();
5698 if (RD->hasFlexibleArrayMember())
John McCall7f416cc2015-09-08 08:05:57 +00005699 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005700
5701 // The structure is passed as an unextended integer, a float, or a double.
5702 llvm::Type *PassTy;
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00005703 if (isFPArgumentType(SingleElementTy)) {
Ulrich Weigand47445072013-05-06 16:26:41 +00005704 assert(Size == 32 || Size == 64);
5705 if (Size == 32)
5706 PassTy = llvm::Type::getFloatTy(getVMContext());
5707 else
5708 PassTy = llvm::Type::getDoubleTy(getVMContext());
5709 } else
5710 PassTy = llvm::IntegerType::get(getVMContext(), Size);
5711 return ABIArgInfo::getDirect(PassTy);
5712 }
5713
5714 // Non-structure compounds are passed indirectly.
5715 if (isCompoundType(Ty))
John McCall7f416cc2015-09-08 08:05:57 +00005716 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Ulrich Weigand47445072013-05-06 16:26:41 +00005717
Craig Topper8a13c412014-05-21 05:09:00 +00005718 return ABIArgInfo::getDirect(nullptr);
Ulrich Weigand47445072013-05-06 16:26:41 +00005719}
5720
5721//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005722// MSP430 ABI Implementation
Chris Lattner0cf24192010-06-28 20:05:43 +00005723//===----------------------------------------------------------------------===//
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005724
5725namespace {
5726
5727class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
5728public:
Chris Lattner2b037972010-07-29 02:01:43 +00005729 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
5730 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00005731 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005732 CodeGen::CodeGenModule &M) const override;
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005733};
5734
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005735}
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005736
Eric Christopher162c91c2015-06-05 22:03:00 +00005737void MSP430TargetCodeGenInfo::setTargetAttributes(const Decl *D,
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005738 llvm::GlobalValue *GV,
5739 CodeGen::CodeGenModule &M) const {
5740 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
5741 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
5742 // Handle 'interrupt' attribute:
5743 llvm::Function *F = cast<llvm::Function>(GV);
5744
5745 // Step 1: Set ISR calling convention.
5746 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
5747
5748 // Step 2: Add attributes goodness.
Bill Wendling207f0532012-12-20 19:27:06 +00005749 F->addFnAttr(llvm::Attribute::NoInline);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005750
5751 // Step 3: Emit ISR vector alias.
Anton Korobeynikovc5a7f922012-11-26 18:59:10 +00005752 unsigned Num = attr->getNumber() / 2;
Rafael Espindola234405b2014-05-17 21:30:14 +00005753 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
5754 "__isr_" + Twine(Num), F);
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00005755 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00005756 }
5757}
5758
Chris Lattner0cf24192010-06-28 20:05:43 +00005759//===----------------------------------------------------------------------===//
John McCall943fae92010-05-27 06:19:26 +00005760// MIPS ABI Implementation. This works for both little-endian and
5761// big-endian variants.
Chris Lattner0cf24192010-06-28 20:05:43 +00005762//===----------------------------------------------------------------------===//
5763
John McCall943fae92010-05-27 06:19:26 +00005764namespace {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005765class MipsABIInfo : public ABIInfo {
Akira Hatanaka14378522011-11-02 23:14:57 +00005766 bool IsO32;
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005767 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
5768 void CoerceToIntArgs(uint64_t TySize,
Craig Topper5603df42013-07-05 19:34:19 +00005769 SmallVectorImpl<llvm::Type *> &ArgList) const;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005770 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005771 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005772 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005773public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005774 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005775 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005776 StackAlignInBytes(IsO32 ? 8 : 16) {}
Akira Hatanakab579fe52011-06-02 00:09:17 +00005777
5778 ABIArgInfo classifyReturnType(QualType RetTy) const;
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005779 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
Craig Topper4f12f102014-03-12 06:41:41 +00005780 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00005781 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5782 QualType Ty) const override;
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00005783 bool shouldSignExtUnsignedType(QualType Ty) const override;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005784};
5785
John McCall943fae92010-05-27 06:19:26 +00005786class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005787 unsigned SizeOfUnwindException;
John McCall943fae92010-05-27 06:19:26 +00005788public:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00005789 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
5790 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
Akira Hatanaka14378522011-11-02 23:14:57 +00005791 SizeOfUnwindException(IsO32 ? 24 : 32) {}
John McCall943fae92010-05-27 06:19:26 +00005792
Craig Topper4f12f102014-03-12 06:41:41 +00005793 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
John McCall943fae92010-05-27 06:19:26 +00005794 return 29;
5795 }
5796
Eric Christopher162c91c2015-06-05 22:03:00 +00005797 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00005798 CodeGen::CodeGenModule &CGM) const override {
Reed Kotler3d5966f2013-03-13 20:40:30 +00005799 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
5800 if (!FD) return;
Rafael Espindolaa0851a22013-03-19 14:32:23 +00005801 llvm::Function *Fn = cast<llvm::Function>(GV);
Reed Kotler3d5966f2013-03-13 20:40:30 +00005802 if (FD->hasAttr<Mips16Attr>()) {
5803 Fn->addFnAttr("mips16");
5804 }
5805 else if (FD->hasAttr<NoMips16Attr>()) {
5806 Fn->addFnAttr("nomips16");
5807 }
Reed Kotler373feca2013-01-16 17:10:28 +00005808 }
Reed Kotler3d5966f2013-03-13 20:40:30 +00005809
John McCall943fae92010-05-27 06:19:26 +00005810 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00005811 llvm::Value *Address) const override;
John McCall3480ef22011-08-30 01:42:09 +00005812
Craig Topper4f12f102014-03-12 06:41:41 +00005813 unsigned getSizeOfUnwindException() const override {
Akira Hatanaka0486db02011-09-20 18:23:28 +00005814 return SizeOfUnwindException;
John McCall3480ef22011-08-30 01:42:09 +00005815 }
John McCall943fae92010-05-27 06:19:26 +00005816};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005817}
John McCall943fae92010-05-27 06:19:26 +00005818
Eric Christopher7565e0d2015-05-29 23:09:49 +00005819void MipsABIInfo::CoerceToIntArgs(
5820 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005821 llvm::IntegerType *IntTy =
5822 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005823
5824 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
5825 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
5826 ArgList.push_back(IntTy);
5827
5828 // If necessary, add one more integer type to ArgList.
5829 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
5830
5831 if (R)
5832 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005833}
5834
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005835// In N32/64, an aligned double precision floating point field is passed in
5836// a register.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005837llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005838 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
5839
5840 if (IsO32) {
5841 CoerceToIntArgs(TySize, ArgList);
5842 return llvm::StructType::get(getVMContext(), ArgList);
5843 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005844
Akira Hatanaka02e13e52012-01-12 00:52:17 +00005845 if (Ty->isComplexType())
5846 return CGT.ConvertType(Ty);
Akira Hatanaka79f04612012-01-10 23:12:19 +00005847
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005848 const RecordType *RT = Ty->getAs<RecordType>();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005849
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005850 // Unions/vectors are passed in integer registers.
5851 if (!RT || !RT->isStructureOrClassType()) {
5852 CoerceToIntArgs(TySize, ArgList);
5853 return llvm::StructType::get(getVMContext(), ArgList);
5854 }
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005855
5856 const RecordDecl *RD = RT->getDecl();
5857 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005858 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
Eric Christopher7565e0d2015-05-29 23:09:49 +00005859
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005860 uint64_t LastOffset = 0;
5861 unsigned idx = 0;
5862 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
5863
Akira Hatanaka4984f5d2012-02-09 19:54:16 +00005864 // Iterate over fields in the struct/class and check if there are any aligned
5865 // double fields.
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005866 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5867 i != e; ++i, ++idx) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005868 const QualType Ty = i->getType();
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005869 const BuiltinType *BT = Ty->getAs<BuiltinType>();
5870
5871 if (!BT || BT->getKind() != BuiltinType::Double)
5872 continue;
5873
5874 uint64_t Offset = Layout.getFieldOffset(idx);
5875 if (Offset % 64) // Ignore doubles that are not aligned.
5876 continue;
5877
5878 // Add ((Offset - LastOffset) / 64) args of type i64.
5879 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
5880 ArgList.push_back(I64);
5881
5882 // Add double type.
5883 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
5884 LastOffset = Offset + 64;
5885 }
5886
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005887 CoerceToIntArgs(TySize - LastOffset, IntArgList);
5888 ArgList.append(IntArgList.begin(), IntArgList.end());
Akira Hatanaka101f70d2011-11-02 23:54:49 +00005889
5890 return llvm::StructType::get(getVMContext(), ArgList);
5891}
5892
Akira Hatanakaddd66342013-10-29 18:41:15 +00005893llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
5894 uint64_t Offset) const {
5895 if (OrigOffset + MinABIStackAlignInBytes > Offset)
Craig Topper8a13c412014-05-21 05:09:00 +00005896 return nullptr;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005897
Akira Hatanakaddd66342013-10-29 18:41:15 +00005898 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005899}
Akira Hatanaka21ee88c2012-01-10 22:44:52 +00005900
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005901ABIArgInfo
5902MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
Daniel Sanders998c9102015-01-14 12:00:12 +00005903 Ty = useFirstFieldIfTransparentUnion(Ty);
5904
Akira Hatanaka1632af62012-01-09 19:31:25 +00005905 uint64_t OrigOffset = Offset;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005906 uint64_t TySize = getContext().getTypeSize(Ty);
Akira Hatanaka1632af62012-01-09 19:31:25 +00005907 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005908
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005909 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
5910 (uint64_t)StackAlignInBytes);
Akira Hatanakaddd66342013-10-29 18:41:15 +00005911 unsigned CurrOffset = llvm::RoundUpToAlignment(Offset, Align);
5912 Offset = CurrOffset + llvm::RoundUpToAlignment(TySize, Align * 8) / 8;
Akira Hatanaka1632af62012-01-09 19:31:25 +00005913
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005914 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
Akira Hatanakab579fe52011-06-02 00:09:17 +00005915 // Ignore empty aggregates.
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005916 if (TySize == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005917 return ABIArgInfo::getIgnore();
5918
Mark Lacey3825e832013-10-06 01:33:34 +00005919 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005920 Offset = OrigOffset + MinABIStackAlignInBytes;
John McCall7f416cc2015-09-08 08:05:57 +00005921 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Akira Hatanakaf64e1ad2012-01-07 00:25:33 +00005922 }
Akira Hatanakadf425db2011-08-01 18:09:58 +00005923
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00005924 // If we have reached here, aggregates are passed directly by coercing to
5925 // another structure type. Padding is inserted if the offset of the
5926 // aggregate is unaligned.
Daniel Sandersaa1b3552014-10-24 15:30:16 +00005927 ABIArgInfo ArgInfo =
5928 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
5929 getPaddingType(OrigOffset, CurrOffset));
5930 ArgInfo.setInReg(true);
5931 return ArgInfo;
Akira Hatanakab579fe52011-06-02 00:09:17 +00005932 }
5933
5934 // Treat an enum type as its underlying type.
5935 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5936 Ty = EnumTy->getDecl()->getIntegerType();
5937
Daniel Sanders5b445b32014-10-24 14:42:42 +00005938 // All integral types are promoted to the GPR width.
5939 if (Ty->isIntegralOrEnumerationType())
Akira Hatanaka1632af62012-01-09 19:31:25 +00005940 return ABIArgInfo::getExtend();
5941
Akira Hatanakaddd66342013-10-29 18:41:15 +00005942 return ABIArgInfo::getDirect(
Craig Topper8a13c412014-05-21 05:09:00 +00005943 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
Akira Hatanakab579fe52011-06-02 00:09:17 +00005944}
5945
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005946llvm::Type*
5947MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
Akira Hatanakab6f74432012-02-09 18:49:26 +00005948 const RecordType *RT = RetTy->getAs<RecordType>();
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005949 SmallVector<llvm::Type*, 8> RTList;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005950
Akira Hatanakab6f74432012-02-09 18:49:26 +00005951 if (RT && RT->isStructureOrClassType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005952 const RecordDecl *RD = RT->getDecl();
Akira Hatanakab6f74432012-02-09 18:49:26 +00005953 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
5954 unsigned FieldCnt = Layout.getFieldCount();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005955
Akira Hatanakab6f74432012-02-09 18:49:26 +00005956 // N32/64 returns struct/classes in floating point registers if the
5957 // following conditions are met:
5958 // 1. The size of the struct/class is no larger than 128-bit.
5959 // 2. The struct/class has one or two fields all of which are floating
5960 // point types.
Eric Christopher7565e0d2015-05-29 23:09:49 +00005961 // 3. The offset of the first field is zero (this follows what gcc does).
Akira Hatanakab6f74432012-02-09 18:49:26 +00005962 //
5963 // Any other composite results are returned in integer registers.
5964 //
5965 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
5966 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
5967 for (; b != e; ++b) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00005968 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005969
Akira Hatanakab6f74432012-02-09 18:49:26 +00005970 if (!BT || !BT->isFloatingPoint())
5971 break;
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005972
David Blaikie2d7c57e2012-04-30 02:36:29 +00005973 RTList.push_back(CGT.ConvertType(b->getType()));
Akira Hatanakab6f74432012-02-09 18:49:26 +00005974 }
5975
5976 if (b == e)
5977 return llvm::StructType::get(getVMContext(), RTList,
5978 RD->hasAttr<PackedAttr>());
5979
5980 RTList.clear();
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005981 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005982 }
5983
Akira Hatanakae1e3ad32012-07-03 19:24:06 +00005984 CoerceToIntArgs(Size, RTList);
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00005985 return llvm::StructType::get(getVMContext(), RTList);
5986}
5987
Akira Hatanakab579fe52011-06-02 00:09:17 +00005988ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
Akira Hatanaka60f5fe62012-01-23 23:18:57 +00005989 uint64_t Size = getContext().getTypeSize(RetTy);
5990
Daniel Sandersed39f582014-09-04 13:28:14 +00005991 if (RetTy->isVoidType())
5992 return ABIArgInfo::getIgnore();
5993
5994 // O32 doesn't treat zero-sized structs differently from other structs.
5995 // However, N32/N64 ignores zero sized return values.
5996 if (!IsO32 && Size == 0)
Akira Hatanakab579fe52011-06-02 00:09:17 +00005997 return ABIArgInfo::getIgnore();
5998
Akira Hatanakac37eddf2012-05-11 21:01:17 +00005999 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006000 if (Size <= 128) {
6001 if (RetTy->isAnyComplexType())
6002 return ABIArgInfo::getDirect();
6003
Daniel Sanderse5018b62014-09-04 15:05:39 +00006004 // O32 returns integer vectors in registers and N32/N64 returns all small
Daniel Sanders00a56ff2014-09-04 15:07:43 +00006005 // aggregates in registers.
Daniel Sanderse5018b62014-09-04 15:05:39 +00006006 if (!IsO32 ||
6007 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6008 ABIArgInfo ArgInfo =
6009 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6010 ArgInfo.setInReg(true);
6011 return ArgInfo;
6012 }
Akira Hatanakaf093f5b2012-01-04 03:34:42 +00006013 }
Akira Hatanakab579fe52011-06-02 00:09:17 +00006014
John McCall7f416cc2015-09-08 08:05:57 +00006015 return getNaturalAlignIndirect(RetTy);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006016 }
6017
6018 // Treat an enum type as its underlying type.
6019 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6020 RetTy = EnumTy->getDecl()->getIntegerType();
6021
6022 return (RetTy->isPromotableIntegerType() ?
6023 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6024}
6025
6026void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
Akira Hatanaka32604a92012-01-12 01:10:09 +00006027 ABIArgInfo &RetInfo = FI.getReturnInfo();
Reid Kleckner40ca9132014-05-13 22:05:45 +00006028 if (!getCXXABI().classifyReturnType(FI))
6029 RetInfo = classifyReturnType(FI.getReturnType());
Akira Hatanaka32604a92012-01-12 01:10:09 +00006030
Eric Christopher7565e0d2015-05-29 23:09:49 +00006031 // Check if a pointer to an aggregate is passed as a hidden argument.
Akira Hatanaka8ab86cb2012-05-11 21:56:58 +00006032 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
Akira Hatanaka32604a92012-01-12 01:10:09 +00006033
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006034 for (auto &I : FI.arguments())
6035 I.info = classifyArgumentType(I.type, Offset);
Akira Hatanakab579fe52011-06-02 00:09:17 +00006036}
6037
John McCall7f416cc2015-09-08 08:05:57 +00006038Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6039 QualType OrigTy) const {
6040 QualType Ty = OrigTy;
Daniel Sanders59229dc2014-11-19 10:01:35 +00006041
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006042 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
6043 // Pointers are also promoted in the same way but this only matters for N32.
Daniel Sanders59229dc2014-11-19 10:01:35 +00006044 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006045 unsigned PtrWidth = getTarget().getPointerWidth(0);
John McCall7f416cc2015-09-08 08:05:57 +00006046 bool DidPromote = false;
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006047 if ((Ty->isIntegerType() &&
John McCall7f416cc2015-09-08 08:05:57 +00006048 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
Daniel Sanderscdcb5802015-01-13 10:47:00 +00006049 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
John McCall7f416cc2015-09-08 08:05:57 +00006050 DidPromote = true;
6051 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
6052 Ty->isSignedIntegerType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00006053 }
Eric Christopher7565e0d2015-05-29 23:09:49 +00006054
John McCall7f416cc2015-09-08 08:05:57 +00006055 auto TyInfo = getContext().getTypeInfoInChars(Ty);
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006056
John McCall7f416cc2015-09-08 08:05:57 +00006057 // The alignment of things in the argument area is never larger than
6058 // StackAlignInBytes.
6059 TyInfo.second =
6060 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
6061
6062 // MinABIStackAlignInBytes is the size of argument slots on the stack.
6063 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
6064
6065 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6066 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
6067
6068
6069 // If there was a promotion, "unpromote" into a temporary.
6070 // TODO: can we just use a pointer into a subset of the original slot?
6071 if (DidPromote) {
6072 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
6073 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
6074
6075 // Truncate down to the right width.
6076 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
6077 : CGF.IntPtrTy);
6078 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
6079 if (OrigTy->isPointerType())
6080 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
6081
6082 CGF.Builder.CreateStore(V, Temp);
6083 Addr = Temp;
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006084 }
Daniel Sanders2ef3cdd32014-08-01 13:26:28 +00006085
John McCall7f416cc2015-09-08 08:05:57 +00006086 return Addr;
Akira Hatanakab579fe52011-06-02 00:09:17 +00006087}
6088
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006089bool MipsABIInfo::shouldSignExtUnsignedType(QualType Ty) const {
6090 int TySize = getContext().getTypeSize(Ty);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006091
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006092 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
6093 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
6094 return true;
Eric Christopher7565e0d2015-05-29 23:09:49 +00006095
Petar Jovanovic1a3f9652015-05-26 21:07:19 +00006096 return false;
6097}
6098
John McCall943fae92010-05-27 06:19:26 +00006099bool
6100MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6101 llvm::Value *Address) const {
6102 // This information comes from gcc's implementation, which seems to
6103 // as canonical as it gets.
6104
John McCall943fae92010-05-27 06:19:26 +00006105 // Everything on MIPS is 4 bytes. Double-precision FP registers
6106 // are aliased to pairs of single-precision FP registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006107 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
John McCall943fae92010-05-27 06:19:26 +00006108
6109 // 0-31 are the general purpose registers, $0 - $31.
6110 // 32-63 are the floating-point registers, $f0 - $f31.
6111 // 64 and 65 are the multiply/divide registers, $hi and $lo.
6112 // 66 is the (notional, I think) register for signal-handler return.
Chris Lattnerece04092012-02-07 00:39:47 +00006113 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
John McCall943fae92010-05-27 06:19:26 +00006114
6115 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
6116 // They are one bit wide and ignored here.
6117
6118 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
6119 // (coprocessor 1 is the FP unit)
6120 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
6121 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
6122 // 176-181 are the DSP accumulator registers.
Chris Lattnerece04092012-02-07 00:39:47 +00006123 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
John McCall943fae92010-05-27 06:19:26 +00006124 return false;
6125}
6126
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006127//===----------------------------------------------------------------------===//
6128// TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
Eric Christopher7565e0d2015-05-29 23:09:49 +00006129// Currently subclassed only to implement custom OpenCL C function attribute
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006130// handling.
6131//===----------------------------------------------------------------------===//
6132
6133namespace {
6134
6135class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
6136public:
6137 TCETargetCodeGenInfo(CodeGenTypes &CGT)
6138 : DefaultTargetCodeGenInfo(CGT) {}
6139
Eric Christopher162c91c2015-06-05 22:03:00 +00006140 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Craig Topper4f12f102014-03-12 06:41:41 +00006141 CodeGen::CodeGenModule &M) const override;
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006142};
6143
Eric Christopher162c91c2015-06-05 22:03:00 +00006144void TCETargetCodeGenInfo::setTargetAttributes(
Eric Christopher7565e0d2015-05-29 23:09:49 +00006145 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006146 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6147 if (!FD) return;
6148
6149 llvm::Function *F = cast<llvm::Function>(GV);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006150
David Blaikiebbafb8a2012-03-11 07:00:24 +00006151 if (M.getLangOpts().OpenCL) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006152 if (FD->hasAttr<OpenCLKernelAttr>()) {
6153 // OpenCL C Kernel functions are not subject to inlining
Bill Wendling207f0532012-12-20 19:27:06 +00006154 F->addFnAttr(llvm::Attribute::NoInline);
Aaron Ballman36a18ff2013-12-19 13:16:35 +00006155 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
6156 if (Attr) {
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006157 // Convert the reqd_work_group_size() attributes to metadata.
6158 llvm::LLVMContext &Context = F->getContext();
Eric Christopher7565e0d2015-05-29 23:09:49 +00006159 llvm::NamedMDNode *OpenCLMetadata =
6160 M.getModule().getOrInsertNamedMetadata(
6161 "opencl.kernel_wg_size_info");
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006162
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006163 SmallVector<llvm::Metadata *, 5> Operands;
6164 Operands.push_back(llvm::ConstantAsMetadata::get(F));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006165
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006166 Operands.push_back(
6167 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6168 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
6169 Operands.push_back(
6170 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6171 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
6172 Operands.push_back(
6173 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
6174 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006175
Eric Christopher7565e0d2015-05-29 23:09:49 +00006176 // Add a boolean constant operand for "required" (true) or "hint"
6177 // (false) for implementing the work_group_size_hint attr later.
6178 // Currently always true as the hint is not yet implemented.
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006179 Operands.push_back(
6180 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00006181 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
6182 }
6183 }
6184 }
6185}
6186
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006187}
John McCall943fae92010-05-27 06:19:26 +00006188
Tony Linthicum76329bf2011-12-12 21:14:55 +00006189//===----------------------------------------------------------------------===//
6190// Hexagon ABI Implementation
6191//===----------------------------------------------------------------------===//
6192
6193namespace {
6194
6195class HexagonABIInfo : public ABIInfo {
6196
6197
6198public:
6199 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6200
6201private:
6202
6203 ABIArgInfo classifyReturnType(QualType RetTy) const;
6204 ABIArgInfo classifyArgumentType(QualType RetTy) const;
6205
Craig Topper4f12f102014-03-12 06:41:41 +00006206 void computeInfo(CGFunctionInfo &FI) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006207
John McCall7f416cc2015-09-08 08:05:57 +00006208 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6209 QualType Ty) const override;
Tony Linthicum76329bf2011-12-12 21:14:55 +00006210};
6211
6212class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
6213public:
6214 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
6215 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
6216
Craig Topper4f12f102014-03-12 06:41:41 +00006217 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Tony Linthicum76329bf2011-12-12 21:14:55 +00006218 return 29;
6219 }
6220};
6221
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006222}
Tony Linthicum76329bf2011-12-12 21:14:55 +00006223
6224void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
Reid Kleckner40ca9132014-05-13 22:05:45 +00006225 if (!getCXXABI().classifyReturnType(FI))
6226 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006227 for (auto &I : FI.arguments())
6228 I.info = classifyArgumentType(I.type);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006229}
6230
6231ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
6232 if (!isAggregateTypeForABI(Ty)) {
6233 // Treat an enum type as its underlying type.
6234 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6235 Ty = EnumTy->getDecl()->getIntegerType();
6236
6237 return (Ty->isPromotableIntegerType() ?
6238 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6239 }
6240
6241 // Ignore empty records.
6242 if (isEmptyRecord(getContext(), Ty, true))
6243 return ABIArgInfo::getIgnore();
6244
Mark Lacey3825e832013-10-06 01:33:34 +00006245 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006246 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006247
6248 uint64_t Size = getContext().getTypeSize(Ty);
6249 if (Size > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006250 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006251 // Pass in the smallest viable integer type.
6252 else if (Size > 32)
6253 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6254 else if (Size > 16)
6255 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6256 else if (Size > 8)
6257 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6258 else
6259 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6260}
6261
6262ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
6263 if (RetTy->isVoidType())
6264 return ABIArgInfo::getIgnore();
6265
6266 // Large vector types should be returned via memory.
6267 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
John McCall7f416cc2015-09-08 08:05:57 +00006268 return getNaturalAlignIndirect(RetTy);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006269
6270 if (!isAggregateTypeForABI(RetTy)) {
6271 // Treat an enum type as its underlying type.
6272 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6273 RetTy = EnumTy->getDecl()->getIntegerType();
6274
6275 return (RetTy->isPromotableIntegerType() ?
6276 ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
6277 }
6278
Tony Linthicum76329bf2011-12-12 21:14:55 +00006279 if (isEmptyRecord(getContext(), RetTy, true))
6280 return ABIArgInfo::getIgnore();
6281
6282 // Aggregates <= 8 bytes are returned in r0; other aggregates
6283 // are returned indirectly.
6284 uint64_t Size = getContext().getTypeSize(RetTy);
6285 if (Size <= 64) {
6286 // Return in the smallest viable integer type.
6287 if (Size <= 8)
6288 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6289 if (Size <= 16)
6290 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6291 if (Size <= 32)
6292 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6293 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
6294 }
6295
John McCall7f416cc2015-09-08 08:05:57 +00006296 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006297}
6298
John McCall7f416cc2015-09-08 08:05:57 +00006299Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6300 QualType Ty) const {
6301 // FIXME: Someone needs to audit that this handle alignment correctly.
6302 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
6303 getContext().getTypeInfoInChars(Ty),
6304 CharUnits::fromQuantity(4),
6305 /*AllowHigherAlign*/ true);
Tony Linthicum76329bf2011-12-12 21:14:55 +00006306}
6307
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006308//===----------------------------------------------------------------------===//
6309// AMDGPU ABI Implementation
6310//===----------------------------------------------------------------------===//
6311
6312namespace {
6313
6314class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
6315public:
6316 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
6317 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
Eric Christopher162c91c2015-06-05 22:03:00 +00006318 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006319 CodeGen::CodeGenModule &M) const override;
6320};
6321
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006322}
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006323
Eric Christopher162c91c2015-06-05 22:03:00 +00006324void AMDGPUTargetCodeGenInfo::setTargetAttributes(
Matt Arsenault43fae6c2014-12-04 20:38:18 +00006325 const Decl *D,
6326 llvm::GlobalValue *GV,
6327 CodeGen::CodeGenModule &M) const {
6328 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
6329 if (!FD)
6330 return;
6331
6332 if (const auto Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
6333 llvm::Function *F = cast<llvm::Function>(GV);
6334 uint32_t NumVGPR = Attr->getNumVGPR();
6335 if (NumVGPR != 0)
6336 F->addFnAttr("amdgpu_num_vgpr", llvm::utostr(NumVGPR));
6337 }
6338
6339 if (const auto Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
6340 llvm::Function *F = cast<llvm::Function>(GV);
6341 unsigned NumSGPR = Attr->getNumSGPR();
6342 if (NumSGPR != 0)
6343 F->addFnAttr("amdgpu_num_sgpr", llvm::utostr(NumSGPR));
6344 }
6345}
6346
Tony Linthicum76329bf2011-12-12 21:14:55 +00006347
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006348//===----------------------------------------------------------------------===//
6349// SPARC v9 ABI Implementation.
6350// Based on the SPARC Compliance Definition version 2.4.1.
6351//
6352// Function arguments a mapped to a nominal "parameter array" and promoted to
6353// registers depending on their type. Each argument occupies 8 or 16 bytes in
6354// the array, structs larger than 16 bytes are passed indirectly.
6355//
6356// One case requires special care:
6357//
6358// struct mixed {
6359// int i;
6360// float f;
6361// };
6362//
6363// When a struct mixed is passed by value, it only occupies 8 bytes in the
6364// parameter array, but the int is passed in an integer register, and the float
6365// is passed in a floating point register. This is represented as two arguments
6366// with the LLVM IR inreg attribute:
6367//
6368// declare void f(i32 inreg %i, float inreg %f)
6369//
6370// The code generator will only allocate 4 bytes from the parameter array for
6371// the inreg arguments. All other arguments are allocated a multiple of 8
6372// bytes.
6373//
6374namespace {
6375class SparcV9ABIInfo : public ABIInfo {
6376public:
6377 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6378
6379private:
6380 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
Craig Topper4f12f102014-03-12 06:41:41 +00006381 void computeInfo(CGFunctionInfo &FI) const override;
John McCall7f416cc2015-09-08 08:05:57 +00006382 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6383 QualType Ty) const override;
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006384
6385 // Coercion type builder for structs passed in registers. The coercion type
6386 // serves two purposes:
6387 //
6388 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
6389 // in registers.
6390 // 2. Expose aligned floating point elements as first-level elements, so the
6391 // code generator knows to pass them in floating point registers.
6392 //
6393 // We also compute the InReg flag which indicates that the struct contains
6394 // aligned 32-bit floats.
6395 //
6396 struct CoerceBuilder {
6397 llvm::LLVMContext &Context;
6398 const llvm::DataLayout &DL;
6399 SmallVector<llvm::Type*, 8> Elems;
6400 uint64_t Size;
6401 bool InReg;
6402
6403 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
6404 : Context(c), DL(dl), Size(0), InReg(false) {}
6405
6406 // Pad Elems with integers until Size is ToSize.
6407 void pad(uint64_t ToSize) {
6408 assert(ToSize >= Size && "Cannot remove elements");
6409 if (ToSize == Size)
6410 return;
6411
6412 // Finish the current 64-bit word.
6413 uint64_t Aligned = llvm::RoundUpToAlignment(Size, 64);
6414 if (Aligned > Size && Aligned <= ToSize) {
6415 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
6416 Size = Aligned;
6417 }
6418
6419 // Add whole 64-bit words.
6420 while (Size + 64 <= ToSize) {
6421 Elems.push_back(llvm::Type::getInt64Ty(Context));
6422 Size += 64;
6423 }
6424
6425 // Final in-word padding.
6426 if (Size < ToSize) {
6427 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
6428 Size = ToSize;
6429 }
6430 }
6431
6432 // Add a floating point element at Offset.
6433 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
6434 // Unaligned floats are treated as integers.
6435 if (Offset % Bits)
6436 return;
6437 // The InReg flag is only required if there are any floats < 64 bits.
6438 if (Bits < 64)
6439 InReg = true;
6440 pad(Offset);
6441 Elems.push_back(Ty);
6442 Size = Offset + Bits;
6443 }
6444
6445 // Add a struct type to the coercion type, starting at Offset (in bits).
6446 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
6447 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
6448 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
6449 llvm::Type *ElemTy = StrTy->getElementType(i);
6450 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
6451 switch (ElemTy->getTypeID()) {
6452 case llvm::Type::StructTyID:
6453 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
6454 break;
6455 case llvm::Type::FloatTyID:
6456 addFloat(ElemOffset, ElemTy, 32);
6457 break;
6458 case llvm::Type::DoubleTyID:
6459 addFloat(ElemOffset, ElemTy, 64);
6460 break;
6461 case llvm::Type::FP128TyID:
6462 addFloat(ElemOffset, ElemTy, 128);
6463 break;
6464 case llvm::Type::PointerTyID:
6465 if (ElemOffset % 64 == 0) {
6466 pad(ElemOffset);
6467 Elems.push_back(ElemTy);
6468 Size += 64;
6469 }
6470 break;
6471 default:
6472 break;
6473 }
6474 }
6475 }
6476
6477 // Check if Ty is a usable substitute for the coercion type.
6478 bool isUsableType(llvm::StructType *Ty) const {
Benjamin Kramer39ccabe2015-03-02 11:57:06 +00006479 return llvm::makeArrayRef(Elems) == Ty->elements();
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006480 }
6481
6482 // Get the coercion type as a literal struct type.
6483 llvm::Type *getType() const {
6484 if (Elems.size() == 1)
6485 return Elems.front();
6486 else
6487 return llvm::StructType::get(Context, Elems);
6488 }
6489 };
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006490};
6491} // end anonymous namespace
6492
6493ABIArgInfo
6494SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
6495 if (Ty->isVoidType())
6496 return ABIArgInfo::getIgnore();
6497
6498 uint64_t Size = getContext().getTypeSize(Ty);
6499
6500 // Anything too big to fit in registers is passed with an explicit indirect
6501 // pointer / sret pointer.
6502 if (Size > SizeLimit)
John McCall7f416cc2015-09-08 08:05:57 +00006503 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006504
6505 // Treat an enum type as its underlying type.
6506 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6507 Ty = EnumTy->getDecl()->getIntegerType();
6508
6509 // Integer types smaller than a register are extended.
6510 if (Size < 64 && Ty->isIntegerType())
6511 return ABIArgInfo::getExtend();
6512
6513 // Other non-aggregates go in registers.
6514 if (!isAggregateTypeForABI(Ty))
6515 return ABIArgInfo::getDirect();
6516
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006517 // If a C++ object has either a non-trivial copy constructor or a non-trivial
6518 // destructor, it is passed with an explicit indirect pointer / sret pointer.
6519 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
John McCall7f416cc2015-09-08 08:05:57 +00006520 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
Jakob Stoklund Olesenb81eb3e2014-01-12 06:54:56 +00006521
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006522 // This is a small aggregate type that should be passed in registers.
Jakob Stoklund Olesen02dc6a12013-05-28 04:57:37 +00006523 // Build a coercion type from the LLVM struct type.
6524 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
6525 if (!StrTy)
6526 return ABIArgInfo::getDirect();
6527
6528 CoerceBuilder CB(getVMContext(), getDataLayout());
6529 CB.addStruct(0, StrTy);
6530 CB.pad(llvm::RoundUpToAlignment(CB.DL.getTypeSizeInBits(StrTy), 64));
6531
6532 // Try to use the original type for coercion.
6533 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
6534
6535 if (CB.InReg)
6536 return ABIArgInfo::getDirectInReg(CoerceTy);
6537 else
6538 return ABIArgInfo::getDirect(CoerceTy);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006539}
6540
John McCall7f416cc2015-09-08 08:05:57 +00006541Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6542 QualType Ty) const {
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006543 ABIArgInfo AI = classifyType(Ty, 16 * 8);
6544 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6545 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6546 AI.setCoerceToType(ArgTy);
6547
John McCall7f416cc2015-09-08 08:05:57 +00006548 CharUnits SlotSize = CharUnits::fromQuantity(8);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006549
John McCall7f416cc2015-09-08 08:05:57 +00006550 CGBuilderTy &Builder = CGF.Builder;
6551 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
6552 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
6553
6554 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
6555
6556 Address ArgAddr = Address::invalid();
6557 CharUnits Stride;
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006558 switch (AI.getKind()) {
6559 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006560 case ABIArgInfo::InAlloca:
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006561 llvm_unreachable("Unsupported ABI kind for va_arg");
6562
John McCall7f416cc2015-09-08 08:05:57 +00006563 case ABIArgInfo::Extend: {
6564 Stride = SlotSize;
6565 CharUnits Offset = SlotSize - TypeInfo.first;
6566 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006567 break;
John McCall7f416cc2015-09-08 08:05:57 +00006568 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006569
John McCall7f416cc2015-09-08 08:05:57 +00006570 case ABIArgInfo::Direct: {
6571 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
6572 Stride = CharUnits::fromQuantity(AllocSize).RoundUpToAlignment(SlotSize);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006573 ArgAddr = Addr;
6574 break;
John McCall7f416cc2015-09-08 08:05:57 +00006575 }
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006576
6577 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006578 Stride = SlotSize;
6579 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
6580 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
6581 TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006582 break;
6583
6584 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006585 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006586 }
6587
6588 // Update VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006589 llvm::Value *NextPtr =
6590 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
6591 Builder.CreateStore(NextPtr, VAListAddr);
Jakob Stoklund Olesen303caed2013-06-05 03:00:18 +00006592
John McCall7f416cc2015-09-08 08:05:57 +00006593 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006594}
6595
6596void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
6597 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
Aaron Ballmanec47bc22014-03-17 18:10:01 +00006598 for (auto &I : FI.arguments())
6599 I.info = classifyType(I.type, 16 * 8);
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006600}
6601
6602namespace {
6603class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
6604public:
6605 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
6606 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
Roman Divackyf02c9942014-02-24 18:46:27 +00006607
Craig Topper4f12f102014-03-12 06:41:41 +00006608 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
Roman Divackyf02c9942014-02-24 18:46:27 +00006609 return 14;
6610 }
6611
6612 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
Craig Topper4f12f102014-03-12 06:41:41 +00006613 llvm::Value *Address) const override;
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006614};
6615} // end anonymous namespace
6616
Roman Divackyf02c9942014-02-24 18:46:27 +00006617bool
6618SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6619 llvm::Value *Address) const {
6620 // This is calculated from the LLVM and GCC tables and verified
6621 // against gcc output. AFAIK all ABIs use the same encoding.
6622
6623 CodeGen::CGBuilderTy &Builder = CGF.Builder;
6624
6625 llvm::IntegerType *i8 = CGF.Int8Ty;
6626 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
6627 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
6628
6629 // 0-31: the 8-byte general-purpose registers
6630 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
6631
6632 // 32-63: f0-31, the 4-byte floating-point registers
6633 AssignToArrayRange(Builder, Address, Four8, 32, 63);
6634
6635 // Y = 64
6636 // PSR = 65
6637 // WIM = 66
6638 // TBR = 67
6639 // PC = 68
6640 // NPC = 69
6641 // FSR = 70
6642 // CSR = 71
6643 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
Eric Christopher7565e0d2015-05-29 23:09:49 +00006644
Roman Divackyf02c9942014-02-24 18:46:27 +00006645 // 72-87: d0-15, the 8-byte floating-point registers
6646 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
6647
6648 return false;
6649}
6650
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00006651
Robert Lytton0e076492013-08-13 09:43:10 +00006652//===----------------------------------------------------------------------===//
Robert Lyttond21e2d72014-03-03 13:45:29 +00006653// XCore ABI Implementation
Robert Lytton0e076492013-08-13 09:43:10 +00006654//===----------------------------------------------------------------------===//
Robert Lytton844aeeb2014-05-02 09:33:20 +00006655
Robert Lytton0e076492013-08-13 09:43:10 +00006656namespace {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006657
6658/// A SmallStringEnc instance is used to build up the TypeString by passing
6659/// it by reference between functions that append to it.
6660typedef llvm::SmallString<128> SmallStringEnc;
6661
6662/// TypeStringCache caches the meta encodings of Types.
6663///
6664/// The reason for caching TypeStrings is two fold:
6665/// 1. To cache a type's encoding for later uses;
6666/// 2. As a means to break recursive member type inclusion.
6667///
6668/// A cache Entry can have a Status of:
6669/// NonRecursive: The type encoding is not recursive;
6670/// Recursive: The type encoding is recursive;
6671/// Incomplete: An incomplete TypeString;
6672/// IncompleteUsed: An incomplete TypeString that has been used in a
6673/// Recursive type encoding.
6674///
6675/// A NonRecursive entry will have all of its sub-members expanded as fully
6676/// as possible. Whilst it may contain types which are recursive, the type
6677/// itself is not recursive and thus its encoding may be safely used whenever
6678/// the type is encountered.
6679///
6680/// A Recursive entry will have all of its sub-members expanded as fully as
6681/// possible. The type itself is recursive and it may contain other types which
6682/// are recursive. The Recursive encoding must not be used during the expansion
6683/// of a recursive type's recursive branch. For simplicity the code uses
6684/// IncompleteCount to reject all usage of Recursive encodings for member types.
6685///
6686/// An Incomplete entry is always a RecordType and only encodes its
6687/// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
6688/// are placed into the cache during type expansion as a means to identify and
6689/// handle recursive inclusion of types as sub-members. If there is recursion
6690/// the entry becomes IncompleteUsed.
6691///
6692/// During the expansion of a RecordType's members:
6693///
6694/// If the cache contains a NonRecursive encoding for the member type, the
6695/// cached encoding is used;
6696///
6697/// If the cache contains a Recursive encoding for the member type, the
6698/// cached encoding is 'Swapped' out, as it may be incorrect, and...
6699///
6700/// If the member is a RecordType, an Incomplete encoding is placed into the
6701/// cache to break potential recursive inclusion of itself as a sub-member;
6702///
6703/// Once a member RecordType has been expanded, its temporary incomplete
6704/// entry is removed from the cache. If a Recursive encoding was swapped out
6705/// it is swapped back in;
6706///
6707/// If an incomplete entry is used to expand a sub-member, the incomplete
6708/// entry is marked as IncompleteUsed. The cache keeps count of how many
6709/// IncompleteUsed entries it currently contains in IncompleteUsedCount;
6710///
6711/// If a member's encoding is found to be a NonRecursive or Recursive viz:
6712/// IncompleteUsedCount==0, the member's encoding is added to the cache.
6713/// Else the member is part of a recursive type and thus the recursion has
6714/// been exited too soon for the encoding to be correct for the member.
6715///
6716class TypeStringCache {
6717 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
6718 struct Entry {
6719 std::string Str; // The encoded TypeString for the type.
6720 enum Status State; // Information about the encoding in 'Str'.
6721 std::string Swapped; // A temporary place holder for a Recursive encoding
6722 // during the expansion of RecordType's members.
6723 };
6724 std::map<const IdentifierInfo *, struct Entry> Map;
6725 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
6726 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
6727public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006728 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006729 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
6730 bool removeIncomplete(const IdentifierInfo *ID);
6731 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
6732 bool IsRecursive);
6733 StringRef lookupStr(const IdentifierInfo *ID);
6734};
6735
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006736/// TypeString encodings for enum & union fields must be order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006737/// FieldEncoding is a helper for this ordering process.
6738class FieldEncoding {
6739 bool HasName;
6740 std::string Enc;
6741public:
Hans Wennborg4afe5042015-07-22 20:46:26 +00006742 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
6743 StringRef str() {return Enc.c_str();}
Robert Lytton844aeeb2014-05-02 09:33:20 +00006744 bool operator<(const FieldEncoding &rhs) const {
6745 if (HasName != rhs.HasName) return HasName;
6746 return Enc < rhs.Enc;
6747 }
6748};
6749
Robert Lytton7d1db152013-08-19 09:46:39 +00006750class XCoreABIInfo : public DefaultABIInfo {
6751public:
6752 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
John McCall7f416cc2015-09-08 08:05:57 +00006753 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6754 QualType Ty) const override;
Robert Lytton7d1db152013-08-19 09:46:39 +00006755};
6756
Robert Lyttond21e2d72014-03-03 13:45:29 +00006757class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006758 mutable TypeStringCache TSC;
Robert Lytton0e076492013-08-13 09:43:10 +00006759public:
Robert Lyttond21e2d72014-03-03 13:45:29 +00006760 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
Robert Lytton7d1db152013-08-19 09:46:39 +00006761 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
Rafael Espindola8dcd6e72014-05-08 15:01:48 +00006762 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6763 CodeGen::CodeGenModule &M) const override;
Robert Lytton0e076492013-08-13 09:43:10 +00006764};
Robert Lytton844aeeb2014-05-02 09:33:20 +00006765
Robert Lytton2d196952013-10-11 10:29:34 +00006766} // End anonymous namespace.
Robert Lytton0e076492013-08-13 09:43:10 +00006767
John McCall7f416cc2015-09-08 08:05:57 +00006768Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6769 QualType Ty) const {
Robert Lytton7d1db152013-08-19 09:46:39 +00006770 CGBuilderTy &Builder = CGF.Builder;
Robert Lytton7d1db152013-08-19 09:46:39 +00006771
Robert Lytton2d196952013-10-11 10:29:34 +00006772 // Get the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006773 CharUnits SlotSize = CharUnits::fromQuantity(4);
6774 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
Robert Lytton7d1db152013-08-19 09:46:39 +00006775
Robert Lytton2d196952013-10-11 10:29:34 +00006776 // Handle the argument.
6777 ABIArgInfo AI = classifyArgumentType(Ty);
John McCall7f416cc2015-09-08 08:05:57 +00006778 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
Robert Lytton2d196952013-10-11 10:29:34 +00006779 llvm::Type *ArgTy = CGT.ConvertType(Ty);
6780 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
6781 AI.setCoerceToType(ArgTy);
Robert Lytton7d1db152013-08-19 09:46:39 +00006782 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
John McCall7f416cc2015-09-08 08:05:57 +00006783
6784 Address Val = Address::invalid();
6785 CharUnits ArgSize = CharUnits::Zero();
Robert Lytton7d1db152013-08-19 09:46:39 +00006786 switch (AI.getKind()) {
Robert Lytton7d1db152013-08-19 09:46:39 +00006787 case ABIArgInfo::Expand:
Reid Kleckner314ef7b2014-02-01 00:04:45 +00006788 case ABIArgInfo::InAlloca:
Robert Lytton7d1db152013-08-19 09:46:39 +00006789 llvm_unreachable("Unsupported ABI kind for va_arg");
6790 case ABIArgInfo::Ignore:
John McCall7f416cc2015-09-08 08:05:57 +00006791 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
6792 ArgSize = CharUnits::Zero();
Robert Lytton2d196952013-10-11 10:29:34 +00006793 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006794 case ABIArgInfo::Extend:
6795 case ABIArgInfo::Direct:
John McCall7f416cc2015-09-08 08:05:57 +00006796 Val = Builder.CreateBitCast(AP, ArgPtrTy);
6797 ArgSize = CharUnits::fromQuantity(
6798 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
6799 ArgSize = ArgSize.RoundUpToAlignment(SlotSize);
Robert Lytton2d196952013-10-11 10:29:34 +00006800 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006801 case ABIArgInfo::Indirect:
John McCall7f416cc2015-09-08 08:05:57 +00006802 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
6803 Val = Address(Builder.CreateLoad(Val), TypeAlign);
6804 ArgSize = SlotSize;
Robert Lytton2d196952013-10-11 10:29:34 +00006805 break;
Robert Lytton7d1db152013-08-19 09:46:39 +00006806 }
Robert Lytton2d196952013-10-11 10:29:34 +00006807
6808 // Increment the VAList.
John McCall7f416cc2015-09-08 08:05:57 +00006809 if (!ArgSize.isZero()) {
6810 llvm::Value *APN =
6811 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
6812 Builder.CreateStore(APN, VAListAddr);
Robert Lytton2d196952013-10-11 10:29:34 +00006813 }
John McCall7f416cc2015-09-08 08:05:57 +00006814
Robert Lytton2d196952013-10-11 10:29:34 +00006815 return Val;
Robert Lytton7d1db152013-08-19 09:46:39 +00006816}
Robert Lytton0e076492013-08-13 09:43:10 +00006817
Robert Lytton844aeeb2014-05-02 09:33:20 +00006818/// During the expansion of a RecordType, an incomplete TypeString is placed
6819/// into the cache as a means to identify and break recursion.
6820/// If there is a Recursive encoding in the cache, it is swapped out and will
6821/// be reinserted by removeIncomplete().
6822/// All other types of encoding should have been used rather than arriving here.
6823void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
6824 std::string StubEnc) {
6825 if (!ID)
6826 return;
6827 Entry &E = Map[ID];
6828 assert( (E.Str.empty() || E.State == Recursive) &&
6829 "Incorrectly use of addIncomplete");
6830 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
6831 E.Swapped.swap(E.Str); // swap out the Recursive
6832 E.Str.swap(StubEnc);
6833 E.State = Incomplete;
6834 ++IncompleteCount;
6835}
6836
6837/// Once the RecordType has been expanded, the temporary incomplete TypeString
6838/// must be removed from the cache.
6839/// If a Recursive was swapped out by addIncomplete(), it will be replaced.
6840/// Returns true if the RecordType was defined recursively.
6841bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
6842 if (!ID)
6843 return false;
6844 auto I = Map.find(ID);
6845 assert(I != Map.end() && "Entry not present");
6846 Entry &E = I->second;
6847 assert( (E.State == Incomplete ||
6848 E.State == IncompleteUsed) &&
6849 "Entry must be an incomplete type");
6850 bool IsRecursive = false;
6851 if (E.State == IncompleteUsed) {
6852 // We made use of our Incomplete encoding, thus we are recursive.
6853 IsRecursive = true;
6854 --IncompleteUsedCount;
6855 }
6856 if (E.Swapped.empty())
6857 Map.erase(I);
6858 else {
6859 // Swap the Recursive back.
6860 E.Swapped.swap(E.Str);
6861 E.Swapped.clear();
6862 E.State = Recursive;
6863 }
6864 --IncompleteCount;
6865 return IsRecursive;
6866}
6867
6868/// Add the encoded TypeString to the cache only if it is NonRecursive or
6869/// Recursive (viz: all sub-members were expanded as fully as possible).
6870void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
6871 bool IsRecursive) {
6872 if (!ID || IncompleteUsedCount)
6873 return; // No key or it is is an incomplete sub-type so don't add.
6874 Entry &E = Map[ID];
6875 if (IsRecursive && !E.Str.empty()) {
6876 assert(E.State==Recursive && E.Str.size() == Str.size() &&
6877 "This is not the same Recursive entry");
6878 // The parent container was not recursive after all, so we could have used
6879 // this Recursive sub-member entry after all, but we assumed the worse when
6880 // we started viz: IncompleteCount!=0.
6881 return;
6882 }
6883 assert(E.Str.empty() && "Entry already present");
6884 E.Str = Str.str();
6885 E.State = IsRecursive? Recursive : NonRecursive;
6886}
6887
6888/// Return a cached TypeString encoding for the ID. If there isn't one, or we
6889/// are recursively expanding a type (IncompleteCount != 0) and the cached
6890/// encoding is Recursive, return an empty StringRef.
6891StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
6892 if (!ID)
6893 return StringRef(); // We have no key.
6894 auto I = Map.find(ID);
6895 if (I == Map.end())
6896 return StringRef(); // We have no encoding.
6897 Entry &E = I->second;
6898 if (E.State == Recursive && IncompleteCount)
6899 return StringRef(); // We don't use Recursive encodings for member types.
6900
6901 if (E.State == Incomplete) {
6902 // The incomplete type is being used to break out of recursion.
6903 E.State = IncompleteUsed;
6904 ++IncompleteUsedCount;
6905 }
6906 return E.Str.c_str();
6907}
6908
6909/// The XCore ABI includes a type information section that communicates symbol
6910/// type information to the linker. The linker uses this information to verify
6911/// safety/correctness of things such as array bound and pointers et al.
6912/// The ABI only requires C (and XC) language modules to emit TypeStrings.
6913/// This type information (TypeString) is emitted into meta data for all global
6914/// symbols: definitions, declarations, functions & variables.
6915///
6916/// The TypeString carries type, qualifier, name, size & value details.
6917/// Please see 'Tools Development Guide' section 2.16.2 for format details:
Eric Christopher7565e0d2015-05-29 23:09:49 +00006918/// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
Robert Lytton844aeeb2014-05-02 09:33:20 +00006919/// The output is tested by test/CodeGen/xcore-stringtype.c.
6920///
6921static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
6922 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
6923
6924/// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
6925void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
6926 CodeGen::CodeGenModule &CGM) const {
6927 SmallStringEnc Enc;
6928 if (getTypeString(Enc, D, CGM, TSC)) {
6929 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00006930 llvm::SmallVector<llvm::Metadata *, 2> MDVals;
6931 MDVals.push_back(llvm::ConstantAsMetadata::get(GV));
Robert Lytton844aeeb2014-05-02 09:33:20 +00006932 MDVals.push_back(llvm::MDString::get(Ctx, Enc.str()));
6933 llvm::NamedMDNode *MD =
6934 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
6935 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6936 }
6937}
6938
6939static bool appendType(SmallStringEnc &Enc, QualType QType,
6940 const CodeGen::CodeGenModule &CGM,
6941 TypeStringCache &TSC);
6942
6943/// Helper function for appendRecordType().
Eric Christopher7565e0d2015-05-29 23:09:49 +00006944/// Builds a SmallVector containing the encoded field types in declaration
6945/// order.
Robert Lytton844aeeb2014-05-02 09:33:20 +00006946static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
6947 const RecordDecl *RD,
6948 const CodeGen::CodeGenModule &CGM,
6949 TypeStringCache &TSC) {
Hans Wennborga302cd92014-08-21 16:06:57 +00006950 for (const auto *Field : RD->fields()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006951 SmallStringEnc Enc;
6952 Enc += "m(";
Hans Wennborga302cd92014-08-21 16:06:57 +00006953 Enc += Field->getName();
Robert Lytton844aeeb2014-05-02 09:33:20 +00006954 Enc += "){";
Hans Wennborga302cd92014-08-21 16:06:57 +00006955 if (Field->isBitField()) {
Robert Lytton844aeeb2014-05-02 09:33:20 +00006956 Enc += "b(";
6957 llvm::raw_svector_ostream OS(Enc);
Hans Wennborga302cd92014-08-21 16:06:57 +00006958 OS << Field->getBitWidthValue(CGM.getContext());
Robert Lytton844aeeb2014-05-02 09:33:20 +00006959 Enc += ':';
6960 }
Hans Wennborga302cd92014-08-21 16:06:57 +00006961 if (!appendType(Enc, Field->getType(), CGM, TSC))
Robert Lytton844aeeb2014-05-02 09:33:20 +00006962 return false;
Hans Wennborga302cd92014-08-21 16:06:57 +00006963 if (Field->isBitField())
Robert Lytton844aeeb2014-05-02 09:33:20 +00006964 Enc += ')';
6965 Enc += '}';
Benjamin Kramer3204b152015-05-29 19:42:19 +00006966 FE.emplace_back(!Field->getName().empty(), Enc);
Robert Lytton844aeeb2014-05-02 09:33:20 +00006967 }
6968 return true;
6969}
6970
6971/// Appends structure and union types to Enc and adds encoding to cache.
6972/// Recursively calls appendType (via extractFieldType) for each field.
6973/// Union types have their fields ordered according to the ABI.
6974static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
6975 const CodeGen::CodeGenModule &CGM,
6976 TypeStringCache &TSC, const IdentifierInfo *ID) {
6977 // Append the cached TypeString if we have one.
6978 StringRef TypeString = TSC.lookupStr(ID);
6979 if (!TypeString.empty()) {
6980 Enc += TypeString;
6981 return true;
6982 }
6983
6984 // Start to emit an incomplete TypeString.
6985 size_t Start = Enc.size();
6986 Enc += (RT->isUnionType()? 'u' : 's');
6987 Enc += '(';
6988 if (ID)
6989 Enc += ID->getName();
6990 Enc += "){";
6991
6992 // We collect all encoded fields and order as necessary.
6993 bool IsRecursive = false;
Robert Lytton844aeeb2014-05-02 09:33:20 +00006994 const RecordDecl *RD = RT->getDecl()->getDefinition();
6995 if (RD && !RD->field_empty()) {
6996 // An incomplete TypeString stub is placed in the cache for this RecordType
6997 // so that recursive calls to this RecordType will use it whilst building a
6998 // complete TypeString for this RecordType.
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00006999 SmallVector<FieldEncoding, 16> FE;
Robert Lytton844aeeb2014-05-02 09:33:20 +00007000 std::string StubEnc(Enc.substr(Start).str());
7001 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
7002 TSC.addIncomplete(ID, std::move(StubEnc));
7003 if (!extractFieldType(FE, RD, CGM, TSC)) {
7004 (void) TSC.removeIncomplete(ID);
7005 return false;
7006 }
7007 IsRecursive = TSC.removeIncomplete(ID);
7008 // The ABI requires unions to be sorted but not structures.
7009 // See FieldEncoding::operator< for sort algorithm.
7010 if (RT->isUnionType())
7011 std::sort(FE.begin(), FE.end());
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007012 // We can now complete the TypeString.
7013 unsigned E = FE.size();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007014 for (unsigned I = 0; I != E; ++I) {
7015 if (I)
7016 Enc += ',';
7017 Enc += FE[I].str();
7018 }
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007019 }
Robert Lytton844aeeb2014-05-02 09:33:20 +00007020 Enc += '}';
7021 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
7022 return true;
7023}
7024
7025/// Appends enum types to Enc and adds the encoding to the cache.
7026static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
7027 TypeStringCache &TSC,
7028 const IdentifierInfo *ID) {
7029 // Append the cached TypeString if we have one.
7030 StringRef TypeString = TSC.lookupStr(ID);
7031 if (!TypeString.empty()) {
7032 Enc += TypeString;
7033 return true;
7034 }
7035
7036 size_t Start = Enc.size();
7037 Enc += "e(";
7038 if (ID)
7039 Enc += ID->getName();
7040 Enc += "){";
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007041
7042 // We collect all encoded enumerations and order them alphanumerically.
Robert Lytton844aeeb2014-05-02 09:33:20 +00007043 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007044 SmallVector<FieldEncoding, 16> FE;
7045 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
7046 ++I) {
7047 SmallStringEnc EnumEnc;
7048 EnumEnc += "m(";
7049 EnumEnc += I->getName();
7050 EnumEnc += "){";
7051 I->getInitVal().toString(EnumEnc);
7052 EnumEnc += '}';
7053 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
7054 }
7055 std::sort(FE.begin(), FE.end());
7056 unsigned E = FE.size();
7057 for (unsigned I = 0; I != E; ++I) {
7058 if (I)
Robert Lytton844aeeb2014-05-02 09:33:20 +00007059 Enc += ',';
Robert Lyttondb8c1cb2014-05-20 07:19:33 +00007060 Enc += FE[I].str();
Robert Lytton844aeeb2014-05-02 09:33:20 +00007061 }
7062 }
7063 Enc += '}';
7064 TSC.addIfComplete(ID, Enc.substr(Start), false);
7065 return true;
7066}
7067
7068/// Appends type's qualifier to Enc.
7069/// This is done prior to appending the type's encoding.
7070static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
7071 // Qualifiers are emitted in alphabetical order.
7072 static const char *Table[] = {"","c:","r:","cr:","v:","cv:","rv:","crv:"};
7073 int Lookup = 0;
7074 if (QT.isConstQualified())
7075 Lookup += 1<<0;
7076 if (QT.isRestrictQualified())
7077 Lookup += 1<<1;
7078 if (QT.isVolatileQualified())
7079 Lookup += 1<<2;
7080 Enc += Table[Lookup];
7081}
7082
7083/// Appends built-in types to Enc.
7084static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
7085 const char *EncType;
7086 switch (BT->getKind()) {
7087 case BuiltinType::Void:
7088 EncType = "0";
7089 break;
7090 case BuiltinType::Bool:
7091 EncType = "b";
7092 break;
7093 case BuiltinType::Char_U:
7094 EncType = "uc";
7095 break;
7096 case BuiltinType::UChar:
7097 EncType = "uc";
7098 break;
7099 case BuiltinType::SChar:
7100 EncType = "sc";
7101 break;
7102 case BuiltinType::UShort:
7103 EncType = "us";
7104 break;
7105 case BuiltinType::Short:
7106 EncType = "ss";
7107 break;
7108 case BuiltinType::UInt:
7109 EncType = "ui";
7110 break;
7111 case BuiltinType::Int:
7112 EncType = "si";
7113 break;
7114 case BuiltinType::ULong:
7115 EncType = "ul";
7116 break;
7117 case BuiltinType::Long:
7118 EncType = "sl";
7119 break;
7120 case BuiltinType::ULongLong:
7121 EncType = "ull";
7122 break;
7123 case BuiltinType::LongLong:
7124 EncType = "sll";
7125 break;
7126 case BuiltinType::Float:
7127 EncType = "ft";
7128 break;
7129 case BuiltinType::Double:
7130 EncType = "d";
7131 break;
7132 case BuiltinType::LongDouble:
7133 EncType = "ld";
7134 break;
7135 default:
7136 return false;
7137 }
7138 Enc += EncType;
7139 return true;
7140}
7141
7142/// Appends a pointer encoding to Enc before calling appendType for the pointee.
7143static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
7144 const CodeGen::CodeGenModule &CGM,
7145 TypeStringCache &TSC) {
7146 Enc += "p(";
7147 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
7148 return false;
7149 Enc += ')';
7150 return true;
7151}
7152
7153/// Appends array encoding to Enc before calling appendType for the element.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007154static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
7155 const ArrayType *AT,
Robert Lytton844aeeb2014-05-02 09:33:20 +00007156 const CodeGen::CodeGenModule &CGM,
7157 TypeStringCache &TSC, StringRef NoSizeEnc) {
7158 if (AT->getSizeModifier() != ArrayType::Normal)
7159 return false;
7160 Enc += "a(";
7161 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
7162 CAT->getSize().toStringUnsigned(Enc);
7163 else
7164 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
7165 Enc += ':';
Robert Lytton6adb20f2014-06-05 09:06:21 +00007166 // The Qualifiers should be attached to the type rather than the array.
7167 appendQualifier(Enc, QT);
Robert Lytton844aeeb2014-05-02 09:33:20 +00007168 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
7169 return false;
7170 Enc += ')';
7171 return true;
7172}
7173
7174/// Appends a function encoding to Enc, calling appendType for the return type
7175/// and the arguments.
7176static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
7177 const CodeGen::CodeGenModule &CGM,
7178 TypeStringCache &TSC) {
7179 Enc += "f{";
7180 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
7181 return false;
7182 Enc += "}(";
7183 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
7184 // N.B. we are only interested in the adjusted param types.
7185 auto I = FPT->param_type_begin();
7186 auto E = FPT->param_type_end();
7187 if (I != E) {
7188 do {
7189 if (!appendType(Enc, *I, CGM, TSC))
7190 return false;
7191 ++I;
7192 if (I != E)
7193 Enc += ',';
7194 } while (I != E);
7195 if (FPT->isVariadic())
7196 Enc += ",va";
7197 } else {
7198 if (FPT->isVariadic())
7199 Enc += "va";
7200 else
7201 Enc += '0';
7202 }
7203 }
7204 Enc += ')';
7205 return true;
7206}
7207
7208/// Handles the type's qualifier before dispatching a call to handle specific
7209/// type encodings.
7210static bool appendType(SmallStringEnc &Enc, QualType QType,
7211 const CodeGen::CodeGenModule &CGM,
7212 TypeStringCache &TSC) {
7213
7214 QualType QT = QType.getCanonicalType();
7215
Robert Lytton6adb20f2014-06-05 09:06:21 +00007216 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
7217 // The Qualifiers should be attached to the type rather than the array.
7218 // Thus we don't call appendQualifier() here.
7219 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
7220
Robert Lytton844aeeb2014-05-02 09:33:20 +00007221 appendQualifier(Enc, QT);
7222
7223 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
7224 return appendBuiltinType(Enc, BT);
7225
Robert Lytton844aeeb2014-05-02 09:33:20 +00007226 if (const PointerType *PT = QT->getAs<PointerType>())
7227 return appendPointerType(Enc, PT, CGM, TSC);
7228
7229 if (const EnumType *ET = QT->getAs<EnumType>())
7230 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
7231
7232 if (const RecordType *RT = QT->getAsStructureType())
7233 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7234
7235 if (const RecordType *RT = QT->getAsUnionType())
7236 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
7237
7238 if (const FunctionType *FT = QT->getAs<FunctionType>())
7239 return appendFunctionType(Enc, FT, CGM, TSC);
7240
7241 return false;
7242}
7243
7244static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
7245 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
7246 if (!D)
7247 return false;
7248
7249 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7250 if (FD->getLanguageLinkage() != CLanguageLinkage)
7251 return false;
7252 return appendType(Enc, FD->getType(), CGM, TSC);
7253 }
7254
7255 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
7256 if (VD->getLanguageLinkage() != CLanguageLinkage)
7257 return false;
7258 QualType QT = VD->getType().getCanonicalType();
7259 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
7260 // Global ArrayTypes are given a size of '*' if the size is unknown.
Robert Lytton6adb20f2014-06-05 09:06:21 +00007261 // The Qualifiers should be attached to the type rather than the array.
7262 // Thus we don't call appendQualifier() here.
7263 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
Robert Lytton844aeeb2014-05-02 09:33:20 +00007264 }
7265 return appendType(Enc, QT, CGM, TSC);
7266 }
7267 return false;
7268}
7269
7270
Robert Lytton0e076492013-08-13 09:43:10 +00007271//===----------------------------------------------------------------------===//
7272// Driver code
7273//===----------------------------------------------------------------------===//
7274
Rafael Espindola9f834732014-09-19 01:54:22 +00007275const llvm::Triple &CodeGenModule::getTriple() const {
7276 return getTarget().getTriple();
7277}
7278
7279bool CodeGenModule::supportsCOMDAT() const {
7280 return !getTriple().isOSBinFormatMachO();
7281}
7282
Chris Lattner2b037972010-07-29 02:01:43 +00007283const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007284 if (TheTargetCodeGenInfo)
7285 return *TheTargetCodeGenInfo;
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007286
John McCallc8e01702013-04-16 22:48:15 +00007287 const llvm::Triple &Triple = getTarget().getTriple();
Daniel Dunbar40165182009-08-24 09:10:05 +00007288 switch (Triple.getArch()) {
Daniel Dunbare3532f82009-08-24 08:52:16 +00007289 default:
Chris Lattner2b037972010-07-29 02:01:43 +00007290 return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
Daniel Dunbare3532f82009-08-24 08:52:16 +00007291
Derek Schuff09338a22012-09-06 17:37:28 +00007292 case llvm::Triple::le32:
7293 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
John McCall943fae92010-05-27 06:19:26 +00007294 case llvm::Triple::mips:
7295 case llvm::Triple::mipsel:
Petar Jovanovic26a4a402015-07-08 13:07:31 +00007296 if (Triple.getOS() == llvm::Triple::NaCl)
7297 return *(TheTargetCodeGenInfo = new PNaClTargetCodeGenInfo(Types));
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007298 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, true));
7299
Akira Hatanakaec11b4f2011-09-20 18:30:57 +00007300 case llvm::Triple::mips64:
7301 case llvm::Triple::mips64el:
Akira Hatanakac4baedd2013-11-11 22:10:46 +00007302 return *(TheTargetCodeGenInfo = new MIPSTargetCodeGenInfo(Types, false));
7303
Tim Northover25e8a672014-05-24 12:51:25 +00007304 case llvm::Triple::aarch64:
Tim Northover40956e62014-07-23 12:32:58 +00007305 case llvm::Triple::aarch64_be: {
Tim Northover573cbee2014-05-24 12:52:07 +00007306 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007307 if (getTarget().getABI() == "darwinpcs")
Tim Northover573cbee2014-05-24 12:52:07 +00007308 Kind = AArch64ABIInfo::DarwinPCS;
Tim Northovera2ee4332014-03-29 15:09:45 +00007309
Tim Northover573cbee2014-05-24 12:52:07 +00007310 return *(TheTargetCodeGenInfo = new AArch64TargetCodeGenInfo(Types, Kind));
Tim Northovera2ee4332014-03-29 15:09:45 +00007311 }
7312
Dan Gohmanc2853072015-09-03 22:51:53 +00007313 case llvm::Triple::wasm32:
7314 case llvm::Triple::wasm64:
7315 return *(TheTargetCodeGenInfo = new WebAssemblyTargetCodeGenInfo(Types));
7316
Daniel Dunbard59655c2009-09-12 00:59:49 +00007317 case llvm::Triple::arm:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007318 case llvm::Triple::armeb:
Daniel Dunbard59655c2009-09-12 00:59:49 +00007319 case llvm::Triple::thumb:
Christian Pirkerf01cd6f2014-03-28 14:40:46 +00007320 case llvm::Triple::thumbeb:
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007321 {
Saleem Abdulrasool71d1dd12015-01-30 23:29:19 +00007322 if (Triple.getOS() == llvm::Triple::Win32) {
7323 TheTargetCodeGenInfo =
7324 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP);
7325 return *TheTargetCodeGenInfo;
7326 }
7327
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007328 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
Alp Toker4925ba72014-06-07 23:30:42 +00007329 if (getTarget().getABI() == "apcs-gnu")
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007330 Kind = ARMABIInfo::APCS;
David Tweed8f676532012-10-25 13:33:01 +00007331 else if (CodeGenOpts.FloatABI == "hard" ||
John McCallc8e01702013-04-16 22:48:15 +00007332 (CodeGenOpts.FloatABI != "soft" &&
7333 Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007334 Kind = ARMABIInfo::AAPCS_VFP;
7335
Derek Schuff71658bd2015-01-29 00:47:04 +00007336 return *(TheTargetCodeGenInfo = new ARMTargetCodeGenInfo(Types, Kind));
Sandeep Patel45df3dd2011-04-05 00:23:47 +00007337 }
Daniel Dunbard59655c2009-09-12 00:59:49 +00007338
John McCallea8d8bb2010-03-11 00:10:12 +00007339 case llvm::Triple::ppc:
Chris Lattner2b037972010-07-29 02:01:43 +00007340 return *(TheTargetCodeGenInfo = new PPC32TargetCodeGenInfo(Types));
Roman Divackyd966e722012-05-09 18:22:46 +00007341 case llvm::Triple::ppc64:
Ulrich Weigandb7122372014-07-21 00:48:09 +00007342 if (Triple.isOSBinFormatELF()) {
Ulrich Weigandb7122372014-07-21 00:48:09 +00007343 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
Ulrich Weigand8afad612014-07-28 13:17:52 +00007344 if (getTarget().getABI() == "elfv2")
7345 Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007346 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007347
Ulrich Weigandb7122372014-07-21 00:48:09 +00007348 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007349 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007350 } else
Bill Schmidt25cb3492012-10-03 19:18:57 +00007351 return *(TheTargetCodeGenInfo = new PPC64TargetCodeGenInfo(Types));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007352 case llvm::Triple::ppc64le: {
Bill Schmidt778d3872013-07-26 01:36:11 +00007353 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
Ulrich Weigandb7122372014-07-21 00:48:09 +00007354 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007355 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
Ulrich Weigand8afad612014-07-28 13:17:52 +00007356 Kind = PPC64_SVR4_ABIInfo::ELFv1;
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007357 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
Ulrich Weigand8afad612014-07-28 13:17:52 +00007358
Ulrich Weigandb7122372014-07-21 00:48:09 +00007359 return *(TheTargetCodeGenInfo =
Hal Finkel0d0a1a52015-03-11 19:14:15 +00007360 new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX));
Ulrich Weigandb7122372014-07-21 00:48:09 +00007361 }
John McCallea8d8bb2010-03-11 00:10:12 +00007362
Peter Collingbournec947aae2012-05-20 23:28:41 +00007363 case llvm::Triple::nvptx:
7364 case llvm::Triple::nvptx64:
Justin Holewinski83e96682012-05-24 17:43:12 +00007365 return *(TheTargetCodeGenInfo = new NVPTXTargetCodeGenInfo(Types));
Justin Holewinskibd4a3c02011-04-22 11:10:38 +00007366
Anton Korobeynikov55bcea12010-01-10 12:58:08 +00007367 case llvm::Triple::msp430:
Chris Lattner2b037972010-07-29 02:01:43 +00007368 return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
Daniel Dunbard59655c2009-09-12 00:59:49 +00007369
Ulrich Weigand66ff51b2015-05-05 19:35:52 +00007370 case llvm::Triple::systemz: {
7371 bool HasVector = getTarget().getABI() == "vector";
7372 return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types,
7373 HasVector));
7374 }
Ulrich Weigand47445072013-05-06 16:26:41 +00007375
Peter Collingbourneadcf7c92011-10-13 16:24:41 +00007376 case llvm::Triple::tce:
7377 return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
7378
Eli Friedman33465822011-07-08 23:31:17 +00007379 case llvm::Triple::x86: {
John McCall1fe2a8c2013-06-18 02:46:29 +00007380 bool IsDarwinVectorABI = Triple.isOSDarwin();
7381 bool IsSmallStructInRegABI =
7382 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
Saleem Abdulrasoolec5c6242014-11-23 02:16:24 +00007383 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
Daniel Dunbar14ad22f2011-04-19 21:43:27 +00007384
John McCall1fe2a8c2013-06-18 02:46:29 +00007385 if (Triple.getOS() == llvm::Triple::Win32) {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007386 return *(TheTargetCodeGenInfo = new WinX86_32TargetCodeGenInfo(
7387 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7388 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
John McCall1fe2a8c2013-06-18 02:46:29 +00007389 } else {
Eric Christopher7565e0d2015-05-29 23:09:49 +00007390 return *(TheTargetCodeGenInfo = new X86_32TargetCodeGenInfo(
7391 Types, IsDarwinVectorABI, IsSmallStructInRegABI,
7392 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007393 }
Eli Friedman33465822011-07-08 23:31:17 +00007394 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007395
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007396 case llvm::Triple::x86_64: {
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007397 StringRef ABI = getTarget().getABI();
Ahmed Bougacha0b938282015-06-22 21:31:43 +00007398 X86AVXABILevel AVXLevel = (ABI == "avx512" ? X86AVXABILevel::AVX512 :
7399 ABI == "avx" ? X86AVXABILevel::AVX :
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007400 X86AVXABILevel::None);
7401
Chris Lattner04dc9572010-08-31 16:44:54 +00007402 switch (Triple.getOS()) {
7403 case llvm::Triple::Win32:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007404 return *(TheTargetCodeGenInfo =
7405 new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
Alex Rosenberg12207fa2015-01-27 14:47:44 +00007406 case llvm::Triple::PS4:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007407 return *(TheTargetCodeGenInfo =
7408 new PS4TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007409 default:
Ahmed Bougachad39a4152015-06-22 21:30:39 +00007410 return *(TheTargetCodeGenInfo =
7411 new X86_64TargetCodeGenInfo(Types, AVXLevel));
Chris Lattner04dc9572010-08-31 16:44:54 +00007412 }
Daniel Dunbare3532f82009-08-24 08:52:16 +00007413 }
Tony Linthicum76329bf2011-12-12 21:14:55 +00007414 case llvm::Triple::hexagon:
7415 return *(TheTargetCodeGenInfo = new HexagonTargetCodeGenInfo(Types));
Matt Arsenault43fae6c2014-12-04 20:38:18 +00007416 case llvm::Triple::r600:
7417 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Tom Stellardd8e38a32015-01-06 20:34:47 +00007418 case llvm::Triple::amdgcn:
7419 return *(TheTargetCodeGenInfo = new AMDGPUTargetCodeGenInfo(Types));
Jakob Stoklund Olesend28ab7e2013-05-27 21:48:25 +00007420 case llvm::Triple::sparcv9:
7421 return *(TheTargetCodeGenInfo = new SparcV9TargetCodeGenInfo(Types));
Robert Lytton0e076492013-08-13 09:43:10 +00007422 case llvm::Triple::xcore:
Robert Lyttond21e2d72014-03-03 13:45:29 +00007423 return *(TheTargetCodeGenInfo = new XCoreTargetCodeGenInfo(Types));
Eli Friedmanbfd5add2011-12-02 00:11:43 +00007424 }
Anton Korobeynikov244360d2009-06-05 22:08:42 +00007425}