1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // These classes wrap the information about a call or function
10 // definition used to handle ABI compliancy.
12 //===----------------------------------------------------------------------===//
14 #include "TargetInfo.h"
19 #include "CodeGenFunction.h"
20 #include "clang/AST/Attr.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/Basic/CodeGenOptions.h"
23 #include "clang/CodeGen/CGFunctionInfo.h"
24 #include "clang/CodeGen/SwiftCallingConv.h"
25 #include "llvm/ADT/SmallBitVector.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/ADT/Twine.h"
30 #include "llvm/IR/DataLayout.h"
31 #include "llvm/IR/Type.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include <algorithm> // std::sort
35 using namespace clang;
36 using namespace CodeGen;
38 // Helper for coercing an aggregate argument or return value into an integer
39 // array of the same size (including padding) and alignment. This alternate
40 // coercion happens only for the RenderScript ABI and can be removed after
41 // runtimes that rely on it are no longer supported.
43 // RenderScript assumes that the size of the argument / return value in the IR
44 // is the same as the size of the corresponding qualified type. This helper
45 // coerces the aggregate type into an array of the same size (including
46 // padding). This coercion is used in lieu of expansion of struct members or
47 // other canonical coercions that return a coerced-type of larger size.
49 // Ty - The argument / return value type
50 // Context - The associated ASTContext
51 // LLVMContext - The associated LLVMContext
52 static ABIArgInfo coerceToIntArray(QualType Ty,
54 llvm::LLVMContext &LLVMContext) {
55 // Alignment and Size are measured in bits.
56 const uint64_t Size = Context.getTypeSize(Ty);
57 const uint64_t Alignment = Context.getTypeAlign(Ty);
58 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
59 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
60 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
63 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
68 // Alternatively, we could emit this as a loop in the source.
69 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
71 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
72 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
76 static bool isAggregateTypeForABI(QualType T) {
77 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
78 T->isMemberFunctionPointerType();
82 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
83 llvm::Type *Padding) const {
84 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
85 ByRef, Realign, Padding);
89 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
90 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
91 /*ByRef*/ false, Realign);
94 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
96 return Address::invalid();
99 ABIInfo::~ABIInfo() {}
101 /// Does the given lowering require more than the given number of
102 /// registers when expanded?
104 /// This is intended to be the basis of a reasonable basic implementation
105 /// of should{Pass,Return}IndirectlyForSwift.
107 /// For most targets, a limit of four total registers is reasonable; this
108 /// limits the amount of code required in order to move around the value
109 /// in case it wasn't produced immediately prior to the call by the caller
110 /// (or wasn't produced in exactly the right registers) or isn't used
111 /// immediately within the callee. But some targets may need to further
112 /// limit the register count due to an inability to support that many
113 /// return registers.
114 static bool occupiesMoreThan(CodeGenTypes &cgt,
115 ArrayRef<llvm::Type*> scalarTypes,
116 unsigned maxAllRegisters) {
117 unsigned intCount = 0, fpCount = 0;
118 for (llvm::Type *type : scalarTypes) {
119 if (type->isPointerTy()) {
121 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
122 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
123 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
125 assert(type->isVectorTy() || type->isFloatingPointTy());
130 return (intCount + fpCount > maxAllRegisters);
133 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
135 unsigned numElts) const {
136 // The default implementation of this assumes that the target guarantees
137 // 128-bit SIMD support but nothing more.
138 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
141 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
143 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
145 if (!RT->getDecl()->canPassInRegisters())
146 return CGCXXABI::RAA_Indirect;
147 return CGCXXABI::RAA_Default;
149 return CXXABI.getRecordArgABI(RD);
152 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
154 const RecordType *RT = T->getAs<RecordType>();
156 return CGCXXABI::RAA_Default;
157 return getRecordArgABI(RT, CXXABI);
160 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
161 const ABIInfo &Info) {
162 QualType Ty = FI.getReturnType();
164 if (const auto *RT = Ty->getAs<RecordType>())
165 if (!isa<CXXRecordDecl>(RT->getDecl()) &&
166 !RT->getDecl()->canPassInRegisters()) {
167 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
171 return CXXABI.classifyReturnType(FI);
174 /// Pass transparent unions as if they were the type of the first element. Sema
175 /// should ensure that all elements of the union have the same "machine type".
176 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
177 if (const RecordType *UT = Ty->getAsUnionType()) {
178 const RecordDecl *UD = UT->getDecl();
179 if (UD->hasAttr<TransparentUnionAttr>()) {
180 assert(!UD->field_empty() && "sema created an empty transparent union");
181 return UD->field_begin()->getType();
187 CGCXXABI &ABIInfo::getCXXABI() const {
188 return CGT.getCXXABI();
191 ASTContext &ABIInfo::getContext() const {
192 return CGT.getContext();
195 llvm::LLVMContext &ABIInfo::getVMContext() const {
196 return CGT.getLLVMContext();
199 const llvm::DataLayout &ABIInfo::getDataLayout() const {
200 return CGT.getDataLayout();
203 const TargetInfo &ABIInfo::getTarget() const {
204 return CGT.getTarget();
207 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
208 return CGT.getCodeGenOpts();
211 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
213 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
217 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
218 uint64_t Members) const {
222 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
223 raw_ostream &OS = llvm::errs();
224 OS << "(ABIArgInfo Kind=";
227 OS << "Direct Type=";
228 if (llvm::Type *Ty = getCoerceToType())
240 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
243 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
244 << " ByVal=" << getIndirectByVal()
245 << " Realign=" << getIndirectRealign();
250 case CoerceAndExpand:
251 OS << "CoerceAndExpand Type=";
252 getCoerceAndExpandType()->print(OS);
258 // Dynamically round a pointer up to a multiple of the given alignment.
259 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
262 llvm::Value *PtrAsInt = Ptr;
263 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
264 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
265 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
266 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
267 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
268 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
269 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
271 Ptr->getName() + ".aligned");
275 /// Emit va_arg for a platform using the common void* representation,
276 /// where arguments are simply emitted in an array of slots on the stack.
278 /// This version implements the core direct-value passing rules.
280 /// \param SlotSize - The size and alignment of a stack slot.
281 /// Each argument will be allocated to a multiple of this number of
282 /// slots, and all the slots will be aligned to this value.
283 /// \param AllowHigherAlign - The slot alignment is not a cap;
284 /// an argument type with an alignment greater than the slot size
285 /// will be emitted on a higher-alignment address, potentially
286 /// leaving one or more empty slots behind as padding. If this
287 /// is false, the returned address might be less-aligned than
289 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
291 llvm::Type *DirectTy,
292 CharUnits DirectSize,
293 CharUnits DirectAlign,
295 bool AllowHigherAlign) {
296 // Cast the element type to i8* if necessary. Some platforms define
297 // va_list as a struct containing an i8* instead of just an i8*.
298 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
299 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
301 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
303 // If the CC aligns values higher than the slot size, do so if needed.
304 Address Addr = Address::invalid();
305 if (AllowHigherAlign && DirectAlign > SlotSize) {
306 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
309 Addr = Address(Ptr, SlotSize);
312 // Advance the pointer past the argument, then store that back.
313 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
315 CGF.Builder.CreateConstInBoundsByteGEP(Addr, FullDirectSize, "argp.next");
316 CGF.Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
318 // If the argument is smaller than a slot, and this is a big-endian
319 // target, the argument will be right-adjusted in its slot.
320 if (DirectSize < SlotSize && CGF.CGM.getDataLayout().isBigEndian() &&
321 !DirectTy->isStructTy()) {
322 Addr = CGF.Builder.CreateConstInBoundsByteGEP(Addr, SlotSize - DirectSize);
325 Addr = CGF.Builder.CreateElementBitCast(Addr, DirectTy);
329 /// Emit va_arg for a platform using the common void* representation,
330 /// where arguments are simply emitted in an array of slots on the stack.
332 /// \param IsIndirect - Values of this type are passed indirectly.
333 /// \param ValueInfo - The size and alignment of this type, generally
334 /// computed with getContext().getTypeInfoInChars(ValueTy).
335 /// \param SlotSizeAndAlign - The size and alignment of a stack slot.
336 /// Each argument will be allocated to a multiple of this number of
337 /// slots, and all the slots will be aligned to this value.
338 /// \param AllowHigherAlign - The slot alignment is not a cap;
339 /// an argument type with an alignment greater than the slot size
340 /// will be emitted on a higher-alignment address, potentially
341 /// leaving one or more empty slots behind as padding.
342 static Address emitVoidPtrVAArg(CodeGenFunction &CGF, Address VAListAddr,
343 QualType ValueTy, bool IsIndirect,
344 std::pair<CharUnits, CharUnits> ValueInfo,
345 CharUnits SlotSizeAndAlign,
346 bool AllowHigherAlign) {
347 // The size and alignment of the value that was passed directly.
348 CharUnits DirectSize, DirectAlign;
350 DirectSize = CGF.getPointerSize();
351 DirectAlign = CGF.getPointerAlign();
353 DirectSize = ValueInfo.first;
354 DirectAlign = ValueInfo.second;
357 // Cast the address we've calculated to the right type.
358 llvm::Type *DirectTy = CGF.ConvertTypeForMem(ValueTy);
360 DirectTy = DirectTy->getPointerTo(0);
362 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, DirectTy,
363 DirectSize, DirectAlign,
368 Addr = Address(CGF.Builder.CreateLoad(Addr), ValueInfo.second);
375 static Address emitMergePHI(CodeGenFunction &CGF,
376 Address Addr1, llvm::BasicBlock *Block1,
377 Address Addr2, llvm::BasicBlock *Block2,
378 const llvm::Twine &Name = "") {
379 assert(Addr1.getType() == Addr2.getType());
380 llvm::PHINode *PHI = CGF.Builder.CreatePHI(Addr1.getType(), 2, Name);
381 PHI->addIncoming(Addr1.getPointer(), Block1);
382 PHI->addIncoming(Addr2.getPointer(), Block2);
383 CharUnits Align = std::min(Addr1.getAlignment(), Addr2.getAlignment());
384 return Address(PHI, Align);
387 TargetCodeGenInfo::~TargetCodeGenInfo() { delete Info; }
389 // If someone can figure out a general rule for this, that would be great.
390 // It's probably just doomed to be platform-dependent, though.
391 unsigned TargetCodeGenInfo::getSizeOfUnwindException() const {
393 // x86-64 FreeBSD, Linux, Darwin
394 // x86-32 FreeBSD, Linux, Darwin
395 // PowerPC Linux, Darwin
396 // ARM Darwin (*not* EABI)
401 bool TargetCodeGenInfo::isNoProtoCallVariadic(const CallArgList &args,
402 const FunctionNoProtoType *fnType) const {
403 // The following conventions are known to require this to be false:
406 // For everything else, we just prefer false unless we opt out.
411 TargetCodeGenInfo::getDependentLibraryOption(llvm::StringRef Lib,
412 llvm::SmallString<24> &Opt) const {
413 // This assumes the user is passing a library name like "rt" instead of a
414 // filename like "librt.a/so", and that they don't care whether it's static or
420 unsigned TargetCodeGenInfo::getOpenCLKernelCallingConv() const {
421 // OpenCL kernels are called via an explicit runtime API with arguments
422 // set with clSetKernelArg(), not as normal sub-functions.
423 // Return SPIR_KERNEL by default as the kernel calling convention to
424 // ensure the fingerprint is fixed such way that each OpenCL argument
425 // gets one matching argument in the produced kernel function argument
426 // list to enable feasible implementation of clSetKernelArg() with
427 // aggregates etc. In case we would use the default C calling conv here,
428 // clSetKernelArg() might break depending on the target-specific
429 // conventions; different targets might split structs passed as values
430 // to multiple function arguments etc.
431 return llvm::CallingConv::SPIR_KERNEL;
434 llvm::Constant *TargetCodeGenInfo::getNullPointer(const CodeGen::CodeGenModule &CGM,
435 llvm::PointerType *T, QualType QT) const {
436 return llvm::ConstantPointerNull::get(T);
439 LangAS TargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
440 const VarDecl *D) const {
441 assert(!CGM.getLangOpts().OpenCL &&
442 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
443 "Address space agnostic languages only");
444 return D ? D->getType().getAddressSpace() : LangAS::Default;
447 llvm::Value *TargetCodeGenInfo::performAddrSpaceCast(
448 CodeGen::CodeGenFunction &CGF, llvm::Value *Src, LangAS SrcAddr,
449 LangAS DestAddr, llvm::Type *DestTy, bool isNonNull) const {
450 // Since target may map different address spaces in AST to the same address
451 // space, an address space conversion may end up as a bitcast.
452 if (auto *C = dyn_cast<llvm::Constant>(Src))
453 return performAddrSpaceCast(CGF.CGM, C, SrcAddr, DestAddr, DestTy);
454 // Try to preserve the source's name to make IR more readable.
455 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
456 Src, DestTy, Src->hasName() ? Src->getName() + ".ascast" : "");
460 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
461 LangAS SrcAddr, LangAS DestAddr,
462 llvm::Type *DestTy) const {
463 // Since target may map different address spaces in AST to the same address
464 // space, an address space conversion may end up as a bitcast.
465 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
469 TargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
471 llvm::AtomicOrdering Ordering,
472 llvm::LLVMContext &Ctx) const {
473 return Ctx.getOrInsertSyncScopeID(""); /* default sync scope */
476 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
478 /// isEmptyField - Return true iff a the field is "empty", that is it
479 /// is an unnamed bit-field or an (array of) empty record(s).
480 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
482 if (FD->isUnnamedBitfield())
485 QualType FT = FD->getType();
487 // Constant arrays of empty records count as empty, strip them off.
488 // Constant arrays of zero length always count as empty.
490 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
491 if (AT->getSize() == 0)
493 FT = AT->getElementType();
496 const RecordType *RT = FT->getAs<RecordType>();
500 // C++ record fields are never empty, at least in the Itanium ABI.
502 // FIXME: We should use a predicate for whether this behavior is true in the
504 if (isa<CXXRecordDecl>(RT->getDecl()))
507 return isEmptyRecord(Context, FT, AllowArrays);
510 /// isEmptyRecord - Return true iff a structure contains only empty
511 /// fields. Note that a structure with a flexible array member is not
512 /// considered empty.
513 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
514 const RecordType *RT = T->getAs<RecordType>();
517 const RecordDecl *RD = RT->getDecl();
518 if (RD->hasFlexibleArrayMember())
521 // If this is a C++ record, check the bases first.
522 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
523 for (const auto &I : CXXRD->bases())
524 if (!isEmptyRecord(Context, I.getType(), true))
527 for (const auto *I : RD->fields())
528 if (!isEmptyField(Context, I, AllowArrays))
533 /// isSingleElementStruct - Determine if a structure is a "single
534 /// element struct", i.e. it has exactly one non-empty field or
535 /// exactly one field which is itself a single element
536 /// struct. Structures with flexible array members are never
537 /// considered single element structs.
539 /// \return The field declaration for the single non-empty field, if
541 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
542 const RecordType *RT = T->getAs<RecordType>();
546 const RecordDecl *RD = RT->getDecl();
547 if (RD->hasFlexibleArrayMember())
550 const Type *Found = nullptr;
552 // If this is a C++ record, check the bases first.
553 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
554 for (const auto &I : CXXRD->bases()) {
555 // Ignore empty records.
556 if (isEmptyRecord(Context, I.getType(), true))
559 // If we already found an element then this isn't a single-element struct.
563 // If this is non-empty and not a single element struct, the composite
564 // cannot be a single element struct.
565 Found = isSingleElementStruct(I.getType(), Context);
571 // Check for single element.
572 for (const auto *FD : RD->fields()) {
573 QualType FT = FD->getType();
575 // Ignore empty fields.
576 if (isEmptyField(Context, FD, true))
579 // If we already found an element then this isn't a single-element
584 // Treat single element arrays as the element.
585 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
586 if (AT->getSize().getZExtValue() != 1)
588 FT = AT->getElementType();
591 if (!isAggregateTypeForABI(FT)) {
592 Found = FT.getTypePtr();
594 Found = isSingleElementStruct(FT, Context);
600 // We don't consider a struct a single-element struct if it has
601 // padding beyond the element type.
602 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
609 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
610 const ABIArgInfo &AI) {
611 // This default implementation defers to the llvm backend's va_arg
612 // instruction. It can handle only passing arguments directly
613 // (typically only handled in the backend for primitive types), or
614 // aggregates passed indirectly by pointer (NOTE: if the "byval"
615 // flag has ABI impact in the callee, this implementation cannot
618 // Only a few cases are covered here at the moment -- those needed
619 // by the default abi.
622 if (AI.isIndirect()) {
623 assert(!AI.getPaddingType() &&
624 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
626 !AI.getIndirectRealign() &&
627 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
629 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
630 CharUnits TyAlignForABI = TyInfo.second;
633 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
635 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
636 return Address(Addr, TyAlignForABI);
638 assert((AI.isDirect() || AI.isExtend()) &&
639 "Unexpected ArgInfo Kind in generic VAArg emitter!");
641 assert(!AI.getInReg() &&
642 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
643 assert(!AI.getPaddingType() &&
644 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
645 assert(!AI.getDirectOffset() &&
646 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
647 assert(!AI.getCoerceToType() &&
648 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
650 Address Temp = CGF.CreateMemTemp(Ty, "varet");
651 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
652 CGF.Builder.CreateStore(Val, Temp);
657 /// DefaultABIInfo - The default implementation for ABI specific
658 /// details. This implementation provides information which results in
659 /// self-consistent and sensible LLVM IR generation, but does not
660 /// conform to any particular ABI.
661 class DefaultABIInfo : public ABIInfo {
663 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
665 ABIArgInfo classifyReturnType(QualType RetTy) const;
666 ABIArgInfo classifyArgumentType(QualType RetTy) const;
668 void computeInfo(CGFunctionInfo &FI) const override {
669 if (!getCXXABI().classifyReturnType(FI))
670 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
671 for (auto &I : FI.arguments())
672 I.info = classifyArgumentType(I.type);
675 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
676 QualType Ty) const override {
677 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
681 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
683 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
684 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
687 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
688 Ty = useFirstFieldIfTransparentUnion(Ty);
690 if (isAggregateTypeForABI(Ty)) {
691 // Records with non-trivial destructors/copy-constructors should not be
693 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
694 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
696 return getNaturalAlignIndirect(Ty);
699 // Treat an enum type as its underlying type.
700 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
701 Ty = EnumTy->getDecl()->getIntegerType();
703 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
704 : ABIArgInfo::getDirect());
707 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
708 if (RetTy->isVoidType())
709 return ABIArgInfo::getIgnore();
711 if (isAggregateTypeForABI(RetTy))
712 return getNaturalAlignIndirect(RetTy);
714 // Treat an enum type as its underlying type.
715 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
716 RetTy = EnumTy->getDecl()->getIntegerType();
718 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
719 : ABIArgInfo::getDirect());
722 //===----------------------------------------------------------------------===//
723 // WebAssembly ABI Implementation
725 // This is a very simple ABI that relies a lot on DefaultABIInfo.
726 //===----------------------------------------------------------------------===//
728 class WebAssemblyABIInfo final : public SwiftABIInfo {
729 DefaultABIInfo defaultInfo;
732 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
733 : SwiftABIInfo(CGT), defaultInfo(CGT) {}
736 ABIArgInfo classifyReturnType(QualType RetTy) const;
737 ABIArgInfo classifyArgumentType(QualType Ty) const;
739 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
740 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
742 void computeInfo(CGFunctionInfo &FI) const override {
743 if (!getCXXABI().classifyReturnType(FI))
744 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
745 for (auto &Arg : FI.arguments())
746 Arg.info = classifyArgumentType(Arg.type);
749 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
750 QualType Ty) const override;
752 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
753 bool asReturnValue) const override {
754 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
757 bool isSwiftErrorInRegister() const override {
762 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
764 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
765 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
767 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
768 CodeGen::CodeGenModule &CGM) const override {
769 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
770 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
771 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
772 llvm::Function *Fn = cast<llvm::Function>(GV);
774 B.addAttribute("wasm-import-module", Attr->getImportModule());
775 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
777 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
778 llvm::Function *Fn = cast<llvm::Function>(GV);
780 B.addAttribute("wasm-import-name", Attr->getImportName());
781 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
783 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
784 llvm::Function *Fn = cast<llvm::Function>(GV);
786 B.addAttribute("wasm-export-name", Attr->getExportName());
787 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
791 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
792 llvm::Function *Fn = cast<llvm::Function>(GV);
793 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
794 Fn->addFnAttr("no-prototype");
799 /// Classify argument of given type \p Ty.
800 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
801 Ty = useFirstFieldIfTransparentUnion(Ty);
803 if (isAggregateTypeForABI(Ty)) {
804 // Records with non-trivial destructors/copy-constructors should not be
806 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
807 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
808 // Ignore empty structs/unions.
809 if (isEmptyRecord(getContext(), Ty, true))
810 return ABIArgInfo::getIgnore();
811 // Lower single-element structs to just pass a regular value. TODO: We
812 // could do reasonable-size multiple-element structs too, using getExpand(),
813 // though watch out for things like bitfields.
814 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
815 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
818 // Otherwise just do the default thing.
819 return defaultInfo.classifyArgumentType(Ty);
822 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
823 if (isAggregateTypeForABI(RetTy)) {
824 // Records with non-trivial destructors/copy-constructors should not be
825 // returned by value.
826 if (!getRecordArgABI(RetTy, getCXXABI())) {
827 // Ignore empty structs/unions.
828 if (isEmptyRecord(getContext(), RetTy, true))
829 return ABIArgInfo::getIgnore();
830 // Lower single-element structs to just return a regular value. TODO: We
831 // could do reasonable-size multiple-element structs too, using
832 // ABIArgInfo::getDirect().
833 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
834 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
838 // Otherwise just do the default thing.
839 return defaultInfo.classifyReturnType(RetTy);
842 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
844 bool IsIndirect = isAggregateTypeForABI(Ty) &&
845 !isEmptyRecord(getContext(), Ty, true) &&
846 !isSingleElementStruct(Ty, getContext());
847 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
848 getContext().getTypeInfoInChars(Ty),
849 CharUnits::fromQuantity(4),
850 /*AllowHigherAlign=*/true);
853 //===----------------------------------------------------------------------===//
854 // le32/PNaCl bitcode ABI Implementation
856 // This is a simplified version of the x86_32 ABI. Arguments and return values
857 // are always passed on the stack.
858 //===----------------------------------------------------------------------===//
860 class PNaClABIInfo : public ABIInfo {
862 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
864 ABIArgInfo classifyReturnType(QualType RetTy) const;
865 ABIArgInfo classifyArgumentType(QualType RetTy) const;
867 void computeInfo(CGFunctionInfo &FI) const override;
868 Address EmitVAArg(CodeGenFunction &CGF,
869 Address VAListAddr, QualType Ty) const override;
872 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
874 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
875 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
878 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
879 if (!getCXXABI().classifyReturnType(FI))
880 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
882 for (auto &I : FI.arguments())
883 I.info = classifyArgumentType(I.type);
886 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
888 // The PNaCL ABI is a bit odd, in that varargs don't use normal
889 // function classification. Structs get passed directly for varargs
890 // functions, through a rewriting transform in
891 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
892 // this target to actually support a va_arg instructions with an
893 // aggregate type, unlike other targets.
894 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
897 /// Classify argument of given type \p Ty.
898 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
899 if (isAggregateTypeForABI(Ty)) {
900 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
901 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
902 return getNaturalAlignIndirect(Ty);
903 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
904 // Treat an enum type as its underlying type.
905 Ty = EnumTy->getDecl()->getIntegerType();
906 } else if (Ty->isFloatingType()) {
907 // Floating-point types don't go inreg.
908 return ABIArgInfo::getDirect();
911 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
912 : ABIArgInfo::getDirect());
915 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
916 if (RetTy->isVoidType())
917 return ABIArgInfo::getIgnore();
919 // In the PNaCl ABI we always return records/structures on the stack.
920 if (isAggregateTypeForABI(RetTy))
921 return getNaturalAlignIndirect(RetTy);
923 // Treat an enum type as its underlying type.
924 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
925 RetTy = EnumTy->getDecl()->getIntegerType();
927 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
928 : ABIArgInfo::getDirect());
931 /// IsX86_MMXType - Return true if this is an MMX type.
932 bool IsX86_MMXType(llvm::Type *IRType) {
933 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
934 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
935 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
936 IRType->getScalarSizeInBits() != 64;
939 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
940 StringRef Constraint,
942 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
943 .Cases("y", "&y", "^Ym", true)
945 if (IsMMXCons && Ty->isVectorTy()) {
946 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
947 // Invalid MMX constraint
951 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
954 // No operation needed
958 /// Returns true if this type can be passed in SSE registers with the
959 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
960 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
961 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
962 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
963 if (BT->getKind() == BuiltinType::LongDouble) {
964 if (&Context.getTargetInfo().getLongDoubleFormat() ==
965 &llvm::APFloat::x87DoubleExtended())
970 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
971 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
972 // registers specially.
973 unsigned VecSize = Context.getTypeSize(VT);
974 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
980 /// Returns true if this aggregate is small enough to be passed in SSE registers
981 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
982 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
983 return NumMembers <= 4;
986 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
987 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
988 auto AI = ABIArgInfo::getDirect(T);
990 AI.setCanBeFlattened(false);
994 //===----------------------------------------------------------------------===//
995 // X86-32 ABI Implementation
996 //===----------------------------------------------------------------------===//
998 /// Similar to llvm::CCState, but for Clang.
1000 CCState(CGFunctionInfo &FI)
1001 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1003 llvm::SmallBitVector IsPreassigned;
1004 unsigned CC = CallingConv::CC_C;
1005 unsigned FreeRegs = 0;
1006 unsigned FreeSSERegs = 0;
1010 // Vectorcall only allows the first 6 parameters to be passed in registers.
1011 VectorcallMaxParamNumAsReg = 6
1014 /// X86_32ABIInfo - The X86-32 ABI information.
1015 class X86_32ABIInfo : public SwiftABIInfo {
1021 static const unsigned MinABIStackAlignInBytes = 4;
1023 bool IsDarwinVectorABI;
1024 bool IsRetSmallStructInRegABI;
1025 bool IsWin32StructABI;
1026 bool IsSoftFloatABI;
1028 unsigned DefaultNumRegisterParameters;
1030 static bool isRegisterSize(unsigned Size) {
1031 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1034 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1035 // FIXME: Assumes vectorcall is in use.
1036 return isX86VectorTypeForVectorCall(getContext(), Ty);
1039 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1040 uint64_t NumMembers) const override {
1041 // FIXME: Assumes vectorcall is in use.
1042 return isX86VectorCallAggregateSmallEnough(NumMembers);
1045 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1047 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1048 /// such that the argument will be passed in memory.
1049 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1051 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1053 /// Return the alignment to use for the given type on the stack.
1054 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1056 Class classify(QualType Ty) const;
1057 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1058 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1060 /// Updates the number of available free registers, returns
1061 /// true if any registers were allocated.
1062 bool updateFreeRegs(QualType Ty, CCState &State) const;
1064 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1065 bool &NeedsPadding) const;
1066 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1068 bool canExpandIndirectArgument(QualType Ty) const;
1070 /// Rewrite the function info so that all memory arguments use
1072 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1074 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1075 CharUnits &StackOffset, ABIArgInfo &Info,
1076 QualType Type) const;
1077 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1081 void computeInfo(CGFunctionInfo &FI) const override;
1082 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1083 QualType Ty) const override;
1085 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1086 bool RetSmallStructInRegABI, bool Win32StructABI,
1087 unsigned NumRegisterParameters, bool SoftFloatABI)
1088 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1089 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1090 IsWin32StructABI(Win32StructABI),
1091 IsSoftFloatABI(SoftFloatABI),
1092 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1093 DefaultNumRegisterParameters(NumRegisterParameters) {}
1095 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1096 bool asReturnValue) const override {
1097 // LLVM's x86-32 lowering currently only assigns up to three
1098 // integer registers and three fp registers. Oddly, it'll use up to
1099 // four vector registers for vectors, but those can overlap with the
1100 // scalar registers.
1101 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1104 bool isSwiftErrorInRegister() const override {
1105 // x86-32 lowering does not support passing swifterror in a register.
1110 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1112 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1113 bool RetSmallStructInRegABI, bool Win32StructABI,
1114 unsigned NumRegisterParameters, bool SoftFloatABI)
1115 : TargetCodeGenInfo(new X86_32ABIInfo(
1116 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1117 NumRegisterParameters, SoftFloatABI)) {}
1119 static bool isStructReturnInRegABI(
1120 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1122 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1123 CodeGen::CodeGenModule &CGM) const override;
1125 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1126 // Darwin uses different dwarf register numbers for EH.
1127 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1131 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1132 llvm::Value *Address) const override;
1134 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1135 StringRef Constraint,
1136 llvm::Type* Ty) const override {
1137 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1140 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1141 std::string &Constraints,
1142 std::vector<llvm::Type *> &ResultRegTypes,
1143 std::vector<llvm::Type *> &ResultTruncRegTypes,
1144 std::vector<LValue> &ResultRegDests,
1145 std::string &AsmString,
1146 unsigned NumOutputs) const override;
1149 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1150 unsigned Sig = (0xeb << 0) | // jmp rel8
1151 (0x06 << 8) | // .+0x08
1154 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1157 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1158 return "movl\t%ebp, %ebp"
1159 "\t\t// marker for objc_retainAutoreleaseReturnValue";
1165 /// Rewrite input constraint references after adding some output constraints.
1166 /// In the case where there is one output and one input and we add one output,
1167 /// we need to replace all operand references greater than or equal to 1:
1170 /// The result will be:
1173 static void rewriteInputConstraintReferences(unsigned FirstIn,
1174 unsigned NumNewOuts,
1175 std::string &AsmString) {
1177 llvm::raw_string_ostream OS(Buf);
1179 while (Pos < AsmString.size()) {
1180 size_t DollarStart = AsmString.find('$', Pos);
1181 if (DollarStart == std::string::npos)
1182 DollarStart = AsmString.size();
1183 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1184 if (DollarEnd == std::string::npos)
1185 DollarEnd = AsmString.size();
1186 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1188 size_t NumDollars = DollarEnd - DollarStart;
1189 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1190 // We have an operand reference.
1191 size_t DigitStart = Pos;
1192 if (AsmString[DigitStart] == '{') {
1196 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1197 if (DigitEnd == std::string::npos)
1198 DigitEnd = AsmString.size();
1199 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1200 unsigned OperandIndex;
1201 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1202 if (OperandIndex >= FirstIn)
1203 OperandIndex += NumNewOuts;
1211 AsmString = std::move(OS.str());
1214 /// Add output constraints for EAX:EDX because they are return registers.
1215 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1216 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1217 std::vector<llvm::Type *> &ResultRegTypes,
1218 std::vector<llvm::Type *> &ResultTruncRegTypes,
1219 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1220 unsigned NumOutputs) const {
1221 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1223 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1225 if (!Constraints.empty())
1227 if (RetWidth <= 32) {
1228 Constraints += "={eax}";
1229 ResultRegTypes.push_back(CGF.Int32Ty);
1231 // Use the 'A' constraint for EAX:EDX.
1232 Constraints += "=A";
1233 ResultRegTypes.push_back(CGF.Int64Ty);
1236 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1237 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1238 ResultTruncRegTypes.push_back(CoerceTy);
1240 // Coerce the integer by bitcasting the return slot pointer.
1241 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1242 CoerceTy->getPointerTo()));
1243 ResultRegDests.push_back(ReturnSlot);
1245 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1248 /// shouldReturnTypeInRegister - Determine if the given type should be
1249 /// returned in a register (for the Darwin and MCU ABI).
1250 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1251 ASTContext &Context) const {
1252 uint64_t Size = Context.getTypeSize(Ty);
1254 // For i386, type must be register sized.
1255 // For the MCU ABI, it only needs to be <= 8-byte
1256 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1259 if (Ty->isVectorType()) {
1260 // 64- and 128- bit vectors inside structures are not returned in
1262 if (Size == 64 || Size == 128)
1268 // If this is a builtin, pointer, enum, complex type, member pointer, or
1269 // member function pointer it is ok.
1270 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1271 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1272 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1275 // Arrays are treated like records.
1276 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1277 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1279 // Otherwise, it must be a record type.
1280 const RecordType *RT = Ty->getAs<RecordType>();
1281 if (!RT) return false;
1283 // FIXME: Traverse bases here too.
1285 // Structure types are passed in register if all fields would be
1286 // passed in a register.
1287 for (const auto *FD : RT->getDecl()->fields()) {
1288 // Empty fields are ignored.
1289 if (isEmptyField(Context, FD, true))
1292 // Check fields recursively.
1293 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1299 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1300 // Treat complex types as the element type.
1301 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1302 Ty = CTy->getElementType();
1304 // Check for a type which we know has a simple scalar argument-passing
1305 // convention without any padding. (We're specifically looking for 32
1306 // and 64-bit integer and integer-equivalents, float, and double.)
1307 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1308 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1311 uint64_t Size = Context.getTypeSize(Ty);
1312 return Size == 32 || Size == 64;
1315 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1317 for (const auto *FD : RD->fields()) {
1318 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1319 // argument is smaller than 32-bits, expanding the struct will create
1320 // alignment padding.
1321 if (!is32Or64BitBasicType(FD->getType(), Context))
1324 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1325 // how to expand them yet, and the predicate for telling if a bitfield still
1326 // counts as "basic" is more complicated than what we were doing previously.
1327 if (FD->isBitField())
1330 Size += Context.getTypeSize(FD->getType());
1335 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1337 // Don't do this if there are any non-empty bases.
1338 for (const CXXBaseSpecifier &Base : RD->bases()) {
1339 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1343 if (!addFieldSizes(Context, RD, Size))
1348 /// Test whether an argument type which is to be passed indirectly (on the
1349 /// stack) would have the equivalent layout if it was expanded into separate
1350 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1352 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1353 // We can only expand structure types.
1354 const RecordType *RT = Ty->getAs<RecordType>();
1357 const RecordDecl *RD = RT->getDecl();
1359 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1360 if (!IsWin32StructABI) {
1361 // On non-Windows, we have to conservatively match our old bitcode
1362 // prototypes in order to be ABI-compatible at the bitcode level.
1363 if (!CXXRD->isCLike())
1366 // Don't do this for dynamic classes.
1367 if (CXXRD->isDynamicClass())
1370 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1373 if (!addFieldSizes(getContext(), RD, Size))
1377 // We can do this if there was no alignment padding.
1378 return Size == getContext().getTypeSize(Ty);
1381 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1382 // If the return value is indirect, then the hidden argument is consuming one
1383 // integer register.
1384 if (State.FreeRegs) {
1387 return getNaturalAlignIndirectInReg(RetTy);
1389 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1392 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1393 CCState &State) const {
1394 if (RetTy->isVoidType())
1395 return ABIArgInfo::getIgnore();
1397 const Type *Base = nullptr;
1398 uint64_t NumElts = 0;
1399 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1400 State.CC == llvm::CallingConv::X86_RegCall) &&
1401 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1402 // The LLVM struct type for such an aggregate should lower properly.
1403 return ABIArgInfo::getDirect();
1406 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1407 // On Darwin, some vectors are returned in registers.
1408 if (IsDarwinVectorABI) {
1409 uint64_t Size = getContext().getTypeSize(RetTy);
1411 // 128-bit vectors are a special case; they are returned in
1412 // registers and we need to make sure to pick a type the LLVM
1413 // backend will like.
1415 return ABIArgInfo::getDirect(llvm::VectorType::get(
1416 llvm::Type::getInt64Ty(getVMContext()), 2));
1418 // Always return in register if it fits in a general purpose
1419 // register, or if it is 64 bits and has a single element.
1420 if ((Size == 8 || Size == 16 || Size == 32) ||
1421 (Size == 64 && VT->getNumElements() == 1))
1422 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1425 return getIndirectReturnResult(RetTy, State);
1428 return ABIArgInfo::getDirect();
1431 if (isAggregateTypeForABI(RetTy)) {
1432 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1433 // Structures with flexible arrays are always indirect.
1434 if (RT->getDecl()->hasFlexibleArrayMember())
1435 return getIndirectReturnResult(RetTy, State);
1438 // If specified, structs and unions are always indirect.
1439 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1440 return getIndirectReturnResult(RetTy, State);
1442 // Ignore empty structs/unions.
1443 if (isEmptyRecord(getContext(), RetTy, true))
1444 return ABIArgInfo::getIgnore();
1446 // Small structures which are register sized are generally returned
1448 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1449 uint64_t Size = getContext().getTypeSize(RetTy);
1451 // As a special-case, if the struct is a "single-element" struct, and
1452 // the field is of type "float" or "double", return it in a
1453 // floating-point register. (MSVC does not apply this special case.)
1454 // We apply a similar transformation for pointer types to improve the
1455 // quality of the generated IR.
1456 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1457 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1458 || SeltTy->hasPointerRepresentation())
1459 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1461 // FIXME: We should be able to narrow this integer in cases with dead
1463 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1466 return getIndirectReturnResult(RetTy, State);
1469 // Treat an enum type as its underlying type.
1470 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1471 RetTy = EnumTy->getDecl()->getIntegerType();
1473 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1474 : ABIArgInfo::getDirect());
1477 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1478 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1481 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1482 const RecordType *RT = Ty->getAs<RecordType>();
1485 const RecordDecl *RD = RT->getDecl();
1487 // If this is a C++ record, check the bases first.
1488 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1489 for (const auto &I : CXXRD->bases())
1490 if (!isRecordWithSSEVectorType(Context, I.getType()))
1493 for (const auto *i : RD->fields()) {
1494 QualType FT = i->getType();
1496 if (isSSEVectorType(Context, FT))
1499 if (isRecordWithSSEVectorType(Context, FT))
1506 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1507 unsigned Align) const {
1508 // Otherwise, if the alignment is less than or equal to the minimum ABI
1509 // alignment, just use the default; the backend will handle this.
1510 if (Align <= MinABIStackAlignInBytes)
1511 return 0; // Use default alignment.
1513 // On non-Darwin, the stack type alignment is always 4.
1514 if (!IsDarwinVectorABI) {
1515 // Set explicit alignment, since we may need to realign the top.
1516 return MinABIStackAlignInBytes;
1519 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1520 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1521 isRecordWithSSEVectorType(getContext(), Ty)))
1524 return MinABIStackAlignInBytes;
1527 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1528 CCState &State) const {
1530 if (State.FreeRegs) {
1531 --State.FreeRegs; // Non-byval indirects just use one pointer.
1533 return getNaturalAlignIndirectInReg(Ty);
1535 return getNaturalAlignIndirect(Ty, false);
1538 // Compute the byval alignment.
1539 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1540 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1541 if (StackAlign == 0)
1542 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1544 // If the stack alignment is less than the type alignment, realign the
1546 bool Realign = TypeAlign > StackAlign;
1547 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1548 /*ByVal=*/true, Realign);
1551 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1552 const Type *T = isSingleElementStruct(Ty, getContext());
1554 T = Ty.getTypePtr();
1556 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1557 BuiltinType::Kind K = BT->getKind();
1558 if (K == BuiltinType::Float || K == BuiltinType::Double)
1564 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1565 if (!IsSoftFloatABI) {
1566 Class C = classify(Ty);
1571 unsigned Size = getContext().getTypeSize(Ty);
1572 unsigned SizeInRegs = (Size + 31) / 32;
1574 if (SizeInRegs == 0)
1578 if (SizeInRegs > State.FreeRegs) {
1583 // The MCU psABI allows passing parameters in-reg even if there are
1584 // earlier parameters that are passed on the stack. Also,
1585 // it does not allow passing >8-byte structs in-register,
1586 // even if there are 3 free registers available.
1587 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1591 State.FreeRegs -= SizeInRegs;
1595 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1597 bool &NeedsPadding) const {
1598 // On Windows, aggregates other than HFAs are never passed in registers, and
1599 // they do not consume register slots. Homogenous floating-point aggregates
1600 // (HFAs) have already been dealt with at this point.
1601 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1604 NeedsPadding = false;
1607 if (!updateFreeRegs(Ty, State))
1613 if (State.CC == llvm::CallingConv::X86_FastCall ||
1614 State.CC == llvm::CallingConv::X86_VectorCall ||
1615 State.CC == llvm::CallingConv::X86_RegCall) {
1616 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1617 NeedsPadding = true;
1625 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1626 if (!updateFreeRegs(Ty, State))
1632 if (State.CC == llvm::CallingConv::X86_FastCall ||
1633 State.CC == llvm::CallingConv::X86_VectorCall ||
1634 State.CC == llvm::CallingConv::X86_RegCall) {
1635 if (getContext().getTypeSize(Ty) > 32)
1638 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1639 Ty->isReferenceType());
1645 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1646 // Vectorcall x86 works subtly different than in x64, so the format is
1647 // a bit different than the x64 version. First, all vector types (not HVAs)
1648 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1649 // This differs from the x64 implementation, where the first 6 by INDEX get
1651 // In the second pass over the arguments, HVAs are passed in the remaining
1652 // vector registers if possible, or indirectly by address. The address will be
1653 // passed in ECX/EDX if available. Any other arguments are passed according to
1654 // the usual fastcall rules.
1655 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1656 for (int I = 0, E = Args.size(); I < E; ++I) {
1657 const Type *Base = nullptr;
1658 uint64_t NumElts = 0;
1659 const QualType &Ty = Args[I].type;
1660 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1661 isHomogeneousAggregate(Ty, Base, NumElts)) {
1662 if (State.FreeSSERegs >= NumElts) {
1663 State.FreeSSERegs -= NumElts;
1664 Args[I].info = ABIArgInfo::getDirect();
1665 State.IsPreassigned.set(I);
1671 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1672 CCState &State) const {
1673 // FIXME: Set alignment on indirect arguments.
1674 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1675 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1676 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1678 Ty = useFirstFieldIfTransparentUnion(Ty);
1680 // Check with the C++ ABI first.
1681 const RecordType *RT = Ty->getAs<RecordType>();
1683 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1684 if (RAA == CGCXXABI::RAA_Indirect) {
1685 return getIndirectResult(Ty, false, State);
1686 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1687 // The field index doesn't matter, we'll fix it up later.
1688 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1692 // Regcall uses the concept of a homogenous vector aggregate, similar
1693 // to other targets.
1694 const Type *Base = nullptr;
1695 uint64_t NumElts = 0;
1696 if ((IsRegCall || IsVectorCall) &&
1697 isHomogeneousAggregate(Ty, Base, NumElts)) {
1698 if (State.FreeSSERegs >= NumElts) {
1699 State.FreeSSERegs -= NumElts;
1701 // Vectorcall passes HVAs directly and does not flatten them, but regcall
1704 return getDirectX86Hva();
1706 if (Ty->isBuiltinType() || Ty->isVectorType())
1707 return ABIArgInfo::getDirect();
1708 return ABIArgInfo::getExpand();
1710 return getIndirectResult(Ty, /*ByVal=*/false, State);
1713 if (isAggregateTypeForABI(Ty)) {
1714 // Structures with flexible arrays are always indirect.
1715 // FIXME: This should not be byval!
1716 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1717 return getIndirectResult(Ty, true, State);
1719 // Ignore empty structs/unions on non-Windows.
1720 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1721 return ABIArgInfo::getIgnore();
1723 llvm::LLVMContext &LLVMContext = getVMContext();
1724 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1725 bool NeedsPadding = false;
1727 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1728 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1729 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1730 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1732 return ABIArgInfo::getDirectInReg(Result);
1734 return ABIArgInfo::getDirect(Result);
1736 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1738 // Expand small (<= 128-bit) record types when we know that the stack layout
1739 // of those arguments will match the struct. This is important because the
1740 // LLVM backend isn't smart enough to remove byval, which inhibits many
1742 // Don't do this for the MCU if there are still free integer registers
1743 // (see X86_64 ABI for full explanation).
1744 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1745 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
1746 return ABIArgInfo::getExpandWithPadding(
1747 IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1749 return getIndirectResult(Ty, true, State);
1752 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1753 // On Darwin, some vectors are passed in memory, we handle this by passing
1754 // it as an i8/i16/i32/i64.
1755 if (IsDarwinVectorABI) {
1756 uint64_t Size = getContext().getTypeSize(Ty);
1757 if ((Size == 8 || Size == 16 || Size == 32) ||
1758 (Size == 64 && VT->getNumElements() == 1))
1759 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1763 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1764 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1766 return ABIArgInfo::getDirect();
1770 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1771 Ty = EnumTy->getDecl()->getIntegerType();
1773 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1775 if (Ty->isPromotableIntegerType()) {
1777 return ABIArgInfo::getExtendInReg(Ty);
1778 return ABIArgInfo::getExtend(Ty);
1782 return ABIArgInfo::getDirectInReg();
1783 return ABIArgInfo::getDirect();
1786 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1790 else if (State.CC == llvm::CallingConv::X86_FastCall)
1792 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1794 State.FreeSSERegs = 6;
1795 } else if (FI.getHasRegParm())
1796 State.FreeRegs = FI.getRegParm();
1797 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1799 State.FreeSSERegs = 8;
1801 State.FreeRegs = DefaultNumRegisterParameters;
1803 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1804 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1805 } else if (FI.getReturnInfo().isIndirect()) {
1806 // The C++ ABI is not aware of register usage, so we have to check if the
1807 // return value was sret and put it in a register ourselves if appropriate.
1808 if (State.FreeRegs) {
1809 --State.FreeRegs; // The sret parameter consumes a register.
1811 FI.getReturnInfo().setInReg(true);
1815 // The chain argument effectively gives us another free register.
1816 if (FI.isChainCall())
1819 // For vectorcall, do a first pass over the arguments, assigning FP and vector
1820 // arguments to XMM registers as available.
1821 if (State.CC == llvm::CallingConv::X86_VectorCall)
1822 runVectorCallFirstPass(FI, State);
1824 bool UsedInAlloca = false;
1825 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1826 for (int I = 0, E = Args.size(); I < E; ++I) {
1827 // Skip arguments that have already been assigned.
1828 if (State.IsPreassigned.test(I))
1831 Args[I].info = classifyArgumentType(Args[I].type, State);
1832 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1835 // If we needed to use inalloca for any argument, do a second pass and rewrite
1836 // all the memory arguments to use inalloca.
1838 rewriteWithInAlloca(FI);
1842 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1843 CharUnits &StackOffset, ABIArgInfo &Info,
1844 QualType Type) const {
1845 // Arguments are always 4-byte-aligned.
1846 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1848 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
1849 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1850 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1851 StackOffset += getContext().getTypeSizeInChars(Type);
1853 // Insert padding bytes to respect alignment.
1854 CharUnits FieldEnd = StackOffset;
1855 StackOffset = FieldEnd.alignTo(FieldAlign);
1856 if (StackOffset != FieldEnd) {
1857 CharUnits NumBytes = StackOffset - FieldEnd;
1858 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1859 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1860 FrameFields.push_back(Ty);
1864 static bool isArgInAlloca(const ABIArgInfo &Info) {
1865 // Leave ignored and inreg arguments alone.
1866 switch (Info.getKind()) {
1867 case ABIArgInfo::InAlloca:
1869 case ABIArgInfo::Indirect:
1870 assert(Info.getIndirectByVal());
1872 case ABIArgInfo::Ignore:
1874 case ABIArgInfo::Direct:
1875 case ABIArgInfo::Extend:
1876 if (Info.getInReg())
1879 case ABIArgInfo::Expand:
1880 case ABIArgInfo::CoerceAndExpand:
1881 // These are aggregate types which are never passed in registers when
1882 // inalloca is involved.
1885 llvm_unreachable("invalid enum");
1888 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1889 assert(IsWin32StructABI && "inalloca only supported on win32");
1891 // Build a packed struct type for all of the arguments in memory.
1892 SmallVector<llvm::Type *, 6> FrameFields;
1894 // The stack alignment is always 4.
1895 CharUnits StackAlign = CharUnits::fromQuantity(4);
1897 CharUnits StackOffset;
1898 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1900 // Put 'this' into the struct before 'sret', if necessary.
1902 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1903 ABIArgInfo &Ret = FI.getReturnInfo();
1904 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1905 isArgInAlloca(I->info)) {
1906 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1910 // Put the sret parameter into the inalloca struct if it's in memory.
1911 if (Ret.isIndirect() && !Ret.getInReg()) {
1912 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1913 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1914 // On Windows, the hidden sret parameter is always returned in eax.
1915 Ret.setInAllocaSRet(IsWin32StructABI);
1918 // Skip the 'this' parameter in ecx.
1922 // Put arguments passed in memory into the struct.
1923 for (; I != E; ++I) {
1924 if (isArgInAlloca(I->info))
1925 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1928 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1933 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1934 Address VAListAddr, QualType Ty) const {
1936 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1938 // x86-32 changes the alignment of certain arguments on the stack.
1940 // Just messing with TypeInfo like this works because we never pass
1941 // anything indirectly.
1942 TypeInfo.second = CharUnits::fromQuantity(
1943 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1945 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1946 TypeInfo, CharUnits::fromQuantity(4),
1947 /*AllowHigherAlign*/ true);
1950 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1951 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1952 assert(Triple.getArch() == llvm::Triple::x86);
1954 switch (Opts.getStructReturnConvention()) {
1955 case CodeGenOptions::SRCK_Default:
1957 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1959 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1963 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1966 switch (Triple.getOS()) {
1967 case llvm::Triple::DragonFly:
1968 case llvm::Triple::FreeBSD:
1969 case llvm::Triple::OpenBSD:
1970 case llvm::Triple::Win32:
1977 void X86_32TargetCodeGenInfo::setTargetAttributes(
1978 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1979 if (GV->isDeclaration())
1981 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1982 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1983 llvm::Function *Fn = cast<llvm::Function>(GV);
1984 Fn->addFnAttr("stackrealign");
1986 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1987 llvm::Function *Fn = cast<llvm::Function>(GV);
1988 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1993 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1994 CodeGen::CodeGenFunction &CGF,
1995 llvm::Value *Address) const {
1996 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1998 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2000 // 0-7 are the eight integer registers; the order is different
2001 // on Darwin (for EH), but the range is the same.
2003 AssignToArrayRange(Builder, Address, Four8, 0, 8);
2005 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2006 // 12-16 are st(0..4). Not sure why we stop at 4.
2007 // These have size 16, which is sizeof(long double) on
2008 // platforms with 8-byte alignment for that type.
2009 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2010 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2013 // 9 is %eflags, which doesn't get a size on Darwin for some
2015 Builder.CreateAlignedStore(
2016 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2019 // 11-16 are st(0..5). Not sure why we stop at 5.
2020 // These have size 12, which is sizeof(long double) on
2021 // platforms with 4-byte alignment for that type.
2022 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2023 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2029 //===----------------------------------------------------------------------===//
2030 // X86-64 ABI Implementation
2031 //===----------------------------------------------------------------------===//
2035 /// The AVX ABI level for X86 targets.
2036 enum class X86AVXABILevel {
2042 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2043 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2045 case X86AVXABILevel::AVX512:
2047 case X86AVXABILevel::AVX:
2049 case X86AVXABILevel::None:
2052 llvm_unreachable("Unknown AVXLevel");
2055 /// X86_64ABIInfo - The X86_64 ABI information.
2056 class X86_64ABIInfo : public SwiftABIInfo {
2068 /// merge - Implement the X86_64 ABI merging algorithm.
2070 /// Merge an accumulating classification \arg Accum with a field
2071 /// classification \arg Field.
2073 /// \param Accum - The accumulating classification. This should
2074 /// always be either NoClass or the result of a previous merge
2075 /// call. In addition, this should never be Memory (the caller
2076 /// should just return Memory for the aggregate).
2077 static Class merge(Class Accum, Class Field);
2079 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2081 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2082 /// final MEMORY or SSE classes when necessary.
2084 /// \param AggregateSize - The size of the current aggregate in
2085 /// the classification process.
2087 /// \param Lo - The classification for the parts of the type
2088 /// residing in the low word of the containing object.
2090 /// \param Hi - The classification for the parts of the type
2091 /// residing in the higher words of the containing object.
2093 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2095 /// classify - Determine the x86_64 register classes in which the
2096 /// given type T should be passed.
2098 /// \param Lo - The classification for the parts of the type
2099 /// residing in the low word of the containing object.
2101 /// \param Hi - The classification for the parts of the type
2102 /// residing in the high word of the containing object.
2104 /// \param OffsetBase - The bit offset of this type in the
2105 /// containing object. Some parameters are classified different
2106 /// depending on whether they straddle an eightbyte boundary.
2108 /// \param isNamedArg - Whether the argument in question is a "named"
2109 /// argument, as used in AMD64-ABI 3.5.7.
2111 /// If a word is unused its result will be NoClass; if a type should
2112 /// be passed in Memory then at least the classification of \arg Lo
2115 /// The \arg Lo class will be NoClass iff the argument is ignored.
2117 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2118 /// also be ComplexX87.
2119 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2120 bool isNamedArg) const;
2122 llvm::Type *GetByteVectorType(QualType Ty) const;
2123 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2124 unsigned IROffset, QualType SourceTy,
2125 unsigned SourceOffset) const;
2126 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2127 unsigned IROffset, QualType SourceTy,
2128 unsigned SourceOffset) const;
2130 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2131 /// such that the argument will be returned in memory.
2132 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2134 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2135 /// such that the argument will be passed in memory.
2137 /// \param freeIntRegs - The number of free integer registers remaining
2139 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2141 ABIArgInfo classifyReturnType(QualType RetTy) const;
2143 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2144 unsigned &neededInt, unsigned &neededSSE,
2145 bool isNamedArg) const;
2147 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2148 unsigned &NeededSSE) const;
2150 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2151 unsigned &NeededSSE) const;
2153 bool IsIllegalVectorType(QualType Ty) const;
2155 /// The 0.98 ABI revision clarified a lot of ambiguities,
2156 /// unfortunately in ways that were not always consistent with
2157 /// certain previous compilers. In particular, platforms which
2158 /// required strict binary compatibility with older versions of GCC
2159 /// may need to exempt themselves.
2160 bool honorsRevision0_98() const {
2161 return !getTarget().getTriple().isOSDarwin();
2164 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2165 /// classify it as INTEGER (for compatibility with older clang compilers).
2166 bool classifyIntegerMMXAsSSE() const {
2167 // Clang <= 3.8 did not do this.
2168 if (getContext().getLangOpts().getClangABICompat() <=
2169 LangOptions::ClangABI::Ver3_8)
2172 const llvm::Triple &Triple = getTarget().getTriple();
2173 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2175 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2180 // GCC classifies vectors of __int128 as memory.
2181 bool passInt128VectorsInMem() const {
2182 // Clang <= 9.0 did not do this.
2183 if (getContext().getLangOpts().getClangABICompat() <=
2184 LangOptions::ClangABI::Ver9)
2187 const llvm::Triple &T = getTarget().getTriple();
2188 return T.isOSLinux() || T.isOSNetBSD();
2191 X86AVXABILevel AVXLevel;
2192 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2194 bool Has64BitPointers;
2197 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2198 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2199 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2202 bool isPassedUsingAVXType(QualType type) const {
2203 unsigned neededInt, neededSSE;
2204 // The freeIntRegs argument doesn't matter here.
2205 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2206 /*isNamedArg*/true);
2207 if (info.isDirect()) {
2208 llvm::Type *ty = info.getCoerceToType();
2209 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2210 return (vectorTy->getBitWidth() > 128);
2215 void computeInfo(CGFunctionInfo &FI) const override;
2217 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2218 QualType Ty) const override;
2219 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2220 QualType Ty) const override;
2222 bool has64BitPointers() const {
2223 return Has64BitPointers;
2226 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2227 bool asReturnValue) const override {
2228 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2230 bool isSwiftErrorInRegister() const override {
2235 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2236 class WinX86_64ABIInfo : public SwiftABIInfo {
2238 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2239 : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2240 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2242 void computeInfo(CGFunctionInfo &FI) const override;
2244 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2245 QualType Ty) const override;
2247 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2248 // FIXME: Assumes vectorcall is in use.
2249 return isX86VectorTypeForVectorCall(getContext(), Ty);
2252 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2253 uint64_t NumMembers) const override {
2254 // FIXME: Assumes vectorcall is in use.
2255 return isX86VectorCallAggregateSmallEnough(NumMembers);
2258 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2259 bool asReturnValue) const override {
2260 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2263 bool isSwiftErrorInRegister() const override {
2268 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2269 bool IsVectorCall, bool IsRegCall) const;
2270 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2271 const ABIArgInfo ¤t) const;
2272 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2273 bool IsVectorCall, bool IsRegCall) const;
2275 X86AVXABILevel AVXLevel;
2280 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2282 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2283 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2285 const X86_64ABIInfo &getABIInfo() const {
2286 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2289 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2290 /// the autoreleaseRV/retainRV optimization.
2291 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2295 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2299 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2300 llvm::Value *Address) const override {
2301 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2303 // 0-15 are the 16 integer registers.
2305 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2309 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2310 StringRef Constraint,
2311 llvm::Type* Ty) const override {
2312 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2315 bool isNoProtoCallVariadic(const CallArgList &args,
2316 const FunctionNoProtoType *fnType) const override {
2317 // The default CC on x86-64 sets %al to the number of SSA
2318 // registers used, and GCC sets this when calling an unprototyped
2319 // function, so we override the default behavior. However, don't do
2320 // that when AVX types are involved: the ABI explicitly states it is
2321 // undefined, and it doesn't work in practice because of how the ABI
2322 // defines varargs anyway.
2323 if (fnType->getCallConv() == CC_C) {
2324 bool HasAVXType = false;
2325 for (CallArgList::const_iterator
2326 it = args.begin(), ie = args.end(); it != ie; ++it) {
2327 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2337 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2341 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2342 unsigned Sig = (0xeb << 0) | // jmp rel8
2343 (0x06 << 8) | // .+0x08
2346 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2349 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2350 CodeGen::CodeGenModule &CGM) const override {
2351 if (GV->isDeclaration())
2353 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2354 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2355 llvm::Function *Fn = cast<llvm::Function>(GV);
2356 Fn->addFnAttr("stackrealign");
2358 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2359 llvm::Function *Fn = cast<llvm::Function>(GV);
2360 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2366 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2367 // If the argument does not end in .lib, automatically add the suffix.
2368 // If the argument contains a space, enclose it in quotes.
2369 // This matches the behavior of MSVC.
2370 bool Quote = (Lib.find(" ") != StringRef::npos);
2371 std::string ArgStr = Quote ? "\"" : "";
2373 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2375 ArgStr += Quote ? "\"" : "";
2379 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2381 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2382 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2383 unsigned NumRegisterParameters)
2384 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2385 Win32StructABI, NumRegisterParameters, false) {}
2387 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2388 CodeGen::CodeGenModule &CGM) const override;
2390 void getDependentLibraryOption(llvm::StringRef Lib,
2391 llvm::SmallString<24> &Opt) const override {
2392 Opt = "/DEFAULTLIB:";
2393 Opt += qualifyWindowsLibrary(Lib);
2396 void getDetectMismatchOption(llvm::StringRef Name,
2397 llvm::StringRef Value,
2398 llvm::SmallString<32> &Opt) const override {
2399 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2403 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2404 CodeGen::CodeGenModule &CGM) {
2405 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2407 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2408 Fn->addFnAttr("stack-probe-size",
2409 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2410 if (CGM.getCodeGenOpts().NoStackArgProbe)
2411 Fn->addFnAttr("no-stack-arg-probe");
2415 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2416 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2417 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2418 if (GV->isDeclaration())
2420 addStackProbeTargetAttributes(D, GV, CGM);
2423 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2425 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2426 X86AVXABILevel AVXLevel)
2427 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {}
2429 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2430 CodeGen::CodeGenModule &CGM) const override;
2432 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2436 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2437 llvm::Value *Address) const override {
2438 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2440 // 0-15 are the 16 integer registers.
2442 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2446 void getDependentLibraryOption(llvm::StringRef Lib,
2447 llvm::SmallString<24> &Opt) const override {
2448 Opt = "/DEFAULTLIB:";
2449 Opt += qualifyWindowsLibrary(Lib);
2452 void getDetectMismatchOption(llvm::StringRef Name,
2453 llvm::StringRef Value,
2454 llvm::SmallString<32> &Opt) const override {
2455 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2459 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2460 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2461 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2462 if (GV->isDeclaration())
2464 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2465 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2466 llvm::Function *Fn = cast<llvm::Function>(GV);
2467 Fn->addFnAttr("stackrealign");
2469 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2470 llvm::Function *Fn = cast<llvm::Function>(GV);
2471 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2475 addStackProbeTargetAttributes(D, GV, CGM);
2479 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2481 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2483 // (a) If one of the classes is Memory, the whole argument is passed in
2486 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2489 // (c) If the size of the aggregate exceeds two eightbytes and the first
2490 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2491 // argument is passed in memory. NOTE: This is necessary to keep the
2492 // ABI working for processors that don't support the __m256 type.
2494 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2496 // Some of these are enforced by the merging logic. Others can arise
2497 // only with unions; for example:
2498 // union { _Complex double; unsigned; }
2500 // Note that clauses (b) and (c) were added in 0.98.
2504 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2506 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2508 if (Hi == SSEUp && Lo != SSE)
2512 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2513 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2514 // classified recursively so that always two fields are
2515 // considered. The resulting class is calculated according to
2516 // the classes of the fields in the eightbyte:
2518 // (a) If both classes are equal, this is the resulting class.
2520 // (b) If one of the classes is NO_CLASS, the resulting class is
2523 // (c) If one of the classes is MEMORY, the result is the MEMORY
2526 // (d) If one of the classes is INTEGER, the result is the
2529 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2530 // MEMORY is used as class.
2532 // (f) Otherwise class SSE is used.
2534 // Accum should never be memory (we should have returned) or
2535 // ComplexX87 (because this cannot be passed in a structure).
2536 assert((Accum != Memory && Accum != ComplexX87) &&
2537 "Invalid accumulated classification during merge.");
2538 if (Accum == Field || Field == NoClass)
2540 if (Field == Memory)
2542 if (Accum == NoClass)
2544 if (Accum == Integer || Field == Integer)
2546 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2547 Accum == X87 || Accum == X87Up)
2552 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2553 Class &Lo, Class &Hi, bool isNamedArg) const {
2554 // FIXME: This code can be simplified by introducing a simple value class for
2555 // Class pairs with appropriate constructor methods for the various
2558 // FIXME: Some of the split computations are wrong; unaligned vectors
2559 // shouldn't be passed in registers for example, so there is no chance they
2560 // can straddle an eightbyte. Verify & simplify.
2564 Class &Current = OffsetBase < 64 ? Lo : Hi;
2567 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2568 BuiltinType::Kind k = BT->getKind();
2570 if (k == BuiltinType::Void) {
2572 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2575 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2577 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2579 } else if (k == BuiltinType::LongDouble) {
2580 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2581 if (LDF == &llvm::APFloat::IEEEquad()) {
2584 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2587 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2590 llvm_unreachable("unexpected long double representation!");
2592 // FIXME: _Decimal32 and _Decimal64 are SSE.
2593 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2597 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2598 // Classify the underlying integer type.
2599 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2603 if (Ty->hasPointerRepresentation()) {
2608 if (Ty->isMemberPointerType()) {
2609 if (Ty->isMemberFunctionPointerType()) {
2610 if (Has64BitPointers) {
2611 // If Has64BitPointers, this is an {i64, i64}, so classify both
2615 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2616 // straddles an eightbyte boundary, Hi should be classified as well.
2617 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2618 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2619 if (EB_FuncPtr != EB_ThisAdj) {
2631 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2632 uint64_t Size = getContext().getTypeSize(VT);
2633 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2634 // gcc passes the following as integer:
2635 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2636 // 2 bytes - <2 x char>, <1 x short>
2637 // 1 byte - <1 x char>
2640 // If this type crosses an eightbyte boundary, it should be
2642 uint64_t EB_Lo = (OffsetBase) / 64;
2643 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2646 } else if (Size == 64) {
2647 QualType ElementType = VT->getElementType();
2649 // gcc passes <1 x double> in memory. :(
2650 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2653 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2654 // pass them as integer. For platforms where clang is the de facto
2655 // platform compiler, we must continue to use integer.
2656 if (!classifyIntegerMMXAsSSE() &&
2657 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2658 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2659 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2660 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2665 // If this type crosses an eightbyte boundary, it should be
2667 if (OffsetBase && OffsetBase != 64)
2669 } else if (Size == 128 ||
2670 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2671 QualType ElementType = VT->getElementType();
2673 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2674 if (passInt128VectorsInMem() && Size != 128 &&
2675 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2676 ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2679 // Arguments of 256-bits are split into four eightbyte chunks. The
2680 // least significant one belongs to class SSE and all the others to class
2681 // SSEUP. The original Lo and Hi design considers that types can't be
2682 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2683 // This design isn't correct for 256-bits, but since there're no cases
2684 // where the upper parts would need to be inspected, avoid adding
2685 // complexity and just consider Hi to match the 64-256 part.
2687 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2688 // registers if they are "named", i.e. not part of the "..." of a
2689 // variadic function.
2691 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2692 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2699 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2700 QualType ET = getContext().getCanonicalType(CT->getElementType());
2702 uint64_t Size = getContext().getTypeSize(Ty);
2703 if (ET->isIntegralOrEnumerationType()) {
2706 else if (Size <= 128)
2708 } else if (ET == getContext().FloatTy) {
2710 } else if (ET == getContext().DoubleTy) {
2712 } else if (ET == getContext().LongDoubleTy) {
2713 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2714 if (LDF == &llvm::APFloat::IEEEquad())
2716 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2717 Current = ComplexX87;
2718 else if (LDF == &llvm::APFloat::IEEEdouble())
2721 llvm_unreachable("unexpected long double representation!");
2724 // If this complex type crosses an eightbyte boundary then it
2726 uint64_t EB_Real = (OffsetBase) / 64;
2727 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2728 if (Hi == NoClass && EB_Real != EB_Imag)
2734 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2735 // Arrays are treated like structures.
2737 uint64_t Size = getContext().getTypeSize(Ty);
2739 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2740 // than eight eightbytes, ..., it has class MEMORY.
2744 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2745 // fields, it has class MEMORY.
2747 // Only need to check alignment of array base.
2748 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2751 // Otherwise implement simplified merge. We could be smarter about
2752 // this, but it isn't worth it and would be harder to verify.
2754 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2755 uint64_t ArraySize = AT->getSize().getZExtValue();
2757 // The only case a 256-bit wide vector could be used is when the array
2758 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2759 // to work for sizes wider than 128, early check and fallback to memory.
2762 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2765 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2766 Class FieldLo, FieldHi;
2767 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2768 Lo = merge(Lo, FieldLo);
2769 Hi = merge(Hi, FieldHi);
2770 if (Lo == Memory || Hi == Memory)
2774 postMerge(Size, Lo, Hi);
2775 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2779 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2780 uint64_t Size = getContext().getTypeSize(Ty);
2782 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2783 // than eight eightbytes, ..., it has class MEMORY.
2787 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2788 // copy constructor or a non-trivial destructor, it is passed by invisible
2790 if (getRecordArgABI(RT, getCXXABI()))
2793 const RecordDecl *RD = RT->getDecl();
2795 // Assume variable sized types are passed in memory.
2796 if (RD->hasFlexibleArrayMember())
2799 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2801 // Reset Lo class, this will be recomputed.
2804 // If this is a C++ record, classify the bases first.
2805 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2806 for (const auto &I : CXXRD->bases()) {
2807 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2808 "Unexpected base class!");
2810 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2812 // Classify this field.
2814 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2815 // single eightbyte, each is classified separately. Each eightbyte gets
2816 // initialized to class NO_CLASS.
2817 Class FieldLo, FieldHi;
2819 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2820 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2821 Lo = merge(Lo, FieldLo);
2822 Hi = merge(Hi, FieldHi);
2823 if (Lo == Memory || Hi == Memory) {
2824 postMerge(Size, Lo, Hi);
2830 // Classify the fields one at a time, merging the results.
2832 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2833 i != e; ++i, ++idx) {
2834 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2835 bool BitField = i->isBitField();
2837 // Ignore padding bit-fields.
2838 if (BitField && i->isUnnamedBitfield())
2841 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2842 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2844 // The only case a 256-bit wide vector could be used is when the struct
2845 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2846 // to work for sizes wider than 128, early check and fallback to memory.
2848 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2849 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2851 postMerge(Size, Lo, Hi);
2854 // Note, skip this test for bit-fields, see below.
2855 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2857 postMerge(Size, Lo, Hi);
2861 // Classify this field.
2863 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2864 // exceeds a single eightbyte, each is classified
2865 // separately. Each eightbyte gets initialized to class
2867 Class FieldLo, FieldHi;
2869 // Bit-fields require special handling, they do not force the
2870 // structure to be passed in memory even if unaligned, and
2871 // therefore they can straddle an eightbyte.
2873 assert(!i->isUnnamedBitfield());
2874 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2875 uint64_t Size = i->getBitWidthValue(getContext());
2877 uint64_t EB_Lo = Offset / 64;
2878 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2881 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2886 FieldHi = EB_Hi ? Integer : NoClass;
2889 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2890 Lo = merge(Lo, FieldLo);
2891 Hi = merge(Hi, FieldHi);
2892 if (Lo == Memory || Hi == Memory)
2896 postMerge(Size, Lo, Hi);
2900 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2901 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2903 if (!isAggregateTypeForABI(Ty)) {
2904 // Treat an enum type as its underlying type.
2905 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2906 Ty = EnumTy->getDecl()->getIntegerType();
2908 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2909 : ABIArgInfo::getDirect());
2912 return getNaturalAlignIndirect(Ty);
2915 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2916 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2917 uint64_t Size = getContext().getTypeSize(VecTy);
2918 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2919 if (Size <= 64 || Size > LargestVector)
2921 QualType EltTy = VecTy->getElementType();
2922 if (passInt128VectorsInMem() &&
2923 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
2924 EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
2931 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2932 unsigned freeIntRegs) const {
2933 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2936 // This assumption is optimistic, as there could be free registers available
2937 // when we need to pass this argument in memory, and LLVM could try to pass
2938 // the argument in the free register. This does not seem to happen currently,
2939 // but this code would be much safer if we could mark the argument with
2940 // 'onstack'. See PR12193.
2941 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2942 // Treat an enum type as its underlying type.
2943 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2944 Ty = EnumTy->getDecl()->getIntegerType();
2946 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2947 : ABIArgInfo::getDirect());
2950 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2951 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2953 // Compute the byval alignment. We specify the alignment of the byval in all
2954 // cases so that the mid-level optimizer knows the alignment of the byval.
2955 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2957 // Attempt to avoid passing indirect results using byval when possible. This
2958 // is important for good codegen.
2960 // We do this by coercing the value into a scalar type which the backend can
2961 // handle naturally (i.e., without using byval).
2963 // For simplicity, we currently only do this when we have exhausted all of the
2964 // free integer registers. Doing this when there are free integer registers
2965 // would require more care, as we would have to ensure that the coerced value
2966 // did not claim the unused register. That would require either reording the
2967 // arguments to the function (so that any subsequent inreg values came first),
2968 // or only doing this optimization when there were no following arguments that
2971 // We currently expect it to be rare (particularly in well written code) for
2972 // arguments to be passed on the stack when there are still free integer
2973 // registers available (this would typically imply large structs being passed
2974 // by value), so this seems like a fair tradeoff for now.
2976 // We can revisit this if the backend grows support for 'onstack' parameter
2977 // attributes. See PR12193.
2978 if (freeIntRegs == 0) {
2979 uint64_t Size = getContext().getTypeSize(Ty);
2981 // If this type fits in an eightbyte, coerce it into the matching integral
2982 // type, which will end up on the stack (with alignment 8).
2983 if (Align == 8 && Size <= 64)
2984 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2988 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
2991 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2992 /// register. Pick an LLVM IR type that will be passed as a vector register.
2993 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2994 // Wrapper structs/arrays that only contain vectors are passed just like
2995 // vectors; strip them off if present.
2996 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2997 Ty = QualType(InnerTy, 0);
2999 llvm::Type *IRType = CGT.ConvertType(Ty);
3000 if (isa<llvm::VectorType>(IRType)) {
3001 // Don't pass vXi128 vectors in their native type, the backend can't
3003 if (passInt128VectorsInMem() &&
3004 IRType->getVectorElementType()->isIntegerTy(128)) {
3005 // Use a vXi64 vector.
3006 uint64_t Size = getContext().getTypeSize(Ty);
3007 return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3014 if (IRType->getTypeID() == llvm::Type::FP128TyID)
3017 // We couldn't find the preferred IR vector type for 'Ty'.
3018 uint64_t Size = getContext().getTypeSize(Ty);
3019 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3022 // Return a LLVM IR vector type based on the size of 'Ty'.
3023 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3027 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3028 /// is known to either be off the end of the specified type or being in
3029 /// alignment padding. The user type specified is known to be at most 128 bits
3030 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3031 /// classification that put one of the two halves in the INTEGER class.
3033 /// It is conservatively correct to return false.
3034 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3035 unsigned EndBit, ASTContext &Context) {
3036 // If the bytes being queried are off the end of the type, there is no user
3037 // data hiding here. This handles analysis of builtins, vectors and other
3038 // types that don't contain interesting padding.
3039 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3040 if (TySize <= StartBit)
3043 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3044 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3045 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3047 // Check each element to see if the element overlaps with the queried range.
3048 for (unsigned i = 0; i != NumElts; ++i) {
3049 // If the element is after the span we care about, then we're done..
3050 unsigned EltOffset = i*EltSize;
3051 if (EltOffset >= EndBit) break;
3053 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3054 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3055 EndBit-EltOffset, Context))
3058 // If it overlaps no elements, then it is safe to process as padding.
3062 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3063 const RecordDecl *RD = RT->getDecl();
3064 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3066 // If this is a C++ record, check the bases first.
3067 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3068 for (const auto &I : CXXRD->bases()) {
3069 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3070 "Unexpected base class!");
3072 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3074 // If the base is after the span we care about, ignore it.
3075 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3076 if (BaseOffset >= EndBit) continue;
3078 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3079 if (!BitsContainNoUserData(I.getType(), BaseStart,
3080 EndBit-BaseOffset, Context))
3085 // Verify that no field has data that overlaps the region of interest. Yes
3086 // this could be sped up a lot by being smarter about queried fields,
3087 // however we're only looking at structs up to 16 bytes, so we don't care
3090 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3091 i != e; ++i, ++idx) {
3092 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3094 // If we found a field after the region we care about, then we're done.
3095 if (FieldOffset >= EndBit) break;
3097 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3098 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3103 // If nothing in this record overlapped the area of interest, then we're
3111 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3112 /// float member at the specified offset. For example, {int,{float}} has a
3113 /// float at offset 4. It is conservatively correct for this routine to return
3115 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3116 const llvm::DataLayout &TD) {
3117 // Base case if we find a float.
3118 if (IROffset == 0 && IRType->isFloatTy())
3121 // If this is a struct, recurse into the field at the specified offset.
3122 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3123 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3124 unsigned Elt = SL->getElementContainingOffset(IROffset);
3125 IROffset -= SL->getElementOffset(Elt);
3126 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3129 // If this is an array, recurse into the field at the specified offset.
3130 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3131 llvm::Type *EltTy = ATy->getElementType();
3132 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3133 IROffset -= IROffset/EltSize*EltSize;
3134 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3141 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3142 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3143 llvm::Type *X86_64ABIInfo::
3144 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3145 QualType SourceTy, unsigned SourceOffset) const {
3146 // The only three choices we have are either double, <2 x float>, or float. We
3147 // pass as float if the last 4 bytes is just padding. This happens for
3148 // structs that contain 3 floats.
3149 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3150 SourceOffset*8+64, getContext()))
3151 return llvm::Type::getFloatTy(getVMContext());
3153 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3154 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3156 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3157 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3158 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3160 return llvm::Type::getDoubleTy(getVMContext());
3164 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3165 /// an 8-byte GPR. This means that we either have a scalar or we are talking
3166 /// about the high or low part of an up-to-16-byte struct. This routine picks
3167 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3168 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3171 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3172 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
3173 /// the 8-byte value references. PrefType may be null.
3175 /// SourceTy is the source-level type for the entire argument. SourceOffset is
3176 /// an offset into this that we're processing (which is always either 0 or 8).
3178 llvm::Type *X86_64ABIInfo::
3179 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3180 QualType SourceTy, unsigned SourceOffset) const {
3181 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3182 // returning an 8-byte unit starting with it. See if we can safely use it.
3183 if (IROffset == 0) {
3184 // Pointers and int64's always fill the 8-byte unit.
3185 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3186 IRType->isIntegerTy(64))
3189 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3190 // goodness in the source type is just tail padding. This is allowed to
3191 // kick in for struct {double,int} on the int, but not on
3192 // struct{double,int,int} because we wouldn't return the second int. We
3193 // have to do this analysis on the source type because we can't depend on
3194 // unions being lowered a specific way etc.
3195 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3196 IRType->isIntegerTy(32) ||
3197 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3198 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3199 cast<llvm::IntegerType>(IRType)->getBitWidth();
3201 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3202 SourceOffset*8+64, getContext()))
3207 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3208 // If this is a struct, recurse into the field at the specified offset.
3209 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3210 if (IROffset < SL->getSizeInBytes()) {
3211 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3212 IROffset -= SL->getElementOffset(FieldIdx);
3214 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3215 SourceTy, SourceOffset);
3219 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3220 llvm::Type *EltTy = ATy->getElementType();
3221 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3222 unsigned EltOffset = IROffset/EltSize*EltSize;
3223 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3227 // Okay, we don't have any better idea of what to pass, so we pass this in an
3228 // integer register that isn't too big to fit the rest of the struct.
3229 unsigned TySizeInBytes =
3230 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3232 assert(TySizeInBytes != SourceOffset && "Empty field?");
3234 // It is always safe to classify this as an integer type up to i64 that
3235 // isn't larger than the structure.
3236 return llvm::IntegerType::get(getVMContext(),
3237 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3241 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3242 /// be used as elements of a two register pair to pass or return, return a
3243 /// first class aggregate to represent them. For example, if the low part of
3244 /// a by-value argument should be passed as i32* and the high part as float,
3245 /// return {i32*, float}.
3247 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3248 const llvm::DataLayout &TD) {
3249 // In order to correctly satisfy the ABI, we need to the high part to start
3250 // at offset 8. If the high and low parts we inferred are both 4-byte types
3251 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3252 // the second element at offset 8. Check for this:
3253 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3254 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3255 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3256 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3258 // To handle this, we have to increase the size of the low part so that the
3259 // second element will start at an 8 byte offset. We can't increase the size
3260 // of the second element because it might make us access off the end of the
3263 // There are usually two sorts of types the ABI generation code can produce
3264 // for the low part of a pair that aren't 8 bytes in size: float or
3265 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3267 // Promote these to a larger type.
3268 if (Lo->isFloatTy())
3269 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3271 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3272 && "Invalid/unknown lo type");
3273 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3277 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3279 // Verify that the second element is at an 8-byte offset.
3280 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3281 "Invalid x86-64 argument pair!");
3285 ABIArgInfo X86_64ABIInfo::
3286 classifyReturnType(QualType RetTy) const {
3287 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3288 // classification algorithm.
3289 X86_64ABIInfo::Class Lo, Hi;
3290 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3292 // Check some invariants.
3293 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3294 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3296 llvm::Type *ResType = nullptr;
3300 return ABIArgInfo::getIgnore();
3301 // If the low part is just padding, it takes no register, leave ResType
3303 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3304 "Unknown missing lo part");
3309 llvm_unreachable("Invalid classification for lo word.");
3311 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3314 return getIndirectReturnResult(RetTy);
3316 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3317 // available register of the sequence %rax, %rdx is used.
3319 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3321 // If we have a sign or zero extended integer, make sure to return Extend
3322 // so that the parameter gets the right LLVM IR attributes.
3323 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3324 // Treat an enum type as its underlying type.
3325 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3326 RetTy = EnumTy->getDecl()->getIntegerType();
3328 if (RetTy->isIntegralOrEnumerationType() &&
3329 RetTy->isPromotableIntegerType())
3330 return ABIArgInfo::getExtend(RetTy);
3334 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3335 // available SSE register of the sequence %xmm0, %xmm1 is used.
3337 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3340 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3341 // returned on the X87 stack in %st0 as 80-bit x87 number.
3343 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3346 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3347 // part of the value is returned in %st0 and the imaginary part in
3350 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3351 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3352 llvm::Type::getX86_FP80Ty(getVMContext()));
3356 llvm::Type *HighPart = nullptr;
3358 // Memory was handled previously and X87 should
3359 // never occur as a hi class.
3362 llvm_unreachable("Invalid classification for hi word.");
3364 case ComplexX87: // Previously handled.
3369 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3370 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3371 return ABIArgInfo::getDirect(HighPart, 8);
3374 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3375 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3376 return ABIArgInfo::getDirect(HighPart, 8);
3379 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3380 // is passed in the next available eightbyte chunk if the last used
3383 // SSEUP should always be preceded by SSE, just widen.
3385 assert(Lo == SSE && "Unexpected SSEUp classification.");
3386 ResType = GetByteVectorType(RetTy);
3389 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3390 // returned together with the previous X87 value in %st0.
3392 // If X87Up is preceded by X87, we don't need to do
3393 // anything. However, in some cases with unions it may not be
3394 // preceded by X87. In such situations we follow gcc and pass the
3395 // extra bits in an SSE reg.
3397 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3398 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3399 return ABIArgInfo::getDirect(HighPart, 8);
3404 // If a high part was specified, merge it together with the low part. It is
3405 // known to pass in the high eightbyte of the result. We do this by forming a
3406 // first class struct aggregate with the high and low part: {low, high}
3408 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3410 return ABIArgInfo::getDirect(ResType);
3413 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3414 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3418 Ty = useFirstFieldIfTransparentUnion(Ty);
3420 X86_64ABIInfo::Class Lo, Hi;
3421 classify(Ty, 0, Lo, Hi, isNamedArg);
3423 // Check some invariants.
3424 // FIXME: Enforce these by construction.
3425 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3426 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3430 llvm::Type *ResType = nullptr;
3434 return ABIArgInfo::getIgnore();
3435 // If the low part is just padding, it takes no register, leave ResType
3437 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3438 "Unknown missing lo part");
3441 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3445 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3446 // COMPLEX_X87, it is passed in memory.
3449 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3451 return getIndirectResult(Ty, freeIntRegs);
3455 llvm_unreachable("Invalid classification for lo word.");
3457 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3458 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3463 // Pick an 8-byte type based on the preferred type.
3464 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3466 // If we have a sign or zero extended integer, make sure to return Extend
3467 // so that the parameter gets the right LLVM IR attributes.
3468 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3469 // Treat an enum type as its underlying type.
3470 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3471 Ty = EnumTy->getDecl()->getIntegerType();
3473 if (Ty->isIntegralOrEnumerationType() &&
3474 Ty->isPromotableIntegerType())
3475 return ABIArgInfo::getExtend(Ty);
3480 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3481 // available SSE register is used, the registers are taken in the
3482 // order from %xmm0 to %xmm7.
3484 llvm::Type *IRType = CGT.ConvertType(Ty);
3485 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3491 llvm::Type *HighPart = nullptr;
3493 // Memory was handled previously, ComplexX87 and X87 should
3494 // never occur as hi classes, and X87Up must be preceded by X87,
3495 // which is passed in memory.
3499 llvm_unreachable("Invalid classification for hi word.");
3501 case NoClass: break;
3505 // Pick an 8-byte type based on the preferred type.
3506 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3508 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3509 return ABIArgInfo::getDirect(HighPart, 8);
3512 // X87Up generally doesn't occur here (long double is passed in
3513 // memory), except in situations involving unions.
3516 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3518 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3519 return ABIArgInfo::getDirect(HighPart, 8);
3524 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3525 // eightbyte is passed in the upper half of the last used SSE
3526 // register. This only happens when 128-bit vectors are passed.
3528 assert(Lo == SSE && "Unexpected SSEUp classification");
3529 ResType = GetByteVectorType(Ty);
3533 // If a high part was specified, merge it together with the low part. It is
3534 // known to pass in the high eightbyte of the result. We do this by forming a
3535 // first class struct aggregate with the high and low part: {low, high}
3537 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3539 return ABIArgInfo::getDirect(ResType);
3543 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3544 unsigned &NeededSSE) const {
3545 auto RT = Ty->getAs<RecordType>();
3546 assert(RT && "classifyRegCallStructType only valid with struct types");
3548 if (RT->getDecl()->hasFlexibleArrayMember())
3549 return getIndirectReturnResult(Ty);
3552 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3553 if (CXXRD->isDynamicClass()) {
3554 NeededInt = NeededSSE = 0;
3555 return getIndirectReturnResult(Ty);
3558 for (const auto &I : CXXRD->bases())
3559 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3561 NeededInt = NeededSSE = 0;
3562 return getIndirectReturnResult(Ty);
3567 for (const auto *FD : RT->getDecl()->fields()) {
3568 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3569 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3571 NeededInt = NeededSSE = 0;
3572 return getIndirectReturnResult(Ty);
3575 unsigned LocalNeededInt, LocalNeededSSE;
3576 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3577 LocalNeededSSE, true)
3579 NeededInt = NeededSSE = 0;
3580 return getIndirectReturnResult(Ty);
3582 NeededInt += LocalNeededInt;
3583 NeededSSE += LocalNeededSSE;
3587 return ABIArgInfo::getDirect();
3590 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3591 unsigned &NeededInt,
3592 unsigned &NeededSSE) const {
3597 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3600 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3602 const unsigned CallingConv = FI.getCallingConvention();
3603 // It is possible to force Win64 calling convention on any x86_64 target by
3604 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3605 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3606 if (CallingConv == llvm::CallingConv::Win64) {
3607 WinX86_64ABIInfo Win64ABIInfo(CGT, AVXLevel);
3608 Win64ABIInfo.computeInfo(FI);
3612 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3614 // Keep track of the number of assigned registers.
3615 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3616 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3617 unsigned NeededInt, NeededSSE;
3619 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3620 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3621 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3622 FI.getReturnInfo() =
3623 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3624 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3625 FreeIntRegs -= NeededInt;
3626 FreeSSERegs -= NeededSSE;
3628 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3630 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3631 // Complex Long Double Type is passed in Memory when Regcall
3632 // calling convention is used.
3633 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3634 if (getContext().getCanonicalType(CT->getElementType()) ==
3635 getContext().LongDoubleTy)
3636 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3638 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3641 // If the return value is indirect, then the hidden argument is consuming one
3642 // integer register.
3643 if (FI.getReturnInfo().isIndirect())
3646 // The chain argument effectively gives us another free register.
3647 if (FI.isChainCall())
3650 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3651 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3652 // get assigned (in left-to-right order) for passing as follows...
3654 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3655 it != ie; ++it, ++ArgNo) {
3656 bool IsNamedArg = ArgNo < NumRequiredArgs;
3658 if (IsRegCall && it->type->isStructureOrClassType())
3659 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3661 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3662 NeededSSE, IsNamedArg);
3664 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3665 // eightbyte of an argument, the whole argument is passed on the
3666 // stack. If registers have already been assigned for some
3667 // eightbytes of such an argument, the assignments get reverted.
3668 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3669 FreeIntRegs -= NeededInt;
3670 FreeSSERegs -= NeededSSE;
3672 it->info = getIndirectResult(it->type, FreeIntRegs);
3677 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3678 Address VAListAddr, QualType Ty) {
3679 Address overflow_arg_area_p =
3680 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_p");
3681 llvm::Value *overflow_arg_area =
3682 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3684 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3685 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3686 // It isn't stated explicitly in the standard, but in practice we use
3687 // alignment greater than 16 where necessary.
3688 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3689 if (Align > CharUnits::fromQuantity(8)) {
3690 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3694 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3695 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3697 CGF.Builder.CreateBitCast(overflow_arg_area,
3698 llvm::PointerType::getUnqual(LTy));
3700 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3701 // l->overflow_arg_area + sizeof(type).
3702 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3703 // an 8 byte boundary.
3705 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3706 llvm::Value *Offset =
3707 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3708 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3709 "overflow_arg_area.next");
3710 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3712 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3713 return Address(Res, Align);
3716 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3717 QualType Ty) const {
3718 // Assume that va_list type is correct; should be pointer to LLVM type:
3722 // i8* overflow_arg_area;
3723 // i8* reg_save_area;
3725 unsigned neededInt, neededSSE;
3727 Ty = getContext().getCanonicalType(Ty);
3728 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3729 /*isNamedArg*/false);
3731 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3732 // in the registers. If not go to step 7.
3733 if (!neededInt && !neededSSE)
3734 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3736 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3737 // general purpose registers needed to pass type and num_fp to hold
3738 // the number of floating point registers needed.
3740 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3741 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3742 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3744 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3745 // register save space).
3747 llvm::Value *InRegs = nullptr;
3748 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3749 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3751 gp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "gp_offset_p");
3752 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3753 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3754 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3758 fp_offset_p = CGF.Builder.CreateStructGEP(VAListAddr, 1, "fp_offset_p");
3759 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3760 llvm::Value *FitsInFP =
3761 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3762 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3763 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3766 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3767 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3768 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3769 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3771 // Emit code to load the value if it was passed in registers.
3773 CGF.EmitBlock(InRegBlock);
3775 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3776 // an offset of l->gp_offset and/or l->fp_offset. This may require
3777 // copying to a temporary location in case the parameter is passed
3778 // in different register classes or requires an alignment greater
3779 // than 8 for general purpose registers and 16 for XMM registers.
3781 // FIXME: This really results in shameful code when we end up needing to
3782 // collect arguments from different places; often what should result in a
3783 // simple assembling of a structure from scattered addresses has many more
3784 // loads than necessary. Can we clean this up?
3785 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3786 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3787 CGF.Builder.CreateStructGEP(VAListAddr, 3), "reg_save_area");
3789 Address RegAddr = Address::invalid();
3790 if (neededInt && neededSSE) {
3792 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3793 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3794 Address Tmp = CGF.CreateMemTemp(Ty);
3795 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3796 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3797 llvm::Type *TyLo = ST->getElementType(0);
3798 llvm::Type *TyHi = ST->getElementType(1);
3799 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3800 "Unexpected ABI info for mixed regs");
3801 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3802 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3803 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3804 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3805 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3806 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3808 // Copy the first element.
3809 // FIXME: Our choice of alignment here and below is probably pessimistic.
3810 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3811 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3812 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3813 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3815 // Copy the second element.
3816 V = CGF.Builder.CreateAlignedLoad(
3817 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3818 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3819 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3821 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3822 } else if (neededInt) {
3823 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3824 CharUnits::fromQuantity(8));
3825 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3827 // Copy to a temporary if necessary to ensure the appropriate alignment.
3828 std::pair<CharUnits, CharUnits> SizeAlign =
3829 getContext().getTypeInfoInChars(Ty);
3830 uint64_t TySize = SizeAlign.first.getQuantity();
3831 CharUnits TyAlign = SizeAlign.second;
3833 // Copy into a temporary if the type is more aligned than the
3834 // register save area.
3835 if (TyAlign.getQuantity() > 8) {
3836 Address Tmp = CGF.CreateMemTemp(Ty);
3837 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3841 } else if (neededSSE == 1) {
3842 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3843 CharUnits::fromQuantity(16));
3844 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3846 assert(neededSSE == 2 && "Invalid number of needed registers!");
3847 // SSE registers are spaced 16 bytes apart in the register save
3848 // area, we need to collect the two eightbytes together.
3849 // The ABI isn't explicit about this, but it seems reasonable
3850 // to assume that the slots are 16-byte aligned, since the stack is
3851 // naturally 16-byte aligned and the prologue is expected to store
3852 // all the SSE registers to the RSA.
3853 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3854 CharUnits::fromQuantity(16));
3856 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3857 CharUnits::fromQuantity(16));
3858 llvm::Type *ST = AI.canHaveCoerceToType()
3859 ? AI.getCoerceToType()
3860 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3862 Address Tmp = CGF.CreateMemTemp(Ty);
3863 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3864 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3865 RegAddrLo, ST->getStructElementType(0)));
3866 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 0));
3867 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3868 RegAddrHi, ST->getStructElementType(1)));
3869 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1));
3871 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3874 // AMD64-ABI 3.5.7p5: Step 5. Set:
3875 // l->gp_offset = l->gp_offset + num_gp * 8
3876 // l->fp_offset = l->fp_offset + num_fp * 16.
3878 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3879 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3883 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3884 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3887 CGF.EmitBranch(ContBlock);
3889 // Emit code to load the value if it was passed in memory.
3891 CGF.EmitBlock(InMemBlock);
3892 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3894 // Return the appropriate result.
3896 CGF.EmitBlock(ContBlock);
3897 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3902 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3903 QualType Ty) const {
3904 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3905 CGF.getContext().getTypeInfoInChars(Ty),
3906 CharUnits::fromQuantity(8),
3907 /*allowHigherAlign*/ false);
3911 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3912 const ABIArgInfo ¤t) const {
3913 // Assumes vectorCall calling convention.
3914 const Type *Base = nullptr;
3915 uint64_t NumElts = 0;
3917 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3918 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3919 FreeSSERegs -= NumElts;
3920 return getDirectX86Hva();
3925 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3926 bool IsReturnType, bool IsVectorCall,
3927 bool IsRegCall) const {
3929 if (Ty->isVoidType())
3930 return ABIArgInfo::getIgnore();
3932 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3933 Ty = EnumTy->getDecl()->getIntegerType();
3935 TypeInfo Info = getContext().getTypeInfo(Ty);
3936 uint64_t Width = Info.Width;
3937 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3939 const RecordType *RT = Ty->getAs<RecordType>();
3941 if (!IsReturnType) {
3942 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3943 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3946 if (RT->getDecl()->hasFlexibleArrayMember())
3947 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3951 const Type *Base = nullptr;
3952 uint64_t NumElts = 0;
3953 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3955 if ((IsVectorCall || IsRegCall) &&
3956 isHomogeneousAggregate(Ty, Base, NumElts)) {
3958 if (FreeSSERegs >= NumElts) {
3959 FreeSSERegs -= NumElts;
3960 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3961 return ABIArgInfo::getDirect();
3962 return ABIArgInfo::getExpand();
3964 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3965 } else if (IsVectorCall) {
3966 if (FreeSSERegs >= NumElts &&
3967 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3968 FreeSSERegs -= NumElts;
3969 return ABIArgInfo::getDirect();
3970 } else if (IsReturnType) {
3971 return ABIArgInfo::getExpand();
3972 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3973 // HVAs are delayed and reclassified in the 2nd step.
3974 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3979 if (Ty->isMemberPointerType()) {
3980 // If the member pointer is represented by an LLVM int or ptr, pass it
3982 llvm::Type *LLTy = CGT.ConvertType(Ty);
3983 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3984 return ABIArgInfo::getDirect();
3987 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3988 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3989 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3990 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3991 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3993 // Otherwise, coerce it to a small integer.
3994 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3997 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
3998 switch (BT->getKind()) {
3999 case BuiltinType::Bool:
4000 // Bool type is always extended to the ABI, other builtin types are not
4002 return ABIArgInfo::getExtend(Ty);
4004 case BuiltinType::LongDouble:
4005 // Mingw64 GCC uses the old 80 bit extended precision floating point
4006 // unit. It passes them indirectly through memory.
4008 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
4009 if (LDF == &llvm::APFloat::x87DoubleExtended())
4010 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4014 case BuiltinType::Int128:
4015 case BuiltinType::UInt128:
4016 // If it's a parameter type, the normal ABI rule is that arguments larger
4017 // than 8 bytes are passed indirectly. GCC follows it. We follow it too,
4018 // even though it isn't particularly efficient.
4020 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
4022 // Mingw64 GCC returns i128 in XMM0. Coerce to v2i64 to handle that.
4023 // Clang matches them for compatibility.
4024 return ABIArgInfo::getDirect(
4025 llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()), 2));
4032 return ABIArgInfo::getDirect();
4035 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
4036 unsigned FreeSSERegs,
4038 bool IsRegCall) const {
4040 for (auto &I : FI.arguments()) {
4041 // Vectorcall in x64 only permits the first 6 arguments to be passed
4042 // as XMM/YMM registers.
4043 if (Count < VectorcallMaxParamNumAsReg)
4044 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4046 // Since these cannot be passed in registers, pretend no registers
4048 unsigned ZeroSSERegsAvail = 0;
4049 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
4050 IsVectorCall, IsRegCall);
4055 for (auto &I : FI.arguments()) {
4056 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
4060 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
4061 const unsigned CC = FI.getCallingConvention();
4062 bool IsVectorCall = CC == llvm::CallingConv::X86_VectorCall;
4063 bool IsRegCall = CC == llvm::CallingConv::X86_RegCall;
4065 // If __attribute__((sysv_abi)) is in use, use the SysV argument
4066 // classification rules.
4067 if (CC == llvm::CallingConv::X86_64_SysV) {
4068 X86_64ABIInfo SysVABIInfo(CGT, AVXLevel);
4069 SysVABIInfo.computeInfo(FI);
4073 unsigned FreeSSERegs = 0;
4075 // We can use up to 4 SSE return registers with vectorcall.
4077 } else if (IsRegCall) {
4078 // RegCall gives us 16 SSE registers.
4082 if (!getCXXABI().classifyReturnType(FI))
4083 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4084 IsVectorCall, IsRegCall);
4087 // We can use up to 6 SSE register parameters with vectorcall.
4089 } else if (IsRegCall) {
4090 // RegCall gives us 16 SSE registers, we can reuse the return registers.
4095 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4097 for (auto &I : FI.arguments())
4098 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4103 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4104 QualType Ty) const {
4106 bool IsIndirect = false;
4108 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4109 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4110 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4111 uint64_t Width = getContext().getTypeSize(Ty);
4112 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4115 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4116 CGF.getContext().getTypeInfoInChars(Ty),
4117 CharUnits::fromQuantity(8),
4118 /*allowHigherAlign*/ false);
4123 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4124 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4125 bool IsSoftFloatABI;
4126 bool IsRetSmallStructInRegABI;
4128 CharUnits getParamTypeAlignment(QualType Ty) const;
4131 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI,
4132 bool RetSmallStructInRegABI)
4133 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI),
4134 IsRetSmallStructInRegABI(RetSmallStructInRegABI) {}
4136 ABIArgInfo classifyReturnType(QualType RetTy) const;
4138 void computeInfo(CGFunctionInfo &FI) const override {
4139 if (!getCXXABI().classifyReturnType(FI))
4140 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4141 for (auto &I : FI.arguments())
4142 I.info = classifyArgumentType(I.type);
4145 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4146 QualType Ty) const override;
4149 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4151 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI,
4152 bool RetSmallStructInRegABI)
4153 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI,
4154 RetSmallStructInRegABI)) {}
4156 static bool isStructReturnInRegABI(const llvm::Triple &Triple,
4157 const CodeGenOptions &Opts);
4159 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4160 // This is recovered from gcc output.
4161 return 1; // r1 is the dedicated stack pointer
4164 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4165 llvm::Value *Address) const override;
4169 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4170 // Complex types are passed just like their elements
4171 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4172 Ty = CTy->getElementType();
4174 if (Ty->isVectorType())
4175 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4178 // For single-element float/vector structs, we consider the whole type
4179 // to have the same alignment requirements as its single element.
4180 const Type *AlignTy = nullptr;
4181 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4182 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4183 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4184 (BT && BT->isFloatingPoint()))
4189 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4190 return CharUnits::fromQuantity(4);
4193 ABIArgInfo PPC32_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4196 // -msvr4-struct-return puts small aggregates in GPR3 and GPR4.
4197 if (isAggregateTypeForABI(RetTy) && IsRetSmallStructInRegABI &&
4198 (Size = getContext().getTypeSize(RetTy)) <= 64) {
4199 // System V ABI (1995), page 3-22, specified:
4200 // > A structure or union whose size is less than or equal to 8 bytes
4201 // > shall be returned in r3 and r4, as if it were first stored in the
4202 // > 8-byte aligned memory area and then the low addressed word were
4203 // > loaded into r3 and the high-addressed word into r4. Bits beyond
4204 // > the last member of the structure or union are not defined.
4206 // GCC for big-endian PPC32 inserts the pad before the first member,
4207 // not "beyond the last member" of the struct. To stay compatible
4208 // with GCC, we coerce the struct to an integer of the same size.
4209 // LLVM will extend it and return i32 in r3, or i64 in r3:r4.
4211 return ABIArgInfo::getIgnore();
4213 llvm::Type *CoerceTy = llvm::Type::getIntNTy(getVMContext(), Size);
4214 return ABIArgInfo::getDirect(CoerceTy);
4218 return DefaultABIInfo::classifyReturnType(RetTy);
4221 // TODO: this implementation is now likely redundant with
4222 // DefaultABIInfo::EmitVAArg.
4223 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4224 QualType Ty) const {
4225 if (getTarget().getTriple().isOSDarwin()) {
4226 auto TI = getContext().getTypeInfoInChars(Ty);
4227 TI.second = getParamTypeAlignment(Ty);
4229 CharUnits SlotSize = CharUnits::fromQuantity(4);
4230 return emitVoidPtrVAArg(CGF, VAList, Ty,
4231 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4232 /*AllowHigherAlign=*/true);
4235 const unsigned OverflowLimit = 8;
4236 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4237 // TODO: Implement this. For now ignore.
4239 return Address::invalid(); // FIXME?
4242 // struct __va_list_tag {
4243 // unsigned char gpr;
4244 // unsigned char fpr;
4245 // unsigned short reserved;
4246 // void *overflow_arg_area;
4247 // void *reg_save_area;
4250 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4252 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4253 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4255 // All aggregates are passed indirectly? That doesn't seem consistent
4256 // with the argument-lowering code.
4257 bool isIndirect = Ty->isAggregateType();
4259 CGBuilderTy &Builder = CGF.Builder;
4261 // The calling convention either uses 1-2 GPRs or 1 FPR.
4262 Address NumRegsAddr = Address::invalid();
4263 if (isInt || IsSoftFloatABI) {
4264 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, "gpr");
4266 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, "fpr");
4269 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4271 // "Align" the register count when TY is i64.
4272 if (isI64 || (isF64 && IsSoftFloatABI)) {
4273 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4274 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4278 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4280 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4281 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4282 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4284 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4286 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4287 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4289 // Case 1: consume registers.
4290 Address RegAddr = Address::invalid();
4292 CGF.EmitBlock(UsingRegs);
4294 Address RegSaveAreaPtr = Builder.CreateStructGEP(VAList, 4);
4295 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4296 CharUnits::fromQuantity(8));
4297 assert(RegAddr.getElementType() == CGF.Int8Ty);
4299 // Floating-point registers start after the general-purpose registers.
4300 if (!(isInt || IsSoftFloatABI)) {
4301 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4302 CharUnits::fromQuantity(32));
4305 // Get the address of the saved value by scaling the number of
4306 // registers we've used by the number of
4307 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4308 llvm::Value *RegOffset =
4309 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4310 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4311 RegAddr.getPointer(), RegOffset),
4312 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4313 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4315 // Increase the used-register count.
4317 Builder.CreateAdd(NumRegs,
4318 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4319 Builder.CreateStore(NumRegs, NumRegsAddr);
4321 CGF.EmitBranch(Cont);
4324 // Case 2: consume space in the overflow area.
4325 Address MemAddr = Address::invalid();
4327 CGF.EmitBlock(UsingOverflow);
4329 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4331 // Everything in the overflow area is rounded up to a size of at least 4.
4332 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4336 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4337 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4339 Size = CGF.getPointerSize();
4342 Address OverflowAreaAddr = Builder.CreateStructGEP(VAList, 3);
4343 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4345 // Round up address of argument to alignment
4346 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4347 if (Align > OverflowAreaAlign) {
4348 llvm::Value *Ptr = OverflowArea.getPointer();
4349 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4353 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4355 // Increase the overflow area.
4356 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4357 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4358 CGF.EmitBranch(Cont);
4361 CGF.EmitBlock(Cont);
4363 // Merge the cases with a phi.
4364 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4367 // Load the pointer if the argument was passed indirectly.
4369 Result = Address(Builder.CreateLoad(Result, "aggr"),
4370 getContext().getTypeAlignInChars(Ty));
4376 bool PPC32TargetCodeGenInfo::isStructReturnInRegABI(
4377 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
4378 assert(Triple.getArch() == llvm::Triple::ppc);
4380 switch (Opts.getStructReturnConvention()) {
4381 case CodeGenOptions::SRCK_Default:
4383 case CodeGenOptions::SRCK_OnStack: // -maix-struct-return
4385 case CodeGenOptions::SRCK_InRegs: // -msvr4-struct-return
4389 if (Triple.isOSBinFormatELF() && !Triple.isOSLinux())
4396 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4397 llvm::Value *Address) const {
4398 // This is calculated from the LLVM and GCC tables and verified
4399 // against gcc output. AFAIK all ABIs use the same encoding.
4401 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4403 llvm::IntegerType *i8 = CGF.Int8Ty;
4404 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4405 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4406 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4408 // 0-31: r0-31, the 4-byte general-purpose registers
4409 AssignToArrayRange(Builder, Address, Four8, 0, 31);
4411 // 32-63: fp0-31, the 8-byte floating-point registers
4412 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4414 // 64-76 are various 4-byte special-purpose registers:
4421 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4423 // 77-108: v0-31, the 16-byte vector registers
4424 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4431 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4439 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4440 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4448 static const unsigned GPRBits = 64;
4451 bool IsSoftFloatABI;
4453 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4454 // will be passed in a QPX register.
4455 bool IsQPXVectorTy(const Type *Ty) const {
4459 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4460 unsigned NumElements = VT->getNumElements();
4461 if (NumElements == 1)
4464 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4465 if (getContext().getTypeSize(Ty) <= 256)
4467 } else if (VT->getElementType()->
4468 isSpecificBuiltinType(BuiltinType::Float)) {
4469 if (getContext().getTypeSize(Ty) <= 128)
4477 bool IsQPXVectorTy(QualType Ty) const {
4478 return IsQPXVectorTy(Ty.getTypePtr());
4482 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4484 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4485 IsSoftFloatABI(SoftFloatABI) {}
4487 bool isPromotableTypeForABI(QualType Ty) const;
4488 CharUnits getParamTypeAlignment(QualType Ty) const;
4490 ABIArgInfo classifyReturnType(QualType RetTy) const;
4491 ABIArgInfo classifyArgumentType(QualType Ty) const;
4493 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4494 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4495 uint64_t Members) const override;
4497 // TODO: We can add more logic to computeInfo to improve performance.
4498 // Example: For aggregate arguments that fit in a register, we could
4499 // use getDirectInReg (as is done below for structs containing a single
4500 // floating-point value) to avoid pushing them to memory on function
4501 // entry. This would require changing the logic in PPCISelLowering
4502 // when lowering the parameters in the caller and args in the callee.
4503 void computeInfo(CGFunctionInfo &FI) const override {
4504 if (!getCXXABI().classifyReturnType(FI))
4505 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4506 for (auto &I : FI.arguments()) {
4507 // We rely on the default argument classification for the most part.
4508 // One exception: An aggregate containing a single floating-point
4509 // or vector item must be passed in a register if one is available.
4510 const Type *T = isSingleElementStruct(I.type, getContext());
4512 const BuiltinType *BT = T->getAs<BuiltinType>();
4513 if (IsQPXVectorTy(T) ||
4514 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4515 (BT && BT->isFloatingPoint())) {
4517 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4521 I.info = classifyArgumentType(I.type);
4525 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4526 QualType Ty) const override;
4528 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4529 bool asReturnValue) const override {
4530 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4533 bool isSwiftErrorInRegister() const override {
4538 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4541 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4542 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4544 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4547 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4548 // This is recovered from gcc output.
4549 return 1; // r1 is the dedicated stack pointer
4552 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4553 llvm::Value *Address) const override;
4556 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4558 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4560 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4561 // This is recovered from gcc output.
4562 return 1; // r1 is the dedicated stack pointer
4565 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4566 llvm::Value *Address) const override;
4571 // Return true if the ABI requires Ty to be passed sign- or zero-
4572 // extended to 64 bits.
4574 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4575 // Treat an enum type as its underlying type.
4576 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4577 Ty = EnumTy->getDecl()->getIntegerType();
4579 // Promotable integer types are required to be promoted by the ABI.
4580 if (Ty->isPromotableIntegerType())
4583 // In addition to the usual promotable integer types, we also need to
4584 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4585 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4586 switch (BT->getKind()) {
4587 case BuiltinType::Int:
4588 case BuiltinType::UInt:
4597 /// isAlignedParamType - Determine whether a type requires 16-byte or
4598 /// higher alignment in the parameter area. Always returns at least 8.
4599 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4600 // Complex types are passed just like their elements.
4601 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4602 Ty = CTy->getElementType();
4604 // Only vector types of size 16 bytes need alignment (larger types are
4605 // passed via reference, smaller types are not aligned).
4606 if (IsQPXVectorTy(Ty)) {
4607 if (getContext().getTypeSize(Ty) > 128)
4608 return CharUnits::fromQuantity(32);
4610 return CharUnits::fromQuantity(16);
4611 } else if (Ty->isVectorType()) {
4612 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4615 // For single-element float/vector structs, we consider the whole type
4616 // to have the same alignment requirements as its single element.
4617 const Type *AlignAsType = nullptr;
4618 const Type *EltType = isSingleElementStruct(Ty, getContext());
4620 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4621 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4622 getContext().getTypeSize(EltType) == 128) ||
4623 (BT && BT->isFloatingPoint()))
4624 AlignAsType = EltType;
4627 // Likewise for ELFv2 homogeneous aggregates.
4628 const Type *Base = nullptr;
4629 uint64_t Members = 0;
4630 if (!AlignAsType && Kind == ELFv2 &&
4631 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4634 // With special case aggregates, only vector base types need alignment.
4635 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4636 if (getContext().getTypeSize(AlignAsType) > 128)
4637 return CharUnits::fromQuantity(32);
4639 return CharUnits::fromQuantity(16);
4640 } else if (AlignAsType) {
4641 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4644 // Otherwise, we only need alignment for any aggregate type that
4645 // has an alignment requirement of >= 16 bytes.
4646 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4647 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4648 return CharUnits::fromQuantity(32);
4649 return CharUnits::fromQuantity(16);
4652 return CharUnits::fromQuantity(8);
4655 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4656 /// aggregate. Base is set to the base element type, and Members is set
4657 /// to the number of base elements.
4658 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4659 uint64_t &Members) const {
4660 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4661 uint64_t NElements = AT->getSize().getZExtValue();
4664 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4666 Members *= NElements;
4667 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4668 const RecordDecl *RD = RT->getDecl();
4669 if (RD->hasFlexibleArrayMember())
4674 // If this is a C++ record, check the bases first.
4675 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4676 for (const auto &I : CXXRD->bases()) {
4677 // Ignore empty records.
4678 if (isEmptyRecord(getContext(), I.getType(), true))
4681 uint64_t FldMembers;
4682 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4685 Members += FldMembers;
4689 for (const auto *FD : RD->fields()) {
4690 // Ignore (non-zero arrays of) empty records.
4691 QualType FT = FD->getType();
4692 while (const ConstantArrayType *AT =
4693 getContext().getAsConstantArrayType(FT)) {
4694 if (AT->getSize().getZExtValue() == 0)
4696 FT = AT->getElementType();
4698 if (isEmptyRecord(getContext(), FT, true))
4701 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4702 if (getContext().getLangOpts().CPlusPlus &&
4703 FD->isZeroLengthBitField(getContext()))
4706 uint64_t FldMembers;
4707 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4710 Members = (RD->isUnion() ?
4711 std::max(Members, FldMembers) : Members + FldMembers);
4717 // Ensure there is no padding.
4718 if (getContext().getTypeSize(Base) * Members !=
4719 getContext().getTypeSize(Ty))
4723 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4725 Ty = CT->getElementType();
4728 // Most ABIs only support float, double, and some vector type widths.
4729 if (!isHomogeneousAggregateBaseType(Ty))
4732 // The base type must be the same for all members. Types that
4733 // agree in both total size and mode (float vs. vector) are
4734 // treated as being equivalent here.
4735 const Type *TyPtr = Ty.getTypePtr();
4738 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4739 // so make sure to widen it explicitly.
4740 if (const VectorType *VT = Base->getAs<VectorType>()) {
4741 QualType EltTy = VT->getElementType();
4742 unsigned NumElements =
4743 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4745 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4750 if (Base->isVectorType() != TyPtr->isVectorType() ||
4751 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4754 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4757 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4758 // Homogeneous aggregates for ELFv2 must have base types of float,
4759 // double, long double, or 128-bit vectors.
4760 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4761 if (BT->getKind() == BuiltinType::Float ||
4762 BT->getKind() == BuiltinType::Double ||
4763 BT->getKind() == BuiltinType::LongDouble ||
4764 (getContext().getTargetInfo().hasFloat128Type() &&
4765 (BT->getKind() == BuiltinType::Float128))) {
4771 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4772 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4778 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4779 const Type *Base, uint64_t Members) const {
4780 // Vector and fp128 types require one register, other floating point types
4781 // require one or two registers depending on their size.
4783 ((getContext().getTargetInfo().hasFloat128Type() &&
4784 Base->isFloat128Type()) ||
4785 Base->isVectorType()) ? 1
4786 : (getContext().getTypeSize(Base) + 63) / 64;
4788 // Homogeneous Aggregates may occupy at most 8 registers.
4789 return Members * NumRegs <= 8;
4793 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4794 Ty = useFirstFieldIfTransparentUnion(Ty);
4796 if (Ty->isAnyComplexType())
4797 return ABIArgInfo::getDirect();
4799 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4800 // or via reference (larger than 16 bytes).
4801 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4802 uint64_t Size = getContext().getTypeSize(Ty);
4804 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4805 else if (Size < 128) {
4806 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4807 return ABIArgInfo::getDirect(CoerceTy);
4811 if (isAggregateTypeForABI(Ty)) {
4812 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4813 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4815 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4816 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4818 // ELFv2 homogeneous aggregates are passed as array types.
4819 const Type *Base = nullptr;
4820 uint64_t Members = 0;
4821 if (Kind == ELFv2 &&
4822 isHomogeneousAggregate(Ty, Base, Members)) {
4823 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4824 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4825 return ABIArgInfo::getDirect(CoerceTy);
4828 // If an aggregate may end up fully in registers, we do not
4829 // use the ByVal method, but pass the aggregate as array.
4830 // This is usually beneficial since we avoid forcing the
4831 // back-end to store the argument to memory.
4832 uint64_t Bits = getContext().getTypeSize(Ty);
4833 if (Bits > 0 && Bits <= 8 * GPRBits) {
4834 llvm::Type *CoerceTy;
4836 // Types up to 8 bytes are passed as integer type (which will be
4837 // properly aligned in the argument save area doubleword).
4838 if (Bits <= GPRBits)
4840 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4841 // Larger types are passed as arrays, with the base type selected
4842 // according to the required alignment in the save area.
4844 uint64_t RegBits = ABIAlign * 8;
4845 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4846 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4847 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4850 return ABIArgInfo::getDirect(CoerceTy);
4853 // All other aggregates are passed ByVal.
4854 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4856 /*Realign=*/TyAlign > ABIAlign);
4859 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4860 : ABIArgInfo::getDirect());
4864 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4865 if (RetTy->isVoidType())
4866 return ABIArgInfo::getIgnore();
4868 if (RetTy->isAnyComplexType())
4869 return ABIArgInfo::getDirect();
4871 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4872 // or via reference (larger than 16 bytes).
4873 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4874 uint64_t Size = getContext().getTypeSize(RetTy);
4876 return getNaturalAlignIndirect(RetTy);
4877 else if (Size < 128) {
4878 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4879 return ABIArgInfo::getDirect(CoerceTy);
4883 if (isAggregateTypeForABI(RetTy)) {
4884 // ELFv2 homogeneous aggregates are returned as array types.
4885 const Type *Base = nullptr;
4886 uint64_t Members = 0;
4887 if (Kind == ELFv2 &&
4888 isHomogeneousAggregate(RetTy, Base, Members)) {
4889 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4890 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4891 return ABIArgInfo::getDirect(CoerceTy);
4894 // ELFv2 small aggregates are returned in up to two registers.
4895 uint64_t Bits = getContext().getTypeSize(RetTy);
4896 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4898 return ABIArgInfo::getIgnore();
4900 llvm::Type *CoerceTy;
4901 if (Bits > GPRBits) {
4902 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4903 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
4906 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4907 return ABIArgInfo::getDirect(CoerceTy);
4910 // All other aggregates are returned indirectly.
4911 return getNaturalAlignIndirect(RetTy);
4914 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4915 : ABIArgInfo::getDirect());
4918 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4919 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4920 QualType Ty) const {
4921 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4922 TypeInfo.second = getParamTypeAlignment(Ty);
4924 CharUnits SlotSize = CharUnits::fromQuantity(8);
4926 // If we have a complex type and the base type is smaller than 8 bytes,
4927 // the ABI calls for the real and imaginary parts to be right-adjusted
4928 // in separate doublewords. However, Clang expects us to produce a
4929 // pointer to a structure with the two parts packed tightly. So generate
4930 // loads of the real and imaginary parts relative to the va_list pointer,
4931 // and store them to a temporary structure.
4932 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4933 CharUnits EltSize = TypeInfo.first / 2;
4934 if (EltSize < SlotSize) {
4935 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4936 SlotSize * 2, SlotSize,
4937 SlotSize, /*AllowHigher*/ true);
4939 Address RealAddr = Addr;
4940 Address ImagAddr = RealAddr;
4941 if (CGF.CGM.getDataLayout().isBigEndian()) {
4942 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4943 SlotSize - EltSize);
4944 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4945 2 * SlotSize - EltSize);
4947 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4950 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4951 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4952 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4953 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4954 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4956 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4957 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4963 // Otherwise, just use the general rule.
4964 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4965 TypeInfo, SlotSize, /*AllowHigher*/ true);
4969 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4970 llvm::Value *Address) {
4971 // This is calculated from the LLVM and GCC tables and verified
4972 // against gcc output. AFAIK all ABIs use the same encoding.
4974 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4976 llvm::IntegerType *i8 = CGF.Int8Ty;
4977 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4978 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4979 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4981 // 0-31: r0-31, the 8-byte general-purpose registers
4982 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4984 // 32-63: fp0-31, the 8-byte floating-point registers
4985 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4987 // 64-67 are various 8-byte special-purpose registers:
4992 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4994 // 68-76 are various 4-byte special-purpose registers:
4997 AssignToArrayRange(Builder, Address, Four8, 68, 76);
4999 // 77-108: v0-31, the 16-byte vector registers
5000 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
5010 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
5016 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
5017 CodeGen::CodeGenFunction &CGF,
5018 llvm::Value *Address) const {
5020 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
5024 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5025 llvm::Value *Address) const {
5027 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
5030 //===----------------------------------------------------------------------===//
5031 // AArch64 ABI Implementation
5032 //===----------------------------------------------------------------------===//
5036 class AArch64ABIInfo : public SwiftABIInfo {
5048 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
5049 : SwiftABIInfo(CGT), Kind(Kind) {}
5052 ABIKind getABIKind() const { return Kind; }
5053 bool isDarwinPCS() const { return Kind == DarwinPCS; }
5055 ABIArgInfo classifyReturnType(QualType RetTy, bool IsVariadic) const;
5056 ABIArgInfo classifyArgumentType(QualType RetTy) const;
5057 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5058 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5059 uint64_t Members) const override;
5061 bool isIllegalVectorType(QualType Ty) const;
5063 void computeInfo(CGFunctionInfo &FI) const override {
5064 if (!::classifyReturnType(getCXXABI(), FI, *this))
5065 FI.getReturnInfo() =
5066 classifyReturnType(FI.getReturnType(), FI.isVariadic());
5068 for (auto &it : FI.arguments())
5069 it.info = classifyArgumentType(it.type);
5072 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5073 CodeGenFunction &CGF) const;
5075 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
5076 CodeGenFunction &CGF) const;
5078 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5079 QualType Ty) const override {
5080 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
5081 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
5082 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
5085 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5086 QualType Ty) const override;
5088 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5089 bool asReturnValue) const override {
5090 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5092 bool isSwiftErrorInRegister() const override {
5096 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5097 unsigned elts) const override;
5100 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
5102 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
5103 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
5105 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5106 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
5109 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5113 bool doesReturnSlotInterfereWithArgs() const override { return false; }
5115 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5116 CodeGen::CodeGenModule &CGM) const override {
5117 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5121 CodeGenOptions::SignReturnAddressScope Scope = CGM.getCodeGenOpts().getSignReturnAddress();
5122 CodeGenOptions::SignReturnAddressKeyValue Key = CGM.getCodeGenOpts().getSignReturnAddressKey();
5123 bool BranchTargetEnforcement = CGM.getCodeGenOpts().BranchTargetEnforcement;
5124 if (const auto *TA = FD->getAttr<TargetAttr>()) {
5125 ParsedTargetAttr Attr = TA->parse();
5126 if (!Attr.BranchProtection.empty()) {
5127 TargetInfo::BranchProtectionInfo BPI;
5129 (void)CGM.getTarget().validateBranchProtection(Attr.BranchProtection,
5131 assert(Error.empty());
5132 Scope = BPI.SignReturnAddr;
5134 BranchTargetEnforcement = BPI.BranchTargetEnforcement;
5138 auto *Fn = cast<llvm::Function>(GV);
5139 if (Scope != CodeGenOptions::SignReturnAddressScope::None) {
5140 Fn->addFnAttr("sign-return-address",
5141 Scope == CodeGenOptions::SignReturnAddressScope::All
5145 Fn->addFnAttr("sign-return-address-key",
5146 Key == CodeGenOptions::SignReturnAddressKeyValue::AKey
5151 if (BranchTargetEnforcement)
5152 Fn->addFnAttr("branch-target-enforcement");
5156 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
5158 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
5159 : AArch64TargetCodeGenInfo(CGT, K) {}
5161 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5162 CodeGen::CodeGenModule &CGM) const override;
5164 void getDependentLibraryOption(llvm::StringRef Lib,
5165 llvm::SmallString<24> &Opt) const override {
5166 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5169 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5170 llvm::SmallString<32> &Opt) const override {
5171 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5175 void WindowsAArch64TargetCodeGenInfo::setTargetAttributes(
5176 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5177 AArch64TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5178 if (GV->isDeclaration())
5180 addStackProbeTargetAttributes(D, GV, CGM);
5184 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
5185 Ty = useFirstFieldIfTransparentUnion(Ty);
5187 // Handle illegal vector types here.
5188 if (isIllegalVectorType(Ty)) {
5189 uint64_t Size = getContext().getTypeSize(Ty);
5190 // Android promotes <2 x i8> to i16, not i32
5191 if (isAndroid() && (Size <= 16)) {
5192 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5193 return ABIArgInfo::getDirect(ResType);
5196 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5197 return ABIArgInfo::getDirect(ResType);
5200 llvm::Type *ResType =
5201 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5202 return ABIArgInfo::getDirect(ResType);
5205 llvm::Type *ResType =
5206 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5207 return ABIArgInfo::getDirect(ResType);
5209 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5212 if (!isAggregateTypeForABI(Ty)) {
5213 // Treat an enum type as its underlying type.
5214 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5215 Ty = EnumTy->getDecl()->getIntegerType();
5217 return (Ty->isPromotableIntegerType() && isDarwinPCS()
5218 ? ABIArgInfo::getExtend(Ty)
5219 : ABIArgInfo::getDirect());
5222 // Structures with either a non-trivial destructor or a non-trivial
5223 // copy constructor are always indirect.
5224 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5225 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5226 CGCXXABI::RAA_DirectInMemory);
5229 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5230 // elsewhere for GNU compatibility.
5231 uint64_t Size = getContext().getTypeSize(Ty);
5232 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5233 if (IsEmpty || Size == 0) {
5234 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5235 return ABIArgInfo::getIgnore();
5237 // GNU C mode. The only argument that gets ignored is an empty one with size
5239 if (IsEmpty && Size == 0)
5240 return ABIArgInfo::getIgnore();
5241 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5244 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5245 const Type *Base = nullptr;
5246 uint64_t Members = 0;
5247 if (isHomogeneousAggregate(Ty, Base, Members)) {
5248 return ABIArgInfo::getDirect(
5249 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5252 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5254 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5255 // same size and alignment.
5256 if (getTarget().isRenderScriptTarget()) {
5257 return coerceToIntArray(Ty, getContext(), getVMContext());
5260 if (Kind == AArch64ABIInfo::AAPCS) {
5261 Alignment = getContext().getTypeUnadjustedAlign(Ty);
5262 Alignment = Alignment < 128 ? 64 : 128;
5264 Alignment = std::max(getContext().getTypeAlign(Ty),
5265 (unsigned)getTarget().getPointerWidth(0));
5267 Size = llvm::alignTo(Size, Alignment);
5269 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5270 // For aggregates with 16-byte alignment, we use i128.
5271 llvm::Type *BaseTy = llvm::Type::getIntNTy(getVMContext(), Alignment);
5272 return ABIArgInfo::getDirect(
5273 Size == Alignment ? BaseTy
5274 : llvm::ArrayType::get(BaseTy, Size / Alignment));
5277 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5280 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy,
5281 bool IsVariadic) const {
5282 if (RetTy->isVoidType())
5283 return ABIArgInfo::getIgnore();
5285 // Large vector types should be returned via memory.
5286 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5287 return getNaturalAlignIndirect(RetTy);
5289 if (!isAggregateTypeForABI(RetTy)) {
5290 // Treat an enum type as its underlying type.
5291 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5292 RetTy = EnumTy->getDecl()->getIntegerType();
5294 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5295 ? ABIArgInfo::getExtend(RetTy)
5296 : ABIArgInfo::getDirect());
5299 uint64_t Size = getContext().getTypeSize(RetTy);
5300 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5301 return ABIArgInfo::getIgnore();
5303 const Type *Base = nullptr;
5304 uint64_t Members = 0;
5305 if (isHomogeneousAggregate(RetTy, Base, Members) &&
5306 !(getTarget().getTriple().getArch() == llvm::Triple::aarch64_32 &&
5308 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5309 return ABIArgInfo::getDirect();
5311 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5313 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5314 // same size and alignment.
5315 if (getTarget().isRenderScriptTarget()) {
5316 return coerceToIntArray(RetTy, getContext(), getVMContext());
5318 unsigned Alignment = getContext().getTypeAlign(RetTy);
5319 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5321 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5322 // For aggregates with 16-byte alignment, we use i128.
5323 if (Alignment < 128 && Size == 128) {
5324 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5325 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5327 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5330 return getNaturalAlignIndirect(RetTy);
5333 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5334 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5335 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5336 // Check whether VT is legal.
5337 unsigned NumElements = VT->getNumElements();
5338 uint64_t Size = getContext().getTypeSize(VT);
5339 // NumElements should be power of 2.
5340 if (!llvm::isPowerOf2_32(NumElements))
5343 // arm64_32 has to be compatible with the ARM logic here, which allows huge
5344 // vectors for some reason.
5345 llvm::Triple Triple = getTarget().getTriple();
5346 if (Triple.getArch() == llvm::Triple::aarch64_32 &&
5347 Triple.isOSBinFormatMachO())
5350 return Size != 64 && (Size != 128 || NumElements == 1);
5355 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5357 unsigned elts) const {
5358 if (!llvm::isPowerOf2_32(elts))
5360 if (totalSize.getQuantity() != 8 &&
5361 (totalSize.getQuantity() != 16 || elts == 1))
5366 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5367 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5368 // point type or a short-vector type. This is the same as the 32-bit ABI,
5369 // but with the difference that any floating-point type is allowed,
5370 // including __fp16.
5371 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5372 if (BT->isFloatingPoint())
5374 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5375 unsigned VecSize = getContext().getTypeSize(VT);
5376 if (VecSize == 64 || VecSize == 128)
5382 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5383 uint64_t Members) const {
5384 return Members <= 4;
5387 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5389 CodeGenFunction &CGF) const {
5390 ABIArgInfo AI = classifyArgumentType(Ty);
5391 bool IsIndirect = AI.isIndirect();
5393 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5395 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5396 else if (AI.getCoerceToType())
5397 BaseTy = AI.getCoerceToType();
5399 unsigned NumRegs = 1;
5400 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5401 BaseTy = ArrTy->getElementType();
5402 NumRegs = ArrTy->getNumElements();
5404 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5406 // The AArch64 va_list type and handling is specified in the Procedure Call
5407 // Standard, section B.4:
5417 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5418 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5419 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5420 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5422 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
5423 CharUnits TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty);
5425 Address reg_offs_p = Address::invalid();
5426 llvm::Value *reg_offs = nullptr;
5428 int RegSize = IsIndirect ? 8 : TySize.getQuantity();
5430 // 3 is the field number of __gr_offs
5431 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 3, "gr_offs_p");
5432 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5433 reg_top_index = 1; // field number for __gr_top
5434 RegSize = llvm::alignTo(RegSize, 8);
5436 // 4 is the field number of __vr_offs.
5437 reg_offs_p = CGF.Builder.CreateStructGEP(VAListAddr, 4, "vr_offs_p");
5438 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5439 reg_top_index = 2; // field number for __vr_top
5440 RegSize = 16 * NumRegs;
5443 //=======================================
5444 // Find out where argument was passed
5445 //=======================================
5447 // If reg_offs >= 0 we're already using the stack for this type of
5448 // argument. We don't want to keep updating reg_offs (in case it overflows,
5449 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5450 // whatever they get).
5451 llvm::Value *UsingStack = nullptr;
5452 UsingStack = CGF.Builder.CreateICmpSGE(
5453 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5455 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5457 // Otherwise, at least some kind of argument could go in these registers, the
5458 // question is whether this particular type is too big.
5459 CGF.EmitBlock(MaybeRegBlock);
5461 // Integer arguments may need to correct register alignment (for example a
5462 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5463 // align __gr_offs to calculate the potential address.
5464 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5465 int Align = TyAlign.getQuantity();
5467 reg_offs = CGF.Builder.CreateAdd(
5468 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5470 reg_offs = CGF.Builder.CreateAnd(
5471 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5475 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5476 // The fact that this is done unconditionally reflects the fact that
5477 // allocating an argument to the stack also uses up all the remaining
5478 // registers of the appropriate kind.
5479 llvm::Value *NewOffset = nullptr;
5480 NewOffset = CGF.Builder.CreateAdd(
5481 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5482 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5484 // Now we're in a position to decide whether this argument really was in
5485 // registers or not.
5486 llvm::Value *InRegs = nullptr;
5487 InRegs = CGF.Builder.CreateICmpSLE(
5488 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5490 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5492 //=======================================
5493 // Argument was in registers
5494 //=======================================
5496 // Now we emit the code for if the argument was originally passed in
5497 // registers. First start the appropriate block:
5498 CGF.EmitBlock(InRegBlock);
5500 llvm::Value *reg_top = nullptr;
5502 CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index, "reg_top_p");
5503 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5504 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5505 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5506 Address RegAddr = Address::invalid();
5507 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5510 // If it's been passed indirectly (actually a struct), whatever we find from
5511 // stored registers or on the stack will actually be a struct **.
5512 MemTy = llvm::PointerType::getUnqual(MemTy);
5515 const Type *Base = nullptr;
5516 uint64_t NumMembers = 0;
5517 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5518 if (IsHFA && NumMembers > 1) {
5519 // Homogeneous aggregates passed in registers will have their elements split
5520 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5521 // qN+1, ...). We reload and store into a temporary local variable
5523 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5524 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5525 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5526 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5527 Address Tmp = CGF.CreateTempAlloca(HFATy,
5528 std::max(TyAlign, BaseTyInfo.second));
5530 // On big-endian platforms, the value will be right-aligned in its slot.
5532 if (CGF.CGM.getDataLayout().isBigEndian() &&
5533 BaseTyInfo.first.getQuantity() < 16)
5534 Offset = 16 - BaseTyInfo.first.getQuantity();
5536 for (unsigned i = 0; i < NumMembers; ++i) {
5537 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5539 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5540 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5542 Address StoreAddr = CGF.Builder.CreateConstArrayGEP(Tmp, i);
5544 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5545 CGF.Builder.CreateStore(Elem, StoreAddr);
5548 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5550 // Otherwise the object is contiguous in memory.
5552 // It might be right-aligned in its slot.
5553 CharUnits SlotSize = BaseAddr.getAlignment();
5554 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5555 (IsHFA || !isAggregateTypeForABI(Ty)) &&
5556 TySize < SlotSize) {
5557 CharUnits Offset = SlotSize - TySize;
5558 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5561 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5564 CGF.EmitBranch(ContBlock);
5566 //=======================================
5567 // Argument was on the stack
5568 //=======================================
5569 CGF.EmitBlock(OnStackBlock);
5571 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0, "stack_p");
5572 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5574 // Again, stack arguments may need realignment. In this case both integer and
5575 // floating-point ones might be affected.
5576 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5577 int Align = TyAlign.getQuantity();
5579 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5581 OnStackPtr = CGF.Builder.CreateAdd(
5582 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5584 OnStackPtr = CGF.Builder.CreateAnd(
5585 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5588 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5590 Address OnStackAddr(OnStackPtr,
5591 std::max(CharUnits::fromQuantity(8), TyAlign));
5593 // All stack slots are multiples of 8 bytes.
5594 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5595 CharUnits StackSize;
5597 StackSize = StackSlotSize;
5599 StackSize = TySize.alignTo(StackSlotSize);
5601 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5602 llvm::Value *NewStack =
5603 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5605 // Write the new value of __stack for the next call to va_arg
5606 CGF.Builder.CreateStore(NewStack, stack_p);
5608 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5609 TySize < StackSlotSize) {
5610 CharUnits Offset = StackSlotSize - TySize;
5611 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5614 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5616 CGF.EmitBranch(ContBlock);
5618 //=======================================
5620 //=======================================
5621 CGF.EmitBlock(ContBlock);
5623 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5624 OnStackAddr, OnStackBlock, "vaargs.addr");
5627 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5633 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5634 CodeGenFunction &CGF) const {
5635 // The backend's lowering doesn't support va_arg for aggregates or
5636 // illegal vector types. Lower VAArg here for these cases and use
5637 // the LLVM va_arg instruction for everything else.
5638 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5639 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5641 uint64_t PointerSize = getTarget().getPointerWidth(0) / 8;
5642 CharUnits SlotSize = CharUnits::fromQuantity(PointerSize);
5644 // Empty records are ignored for parameter passing purposes.
5645 if (isEmptyRecord(getContext(), Ty, true)) {
5646 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5647 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5651 // The size of the actual thing passed, which might end up just
5652 // being a pointer for indirect types.
5653 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5655 // Arguments bigger than 16 bytes which aren't homogeneous
5656 // aggregates should be passed indirectly.
5657 bool IsIndirect = false;
5658 if (TyInfo.first.getQuantity() > 16) {
5659 const Type *Base = nullptr;
5660 uint64_t Members = 0;
5661 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5664 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5665 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5668 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5669 QualType Ty) const {
5670 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5671 CGF.getContext().getTypeInfoInChars(Ty),
5672 CharUnits::fromQuantity(8),
5673 /*allowHigherAlign*/ false);
5676 //===----------------------------------------------------------------------===//
5677 // ARM ABI Implementation
5678 //===----------------------------------------------------------------------===//
5682 class ARMABIInfo : public SwiftABIInfo {
5695 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5696 : SwiftABIInfo(CGT), Kind(_Kind) {
5700 bool isEABI() const {
5701 switch (getTarget().getTriple().getEnvironment()) {
5702 case llvm::Triple::Android:
5703 case llvm::Triple::EABI:
5704 case llvm::Triple::EABIHF:
5705 case llvm::Triple::GNUEABI:
5706 case llvm::Triple::GNUEABIHF:
5707 case llvm::Triple::MuslEABI:
5708 case llvm::Triple::MuslEABIHF:
5715 bool isEABIHF() const {
5716 switch (getTarget().getTriple().getEnvironment()) {
5717 case llvm::Triple::EABIHF:
5718 case llvm::Triple::GNUEABIHF:
5719 case llvm::Triple::MuslEABIHF:
5726 ABIKind getABIKind() const { return Kind; }
5729 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic,
5730 unsigned functionCallConv) const;
5731 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic,
5732 unsigned functionCallConv) const;
5733 ABIArgInfo classifyHomogeneousAggregate(QualType Ty, const Type *Base,
5734 uint64_t Members) const;
5735 ABIArgInfo coerceIllegalVector(QualType Ty) const;
5736 bool isIllegalVectorType(QualType Ty) const;
5737 bool containsAnyFP16Vectors(QualType Ty) const;
5739 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5740 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5741 uint64_t Members) const override;
5743 bool isEffectivelyAAPCS_VFP(unsigned callConvention, bool acceptHalf) const;
5745 void computeInfo(CGFunctionInfo &FI) const override;
5747 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5748 QualType Ty) const override;
5750 llvm::CallingConv::ID getLLVMDefaultCC() const;
5751 llvm::CallingConv::ID getABIDefaultCC() const;
5754 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5755 bool asReturnValue) const override {
5756 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5758 bool isSwiftErrorInRegister() const override {
5761 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5762 unsigned elts) const override;
5765 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5767 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5768 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5770 const ARMABIInfo &getABIInfo() const {
5771 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5774 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5778 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5779 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
5782 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5783 llvm::Value *Address) const override {
5784 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5786 // 0-15 are the 16 integer registers.
5787 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5791 unsigned getSizeOfUnwindException() const override {
5792 if (getABIInfo().isEABI()) return 88;
5793 return TargetCodeGenInfo::getSizeOfUnwindException();
5796 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5797 CodeGen::CodeGenModule &CGM) const override {
5798 if (GV->isDeclaration())
5800 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5804 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5809 switch (Attr->getInterrupt()) {
5810 case ARMInterruptAttr::Generic: Kind = ""; break;
5811 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5812 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5813 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5814 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5815 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5818 llvm::Function *Fn = cast<llvm::Function>(GV);
5820 Fn->addFnAttr("interrupt", Kind);
5822 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5823 if (ABI == ARMABIInfo::APCS)
5826 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5827 // however this is not necessarily true on taking any interrupt. Instruct
5828 // the backend to perform a realignment as part of the function prologue.
5829 llvm::AttrBuilder B;
5830 B.addStackAlignmentAttr(8);
5831 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5835 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5837 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5838 : ARMTargetCodeGenInfo(CGT, K) {}
5840 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5841 CodeGen::CodeGenModule &CGM) const override;
5843 void getDependentLibraryOption(llvm::StringRef Lib,
5844 llvm::SmallString<24> &Opt) const override {
5845 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5848 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5849 llvm::SmallString<32> &Opt) const override {
5850 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5854 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5855 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5856 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5857 if (GV->isDeclaration())
5859 addStackProbeTargetAttributes(D, GV, CGM);
5863 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5864 if (!::classifyReturnType(getCXXABI(), FI, *this))
5865 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), FI.isVariadic(),
5866 FI.getCallingConvention());
5868 for (auto &I : FI.arguments())
5869 I.info = classifyArgumentType(I.type, FI.isVariadic(),
5870 FI.getCallingConvention());
5873 // Always honor user-specified calling convention.
5874 if (FI.getCallingConvention() != llvm::CallingConv::C)
5877 llvm::CallingConv::ID cc = getRuntimeCC();
5878 if (cc != llvm::CallingConv::C)
5879 FI.setEffectiveCallingConvention(cc);
5882 /// Return the default calling convention that LLVM will use.
5883 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5884 // The default calling convention that LLVM will infer.
5885 if (isEABIHF() || getTarget().getTriple().isWatchABI())
5886 return llvm::CallingConv::ARM_AAPCS_VFP;
5888 return llvm::CallingConv::ARM_AAPCS;
5890 return llvm::CallingConv::ARM_APCS;
5893 /// Return the calling convention that our ABI would like us to use
5894 /// as the C calling convention.
5895 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5896 switch (getABIKind()) {
5897 case APCS: return llvm::CallingConv::ARM_APCS;
5898 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5899 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5900 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5902 llvm_unreachable("bad ABI kind");
5905 void ARMABIInfo::setCCs() {
5906 assert(getRuntimeCC() == llvm::CallingConv::C);
5908 // Don't muddy up the IR with a ton of explicit annotations if
5909 // they'd just match what LLVM will infer from the triple.
5910 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5911 if (abiCC != getLLVMDefaultCC())
5915 ABIArgInfo ARMABIInfo::coerceIllegalVector(QualType Ty) const {
5916 uint64_t Size = getContext().getTypeSize(Ty);
5918 llvm::Type *ResType =
5919 llvm::Type::getInt32Ty(getVMContext());
5920 return ABIArgInfo::getDirect(ResType);
5922 if (Size == 64 || Size == 128) {
5923 llvm::Type *ResType = llvm::VectorType::get(
5924 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5925 return ABIArgInfo::getDirect(ResType);
5927 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5930 ABIArgInfo ARMABIInfo::classifyHomogeneousAggregate(QualType Ty,
5932 uint64_t Members) const {
5933 assert(Base && "Base class should be set for homogeneous aggregate");
5934 // Base can be a floating-point or a vector.
5935 if (const VectorType *VT = Base->getAs<VectorType>()) {
5936 // FP16 vectors should be converted to integer vectors
5937 if (!getTarget().hasLegalHalfType() && containsAnyFP16Vectors(Ty)) {
5938 uint64_t Size = getContext().getTypeSize(VT);
5939 llvm::Type *NewVecTy = llvm::VectorType::get(
5940 llvm::Type::getInt32Ty(getVMContext()), Size / 32);
5941 llvm::Type *Ty = llvm::ArrayType::get(NewVecTy, Members);
5942 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5945 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5948 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, bool isVariadic,
5949 unsigned functionCallConv) const {
5950 // 6.1.2.1 The following argument types are VFP CPRCs:
5951 // A single-precision floating-point type (including promoted
5952 // half-precision types); A double-precision floating-point type;
5953 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5954 // with a Base Type of a single- or double-precision floating-point type,
5955 // 64-bit containerized vectors or 128-bit containerized vectors with one
5956 // to four Elements.
5957 // Variadic functions should always marshal to the base standard.
5959 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ false);
5961 Ty = useFirstFieldIfTransparentUnion(Ty);
5963 // Handle illegal vector types here.
5964 if (isIllegalVectorType(Ty))
5965 return coerceIllegalVector(Ty);
5967 // _Float16 and __fp16 get passed as if it were an int or float, but with
5968 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5969 // half type natively, and does not need to interwork with AAPCS code.
5970 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5971 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5972 llvm::Type *ResType = IsAAPCS_VFP ?
5973 llvm::Type::getFloatTy(getVMContext()) :
5974 llvm::Type::getInt32Ty(getVMContext());
5975 return ABIArgInfo::getDirect(ResType);
5978 if (!isAggregateTypeForABI(Ty)) {
5979 // Treat an enum type as its underlying type.
5980 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5981 Ty = EnumTy->getDecl()->getIntegerType();
5984 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
5985 : ABIArgInfo::getDirect());
5988 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5989 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5992 // Ignore empty records.
5993 if (isEmptyRecord(getContext(), Ty, true))
5994 return ABIArgInfo::getIgnore();
5997 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5998 // into VFP registers.
5999 const Type *Base = nullptr;
6000 uint64_t Members = 0;
6001 if (isHomogeneousAggregate(Ty, Base, Members))
6002 return classifyHomogeneousAggregate(Ty, Base, Members);
6003 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6004 // WatchOS does have homogeneous aggregates. Note that we intentionally use
6005 // this convention even for a variadic function: the backend will use GPRs
6007 const Type *Base = nullptr;
6008 uint64_t Members = 0;
6009 if (isHomogeneousAggregate(Ty, Base, Members)) {
6010 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
6012 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
6013 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
6017 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6018 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
6019 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
6020 // bigger than 128-bits, they get placed in space allocated by the caller,
6021 // and a pointer is passed.
6022 return ABIArgInfo::getIndirect(
6023 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
6026 // Support byval for ARM.
6027 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
6028 // most 8-byte. We realign the indirect argument if type alignment is bigger
6029 // than ABI alignment.
6030 uint64_t ABIAlign = 4;
6032 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6033 getABIKind() == ARMABIInfo::AAPCS) {
6034 TyAlign = getContext().getTypeUnadjustedAlignInChars(Ty).getQuantity();
6035 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
6037 TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
6039 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
6040 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
6041 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
6043 /*Realign=*/TyAlign > ABIAlign);
6046 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
6047 // same size and alignment.
6048 if (getTarget().isRenderScriptTarget()) {
6049 return coerceToIntArray(Ty, getContext(), getVMContext());
6052 // Otherwise, pass by coercing to a structure of the appropriate size.
6055 // FIXME: Try to match the types of the arguments more accurately where
6058 ElemTy = llvm::Type::getInt32Ty(getVMContext());
6059 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
6061 ElemTy = llvm::Type::getInt64Ty(getVMContext());
6062 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
6065 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
6068 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
6069 llvm::LLVMContext &VMContext) {
6070 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
6071 // is called integer-like if its size is less than or equal to one word, and
6072 // the offset of each of its addressable sub-fields is zero.
6074 uint64_t Size = Context.getTypeSize(Ty);
6076 // Check that the type fits in a word.
6080 // FIXME: Handle vector types!
6081 if (Ty->isVectorType())
6084 // Float types are never treated as "integer like".
6085 if (Ty->isRealFloatingType())
6088 // If this is a builtin or pointer type then it is ok.
6089 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
6092 // Small complex integer types are "integer like".
6093 if (const ComplexType *CT = Ty->getAs<ComplexType>())
6094 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
6096 // Single element and zero sized arrays should be allowed, by the definition
6097 // above, but they are not.
6099 // Otherwise, it must be a record type.
6100 const RecordType *RT = Ty->getAs<RecordType>();
6101 if (!RT) return false;
6103 // Ignore records with flexible arrays.
6104 const RecordDecl *RD = RT->getDecl();
6105 if (RD->hasFlexibleArrayMember())
6108 // Check that all sub-fields are at offset 0, and are themselves "integer
6110 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
6112 bool HadField = false;
6114 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6115 i != e; ++i, ++idx) {
6116 const FieldDecl *FD = *i;
6118 // Bit-fields are not addressable, we only need to verify they are "integer
6119 // like". We still have to disallow a subsequent non-bitfield, for example:
6120 // struct { int : 0; int x }
6121 // is non-integer like according to gcc.
6122 if (FD->isBitField()) {
6126 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6132 // Check if this field is at offset 0.
6133 if (Layout.getFieldOffset(idx) != 0)
6136 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
6139 // Only allow at most one field in a structure. This doesn't match the
6140 // wording above, but follows gcc in situations with a field following an
6142 if (!RD->isUnion()) {
6153 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy, bool isVariadic,
6154 unsigned functionCallConv) const {
6156 // Variadic functions should always marshal to the base standard.
6158 !isVariadic && isEffectivelyAAPCS_VFP(functionCallConv, /* AAPCS16 */ true);
6160 if (RetTy->isVoidType())
6161 return ABIArgInfo::getIgnore();
6163 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
6164 // Large vector types should be returned via memory.
6165 if (getContext().getTypeSize(RetTy) > 128)
6166 return getNaturalAlignIndirect(RetTy);
6167 // FP16 vectors should be converted to integer vectors
6168 if (!getTarget().hasLegalHalfType() &&
6169 (VT->getElementType()->isFloat16Type() ||
6170 VT->getElementType()->isHalfType()))
6171 return coerceIllegalVector(RetTy);
6174 // _Float16 and __fp16 get returned as if it were an int or float, but with
6175 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
6176 // half type natively, and does not need to interwork with AAPCS code.
6177 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
6178 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
6179 llvm::Type *ResType = IsAAPCS_VFP ?
6180 llvm::Type::getFloatTy(getVMContext()) :
6181 llvm::Type::getInt32Ty(getVMContext());
6182 return ABIArgInfo::getDirect(ResType);
6185 if (!isAggregateTypeForABI(RetTy)) {
6186 // Treat an enum type as its underlying type.
6187 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6188 RetTy = EnumTy->getDecl()->getIntegerType();
6190 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6191 : ABIArgInfo::getDirect();
6194 // Are we following APCS?
6195 if (getABIKind() == APCS) {
6196 if (isEmptyRecord(getContext(), RetTy, false))
6197 return ABIArgInfo::getIgnore();
6199 // Complex types are all returned as packed integers.
6201 // FIXME: Consider using 2 x vector types if the back end handles them
6203 if (RetTy->isAnyComplexType())
6204 return ABIArgInfo::getDirect(llvm::IntegerType::get(
6205 getVMContext(), getContext().getTypeSize(RetTy)));
6207 // Integer like structures are returned in r0.
6208 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
6209 // Return in the smallest viable integer type.
6210 uint64_t Size = getContext().getTypeSize(RetTy);
6212 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6214 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6215 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6218 // Otherwise return in memory.
6219 return getNaturalAlignIndirect(RetTy);
6222 // Otherwise this is an AAPCS variant.
6224 if (isEmptyRecord(getContext(), RetTy, true))
6225 return ABIArgInfo::getIgnore();
6227 // Check for homogeneous aggregates with AAPCS-VFP.
6229 const Type *Base = nullptr;
6230 uint64_t Members = 0;
6231 if (isHomogeneousAggregate(RetTy, Base, Members))
6232 return classifyHomogeneousAggregate(RetTy, Base, Members);
6235 // Aggregates <= 4 bytes are returned in r0; other aggregates
6236 // are returned indirectly.
6237 uint64_t Size = getContext().getTypeSize(RetTy);
6239 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6240 // same size and alignment.
6241 if (getTarget().isRenderScriptTarget()) {
6242 return coerceToIntArray(RetTy, getContext(), getVMContext());
6244 if (getDataLayout().isBigEndian())
6245 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6246 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6248 // Return in the smallest viable integer type.
6250 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6252 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6253 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6254 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6255 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6256 llvm::Type *CoerceTy =
6257 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6258 return ABIArgInfo::getDirect(CoerceTy);
6261 return getNaturalAlignIndirect(RetTy);
6264 /// isIllegalVector - check whether Ty is an illegal vector type.
6265 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6266 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6267 // On targets that don't support FP16, FP16 is expanded into float, and we
6268 // don't want the ABI to depend on whether or not FP16 is supported in
6269 // hardware. Thus return false to coerce FP16 vectors into integer vectors.
6270 if (!getTarget().hasLegalHalfType() &&
6271 (VT->getElementType()->isFloat16Type() ||
6272 VT->getElementType()->isHalfType()))
6275 // Android shipped using Clang 3.1, which supported a slightly different
6276 // vector ABI. The primary differences were that 3-element vector types
6277 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6278 // accepts that legacy behavior for Android only.
6279 // Check whether VT is legal.
6280 unsigned NumElements = VT->getNumElements();
6281 // NumElements should be power of 2 or equal to 3.
6282 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6285 // Check whether VT is legal.
6286 unsigned NumElements = VT->getNumElements();
6287 uint64_t Size = getContext().getTypeSize(VT);
6288 // NumElements should be power of 2.
6289 if (!llvm::isPowerOf2_32(NumElements))
6291 // Size should be greater than 32 bits.
6298 /// Return true if a type contains any 16-bit floating point vectors
6299 bool ARMABIInfo::containsAnyFP16Vectors(QualType Ty) const {
6300 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
6301 uint64_t NElements = AT->getSize().getZExtValue();
6304 return containsAnyFP16Vectors(AT->getElementType());
6305 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
6306 const RecordDecl *RD = RT->getDecl();
6308 // If this is a C++ record, check the bases first.
6309 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6310 if (llvm::any_of(CXXRD->bases(), [this](const CXXBaseSpecifier &B) {
6311 return containsAnyFP16Vectors(B.getType());
6315 if (llvm::any_of(RD->fields(), [this](FieldDecl *FD) {
6316 return FD && containsAnyFP16Vectors(FD->getType());
6322 if (const VectorType *VT = Ty->getAs<VectorType>())
6323 return (VT->getElementType()->isFloat16Type() ||
6324 VT->getElementType()->isHalfType());
6329 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6331 unsigned numElts) const {
6332 if (!llvm::isPowerOf2_32(numElts))
6334 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6337 if (vectorSize.getQuantity() != 8 &&
6338 (vectorSize.getQuantity() != 16 || numElts == 1))
6343 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6344 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6345 // double, or 64-bit or 128-bit vectors.
6346 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6347 if (BT->getKind() == BuiltinType::Float ||
6348 BT->getKind() == BuiltinType::Double ||
6349 BT->getKind() == BuiltinType::LongDouble)
6351 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6352 unsigned VecSize = getContext().getTypeSize(VT);
6353 if (VecSize == 64 || VecSize == 128)
6359 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6360 uint64_t Members) const {
6361 return Members <= 4;
6364 bool ARMABIInfo::isEffectivelyAAPCS_VFP(unsigned callConvention,
6365 bool acceptHalf) const {
6366 // Give precedence to user-specified calling conventions.
6367 if (callConvention != llvm::CallingConv::C)
6368 return (callConvention == llvm::CallingConv::ARM_AAPCS_VFP);
6370 return (getABIKind() == AAPCS_VFP) ||
6371 (acceptHalf && (getABIKind() == AAPCS16_VFP));
6374 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6375 QualType Ty) const {
6376 CharUnits SlotSize = CharUnits::fromQuantity(4);
6378 // Empty records are ignored for parameter passing purposes.
6379 if (isEmptyRecord(getContext(), Ty, true)) {
6380 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6381 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6385 CharUnits TySize = getContext().getTypeSizeInChars(Ty);
6386 CharUnits TyAlignForABI = getContext().getTypeUnadjustedAlignInChars(Ty);
6388 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6389 bool IsIndirect = false;
6390 const Type *Base = nullptr;
6391 uint64_t Members = 0;
6392 if (TySize > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6395 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6396 // allocated by the caller.
6397 } else if (TySize > CharUnits::fromQuantity(16) &&
6398 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6399 !isHomogeneousAggregate(Ty, Base, Members)) {
6402 // Otherwise, bound the type's ABI alignment.
6403 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6404 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6405 // Our callers should be prepared to handle an under-aligned address.
6406 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6407 getABIKind() == ARMABIInfo::AAPCS) {
6408 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6409 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6410 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6411 // ARMv7k allows type alignment up to 16 bytes.
6412 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6413 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6415 TyAlignForABI = CharUnits::fromQuantity(4);
6418 std::pair<CharUnits, CharUnits> TyInfo = { TySize, TyAlignForABI };
6419 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6420 SlotSize, /*AllowHigherAlign*/ true);
6423 //===----------------------------------------------------------------------===//
6424 // NVPTX ABI Implementation
6425 //===----------------------------------------------------------------------===//
6429 class NVPTXABIInfo : public ABIInfo {
6431 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6433 ABIArgInfo classifyReturnType(QualType RetTy) const;
6434 ABIArgInfo classifyArgumentType(QualType Ty) const;
6436 void computeInfo(CGFunctionInfo &FI) const override;
6437 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6438 QualType Ty) const override;
6441 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6443 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6444 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
6446 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6447 CodeGen::CodeGenModule &M) const override;
6448 bool shouldEmitStaticExternCAliases() const override;
6451 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6452 // resulting MDNode to the nvvm.annotations MDNode.
6453 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
6456 /// Checks if the type is unsupported directly by the current target.
6457 static bool isUnsupportedType(ASTContext &Context, QualType T) {
6458 if (!Context.getTargetInfo().hasFloat16Type() && T->isFloat16Type())
6460 if (!Context.getTargetInfo().hasFloat128Type() &&
6461 (T->isFloat128Type() ||
6462 (T->isRealFloatingType() && Context.getTypeSize(T) == 128)))
6464 if (!Context.getTargetInfo().hasInt128Type() && T->isIntegerType() &&
6465 Context.getTypeSize(T) > 64)
6467 if (const auto *AT = T->getAsArrayTypeUnsafe())
6468 return isUnsupportedType(Context, AT->getElementType());
6469 const auto *RT = T->getAs<RecordType>();
6472 const RecordDecl *RD = RT->getDecl();
6474 // If this is a C++ record, check the bases first.
6475 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6476 for (const CXXBaseSpecifier &I : CXXRD->bases())
6477 if (isUnsupportedType(Context, I.getType()))
6480 for (const FieldDecl *I : RD->fields())
6481 if (isUnsupportedType(Context, I->getType()))
6486 /// Coerce the given type into an array with maximum allowed size of elements.
6487 static ABIArgInfo coerceToIntArrayWithLimit(QualType Ty, ASTContext &Context,
6488 llvm::LLVMContext &LLVMContext,
6490 // Alignment and Size are measured in bits.
6491 const uint64_t Size = Context.getTypeSize(Ty);
6492 const uint64_t Alignment = Context.getTypeAlign(Ty);
6493 const unsigned Div = std::min<unsigned>(MaxSize, Alignment);
6494 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Div);
6495 const uint64_t NumElements = (Size + Div - 1) / Div;
6496 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
6499 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6500 if (RetTy->isVoidType())
6501 return ABIArgInfo::getIgnore();
6503 if (getContext().getLangOpts().OpenMP &&
6504 getContext().getLangOpts().OpenMPIsDevice &&
6505 isUnsupportedType(getContext(), RetTy))
6506 return coerceToIntArrayWithLimit(RetTy, getContext(), getVMContext(), 64);
6508 // note: this is different from default ABI
6509 if (!RetTy->isScalarType())
6510 return ABIArgInfo::getDirect();
6512 // Treat an enum type as its underlying type.
6513 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6514 RetTy = EnumTy->getDecl()->getIntegerType();
6516 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6517 : ABIArgInfo::getDirect());
6520 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6521 // Treat an enum type as its underlying type.
6522 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6523 Ty = EnumTy->getDecl()->getIntegerType();
6525 // Return aggregates type as indirect by value
6526 if (isAggregateTypeForABI(Ty))
6527 return getNaturalAlignIndirect(Ty, /* byval */ true);
6529 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6530 : ABIArgInfo::getDirect());
6533 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6534 if (!getCXXABI().classifyReturnType(FI))
6535 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6536 for (auto &I : FI.arguments())
6537 I.info = classifyArgumentType(I.type);
6539 // Always honor user-specified calling convention.
6540 if (FI.getCallingConvention() != llvm::CallingConv::C)
6543 FI.setEffectiveCallingConvention(getRuntimeCC());
6546 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6547 QualType Ty) const {
6548 llvm_unreachable("NVPTX does not support varargs");
6551 void NVPTXTargetCodeGenInfo::setTargetAttributes(
6552 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6553 if (GV->isDeclaration())
6555 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6558 llvm::Function *F = cast<llvm::Function>(GV);
6560 // Perform special handling in OpenCL mode
6561 if (M.getLangOpts().OpenCL) {
6562 // Use OpenCL function attributes to check for kernel functions
6563 // By default, all functions are device functions
6564 if (FD->hasAttr<OpenCLKernelAttr>()) {
6565 // OpenCL __kernel functions get kernel metadata
6566 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6567 addNVVMMetadata(F, "kernel", 1);
6568 // And kernel functions are not subject to inlining
6569 F->addFnAttr(llvm::Attribute::NoInline);
6573 // Perform special handling in CUDA mode.
6574 if (M.getLangOpts().CUDA) {
6575 // CUDA __global__ functions get a kernel metadata entry. Since
6576 // __global__ functions cannot be called from the device, we do not
6577 // need to set the noinline attribute.
6578 if (FD->hasAttr<CUDAGlobalAttr>()) {
6579 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6580 addNVVMMetadata(F, "kernel", 1);
6582 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6583 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6584 llvm::APSInt MaxThreads(32);
6585 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6587 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6589 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6590 // not specified in __launch_bounds__ or if the user specified a 0 value,
6591 // we don't have to add a PTX directive.
6592 if (Attr->getMinBlocks()) {
6593 llvm::APSInt MinBlocks(32);
6594 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6596 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6597 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6603 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6605 llvm::Module *M = F->getParent();
6606 llvm::LLVMContext &Ctx = M->getContext();
6608 // Get "nvvm.annotations" metadata node
6609 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6611 llvm::Metadata *MDVals[] = {
6612 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6613 llvm::ConstantAsMetadata::get(
6614 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6615 // Append metadata to nvvm.annotations
6616 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6619 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6624 //===----------------------------------------------------------------------===//
6625 // SystemZ ABI Implementation
6626 //===----------------------------------------------------------------------===//
6630 class SystemZABIInfo : public SwiftABIInfo {
6634 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6635 : SwiftABIInfo(CGT), HasVector(HV) {}
6637 bool isPromotableIntegerType(QualType Ty) const;
6638 bool isCompoundType(QualType Ty) const;
6639 bool isVectorArgumentType(QualType Ty) const;
6640 bool isFPArgumentType(QualType Ty) const;
6641 QualType GetSingleElementType(QualType Ty) const;
6643 ABIArgInfo classifyReturnType(QualType RetTy) const;
6644 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6646 void computeInfo(CGFunctionInfo &FI) const override {
6647 if (!getCXXABI().classifyReturnType(FI))
6648 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6649 for (auto &I : FI.arguments())
6650 I.info = classifyArgumentType(I.type);
6653 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6654 QualType Ty) const override;
6656 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6657 bool asReturnValue) const override {
6658 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6660 bool isSwiftErrorInRegister() const override {
6665 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6667 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6668 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6673 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6674 // Treat an enum type as its underlying type.
6675 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6676 Ty = EnumTy->getDecl()->getIntegerType();
6678 // Promotable integer types are required to be promoted by the ABI.
6679 if (Ty->isPromotableIntegerType())
6682 // 32-bit values must also be promoted.
6683 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6684 switch (BT->getKind()) {
6685 case BuiltinType::Int:
6686 case BuiltinType::UInt:
6694 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6695 return (Ty->isAnyComplexType() ||
6696 Ty->isVectorType() ||
6697 isAggregateTypeForABI(Ty));
6700 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6701 return (HasVector &&
6702 Ty->isVectorType() &&
6703 getContext().getTypeSize(Ty) <= 128);
6706 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6707 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6708 switch (BT->getKind()) {
6709 case BuiltinType::Float:
6710 case BuiltinType::Double:
6719 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6720 if (const RecordType *RT = Ty->getAsStructureType()) {
6721 const RecordDecl *RD = RT->getDecl();
6724 // If this is a C++ record, check the bases first.
6725 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6726 for (const auto &I : CXXRD->bases()) {
6727 QualType Base = I.getType();
6729 // Empty bases don't affect things either way.
6730 if (isEmptyRecord(getContext(), Base, true))
6733 if (!Found.isNull())
6735 Found = GetSingleElementType(Base);
6738 // Check the fields.
6739 for (const auto *FD : RD->fields()) {
6740 // For compatibility with GCC, ignore empty bitfields in C++ mode.
6741 // Unlike isSingleElementStruct(), empty structure and array fields
6742 // do count. So do anonymous bitfields that aren't zero-sized.
6743 if (getContext().getLangOpts().CPlusPlus &&
6744 FD->isZeroLengthBitField(getContext()))
6747 // Unlike isSingleElementStruct(), arrays do not count.
6748 // Nested structures still do though.
6749 if (!Found.isNull())
6751 Found = GetSingleElementType(FD->getType());
6754 // Unlike isSingleElementStruct(), trailing padding is allowed.
6755 // An 8-byte aligned struct s { float f; } is passed as a double.
6756 if (!Found.isNull())
6763 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6764 QualType Ty) const {
6765 // Assume that va_list type is correct; should be pointer to LLVM type:
6769 // i8 *__overflow_arg_area;
6770 // i8 *__reg_save_area;
6773 // Every non-vector argument occupies 8 bytes and is passed by preference
6774 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6775 // always passed on the stack.
6776 Ty = getContext().getCanonicalType(Ty);
6777 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6778 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6779 llvm::Type *DirectTy = ArgTy;
6780 ABIArgInfo AI = classifyArgumentType(Ty);
6781 bool IsIndirect = AI.isIndirect();
6782 bool InFPRs = false;
6783 bool IsVector = false;
6784 CharUnits UnpaddedSize;
6785 CharUnits DirectAlign;
6787 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6788 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6790 if (AI.getCoerceToType())
6791 ArgTy = AI.getCoerceToType();
6792 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6793 IsVector = ArgTy->isVectorTy();
6794 UnpaddedSize = TyInfo.first;
6795 DirectAlign = TyInfo.second;
6797 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6798 if (IsVector && UnpaddedSize > PaddedSize)
6799 PaddedSize = CharUnits::fromQuantity(16);
6800 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6802 CharUnits Padding = (PaddedSize - UnpaddedSize);
6804 llvm::Type *IndexTy = CGF.Int64Ty;
6805 llvm::Value *PaddedSizeV =
6806 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6809 // Work out the address of a vector argument on the stack.
6810 // Vector arguments are always passed in the high bits of a
6811 // single (8 byte) or double (16 byte) stack slot.
6812 Address OverflowArgAreaPtr =
6813 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
6814 Address OverflowArgArea =
6815 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6818 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6820 // Update overflow_arg_area_ptr pointer
6821 llvm::Value *NewOverflowArgArea =
6822 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6823 "overflow_arg_area");
6824 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6829 assert(PaddedSize.getQuantity() == 8);
6831 unsigned MaxRegs, RegCountField, RegSaveIndex;
6832 CharUnits RegPadding;
6834 MaxRegs = 4; // Maximum of 4 FPR arguments
6835 RegCountField = 1; // __fpr
6836 RegSaveIndex = 16; // save offset for f0
6837 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6839 MaxRegs = 5; // Maximum of 5 GPR arguments
6840 RegCountField = 0; // __gpr
6841 RegSaveIndex = 2; // save offset for r2
6842 RegPadding = Padding; // values are passed in the low bits of a GPR
6845 Address RegCountPtr =
6846 CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
6847 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6848 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6849 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6852 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6853 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6854 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6855 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6857 // Emit code to load the value if it was passed in registers.
6858 CGF.EmitBlock(InRegBlock);
6860 // Work out the address of an argument register.
6861 llvm::Value *ScaledRegCount =
6862 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6863 llvm::Value *RegBase =
6864 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6865 + RegPadding.getQuantity());
6866 llvm::Value *RegOffset =
6867 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6868 Address RegSaveAreaPtr =
6869 CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
6870 llvm::Value *RegSaveArea =
6871 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6872 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6876 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6878 // Update the register count
6879 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6880 llvm::Value *NewRegCount =
6881 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6882 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6883 CGF.EmitBranch(ContBlock);
6885 // Emit code to load the value if it was passed in memory.
6886 CGF.EmitBlock(InMemBlock);
6888 // Work out the address of a stack argument.
6889 Address OverflowArgAreaPtr =
6890 CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
6891 Address OverflowArgArea =
6892 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6894 Address RawMemAddr =
6895 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6897 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6899 // Update overflow_arg_area_ptr pointer
6900 llvm::Value *NewOverflowArgArea =
6901 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6902 "overflow_arg_area");
6903 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6904 CGF.EmitBranch(ContBlock);
6906 // Return the appropriate result.
6907 CGF.EmitBlock(ContBlock);
6908 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6909 MemAddr, InMemBlock, "va_arg.addr");
6912 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6918 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6919 if (RetTy->isVoidType())
6920 return ABIArgInfo::getIgnore();
6921 if (isVectorArgumentType(RetTy))
6922 return ABIArgInfo::getDirect();
6923 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6924 return getNaturalAlignIndirect(RetTy);
6925 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6926 : ABIArgInfo::getDirect());
6929 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6930 // Handle the generic C++ ABI.
6931 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6932 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6934 // Integers and enums are extended to full register width.
6935 if (isPromotableIntegerType(Ty))
6936 return ABIArgInfo::getExtend(Ty);
6938 // Handle vector types and vector-like structure types. Note that
6939 // as opposed to float-like structure types, we do not allow any
6940 // padding for vector-like structures, so verify the sizes match.
6941 uint64_t Size = getContext().getTypeSize(Ty);
6942 QualType SingleElementTy = GetSingleElementType(Ty);
6943 if (isVectorArgumentType(SingleElementTy) &&
6944 getContext().getTypeSize(SingleElementTy) == Size)
6945 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6947 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6948 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6949 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6951 // Handle small structures.
6952 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6953 // Structures with flexible arrays have variable length, so really
6954 // fail the size test above.
6955 const RecordDecl *RD = RT->getDecl();
6956 if (RD->hasFlexibleArrayMember())
6957 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6959 // The structure is passed as an unextended integer, a float, or a double.
6961 if (isFPArgumentType(SingleElementTy)) {
6962 assert(Size == 32 || Size == 64);
6964 PassTy = llvm::Type::getFloatTy(getVMContext());
6966 PassTy = llvm::Type::getDoubleTy(getVMContext());
6968 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6969 return ABIArgInfo::getDirect(PassTy);
6972 // Non-structure compounds are passed indirectly.
6973 if (isCompoundType(Ty))
6974 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6976 return ABIArgInfo::getDirect(nullptr);
6979 //===----------------------------------------------------------------------===//
6980 // MSP430 ABI Implementation
6981 //===----------------------------------------------------------------------===//
6985 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6987 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6988 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6989 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6990 CodeGen::CodeGenModule &M) const override;
6995 void MSP430TargetCodeGenInfo::setTargetAttributes(
6996 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6997 if (GV->isDeclaration())
6999 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
7000 const auto *InterruptAttr = FD->getAttr<MSP430InterruptAttr>();
7004 // Handle 'interrupt' attribute:
7005 llvm::Function *F = cast<llvm::Function>(GV);
7007 // Step 1: Set ISR calling convention.
7008 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
7010 // Step 2: Add attributes goodness.
7011 F->addFnAttr(llvm::Attribute::NoInline);
7012 F->addFnAttr("interrupt", llvm::utostr(InterruptAttr->getNumber()));
7016 //===----------------------------------------------------------------------===//
7017 // MIPS ABI Implementation. This works for both little-endian and
7018 // big-endian variants.
7019 //===----------------------------------------------------------------------===//
7022 class MipsABIInfo : public ABIInfo {
7024 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
7025 void CoerceToIntArgs(uint64_t TySize,
7026 SmallVectorImpl<llvm::Type *> &ArgList) const;
7027 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
7028 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
7029 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
7031 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
7032 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
7033 StackAlignInBytes(IsO32 ? 8 : 16) {}
7035 ABIArgInfo classifyReturnType(QualType RetTy) const;
7036 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
7037 void computeInfo(CGFunctionInfo &FI) const override;
7038 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7039 QualType Ty) const override;
7040 ABIArgInfo extendType(QualType Ty) const;
7043 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
7044 unsigned SizeOfUnwindException;
7046 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
7047 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
7048 SizeOfUnwindException(IsO32 ? 24 : 32) {}
7050 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
7054 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7055 CodeGen::CodeGenModule &CGM) const override {
7056 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7058 llvm::Function *Fn = cast<llvm::Function>(GV);
7060 if (FD->hasAttr<MipsLongCallAttr>())
7061 Fn->addFnAttr("long-call");
7062 else if (FD->hasAttr<MipsShortCallAttr>())
7063 Fn->addFnAttr("short-call");
7065 // Other attributes do not have a meaning for declarations.
7066 if (GV->isDeclaration())
7069 if (FD->hasAttr<Mips16Attr>()) {
7070 Fn->addFnAttr("mips16");
7072 else if (FD->hasAttr<NoMips16Attr>()) {
7073 Fn->addFnAttr("nomips16");
7076 if (FD->hasAttr<MicroMipsAttr>())
7077 Fn->addFnAttr("micromips");
7078 else if (FD->hasAttr<NoMicroMipsAttr>())
7079 Fn->addFnAttr("nomicromips");
7081 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
7086 switch (Attr->getInterrupt()) {
7087 case MipsInterruptAttr::eic: Kind = "eic"; break;
7088 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
7089 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
7090 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
7091 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
7092 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
7093 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
7094 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
7095 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
7098 Fn->addFnAttr("interrupt", Kind);
7102 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7103 llvm::Value *Address) const override;
7105 unsigned getSizeOfUnwindException() const override {
7106 return SizeOfUnwindException;
7111 void MipsABIInfo::CoerceToIntArgs(
7112 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
7113 llvm::IntegerType *IntTy =
7114 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
7116 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
7117 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
7118 ArgList.push_back(IntTy);
7120 // If necessary, add one more integer type to ArgList.
7121 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
7124 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
7127 // In N32/64, an aligned double precision floating point field is passed in
7129 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
7130 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
7133 CoerceToIntArgs(TySize, ArgList);
7134 return llvm::StructType::get(getVMContext(), ArgList);
7137 if (Ty->isComplexType())
7138 return CGT.ConvertType(Ty);
7140 const RecordType *RT = Ty->getAs<RecordType>();
7142 // Unions/vectors are passed in integer registers.
7143 if (!RT || !RT->isStructureOrClassType()) {
7144 CoerceToIntArgs(TySize, ArgList);
7145 return llvm::StructType::get(getVMContext(), ArgList);
7148 const RecordDecl *RD = RT->getDecl();
7149 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7150 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
7152 uint64_t LastOffset = 0;
7154 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
7156 // Iterate over fields in the struct/class and check if there are any aligned
7158 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
7159 i != e; ++i, ++idx) {
7160 const QualType Ty = i->getType();
7161 const BuiltinType *BT = Ty->getAs<BuiltinType>();
7163 if (!BT || BT->getKind() != BuiltinType::Double)
7166 uint64_t Offset = Layout.getFieldOffset(idx);
7167 if (Offset % 64) // Ignore doubles that are not aligned.
7170 // Add ((Offset - LastOffset) / 64) args of type i64.
7171 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
7172 ArgList.push_back(I64);
7175 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
7176 LastOffset = Offset + 64;
7179 CoerceToIntArgs(TySize - LastOffset, IntArgList);
7180 ArgList.append(IntArgList.begin(), IntArgList.end());
7182 return llvm::StructType::get(getVMContext(), ArgList);
7185 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
7186 uint64_t Offset) const {
7187 if (OrigOffset + MinABIStackAlignInBytes > Offset)
7190 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
7194 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
7195 Ty = useFirstFieldIfTransparentUnion(Ty);
7197 uint64_t OrigOffset = Offset;
7198 uint64_t TySize = getContext().getTypeSize(Ty);
7199 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
7201 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
7202 (uint64_t)StackAlignInBytes);
7203 unsigned CurrOffset = llvm::alignTo(Offset, Align);
7204 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
7206 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
7207 // Ignore empty aggregates.
7209 return ABIArgInfo::getIgnore();
7211 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
7212 Offset = OrigOffset + MinABIStackAlignInBytes;
7213 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7216 // If we have reached here, aggregates are passed directly by coercing to
7217 // another structure type. Padding is inserted if the offset of the
7218 // aggregate is unaligned.
7219 ABIArgInfo ArgInfo =
7220 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
7221 getPaddingType(OrigOffset, CurrOffset));
7222 ArgInfo.setInReg(true);
7226 // Treat an enum type as its underlying type.
7227 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7228 Ty = EnumTy->getDecl()->getIntegerType();
7230 // All integral types are promoted to the GPR width.
7231 if (Ty->isIntegralOrEnumerationType())
7232 return extendType(Ty);
7234 return ABIArgInfo::getDirect(
7235 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
7239 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
7240 const RecordType *RT = RetTy->getAs<RecordType>();
7241 SmallVector<llvm::Type*, 8> RTList;
7243 if (RT && RT->isStructureOrClassType()) {
7244 const RecordDecl *RD = RT->getDecl();
7245 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
7246 unsigned FieldCnt = Layout.getFieldCount();
7248 // N32/64 returns struct/classes in floating point registers if the
7249 // following conditions are met:
7250 // 1. The size of the struct/class is no larger than 128-bit.
7251 // 2. The struct/class has one or two fields all of which are floating
7253 // 3. The offset of the first field is zero (this follows what gcc does).
7255 // Any other composite results are returned in integer registers.
7257 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
7258 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
7259 for (; b != e; ++b) {
7260 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
7262 if (!BT || !BT->isFloatingPoint())
7265 RTList.push_back(CGT.ConvertType(b->getType()));
7269 return llvm::StructType::get(getVMContext(), RTList,
7270 RD->hasAttr<PackedAttr>());
7276 CoerceToIntArgs(Size, RTList);
7277 return llvm::StructType::get(getVMContext(), RTList);
7280 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
7281 uint64_t Size = getContext().getTypeSize(RetTy);
7283 if (RetTy->isVoidType())
7284 return ABIArgInfo::getIgnore();
7286 // O32 doesn't treat zero-sized structs differently from other structs.
7287 // However, N32/N64 ignores zero sized return values.
7288 if (!IsO32 && Size == 0)
7289 return ABIArgInfo::getIgnore();
7291 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
7293 if (RetTy->isAnyComplexType())
7294 return ABIArgInfo::getDirect();
7296 // O32 returns integer vectors in registers and N32/N64 returns all small
7297 // aggregates in registers.
7299 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
7300 ABIArgInfo ArgInfo =
7301 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
7302 ArgInfo.setInReg(true);
7307 return getNaturalAlignIndirect(RetTy);
7310 // Treat an enum type as its underlying type.
7311 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7312 RetTy = EnumTy->getDecl()->getIntegerType();
7314 if (RetTy->isPromotableIntegerType())
7315 return ABIArgInfo::getExtend(RetTy);
7317 if ((RetTy->isUnsignedIntegerOrEnumerationType() ||
7318 RetTy->isSignedIntegerOrEnumerationType()) && Size == 32 && !IsO32)
7319 return ABIArgInfo::getSignExtend(RetTy);
7321 return ABIArgInfo::getDirect();
7324 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
7325 ABIArgInfo &RetInfo = FI.getReturnInfo();
7326 if (!getCXXABI().classifyReturnType(FI))
7327 RetInfo = classifyReturnType(FI.getReturnType());
7329 // Check if a pointer to an aggregate is passed as a hidden argument.
7330 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7332 for (auto &I : FI.arguments())
7333 I.info = classifyArgumentType(I.type, Offset);
7336 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7337 QualType OrigTy) const {
7338 QualType Ty = OrigTy;
7340 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7341 // Pointers are also promoted in the same way but this only matters for N32.
7342 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7343 unsigned PtrWidth = getTarget().getPointerWidth(0);
7344 bool DidPromote = false;
7345 if ((Ty->isIntegerType() &&
7346 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7347 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7349 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7350 Ty->isSignedIntegerType());
7353 auto TyInfo = getContext().getTypeInfoInChars(Ty);
7355 // The alignment of things in the argument area is never larger than
7356 // StackAlignInBytes.
7358 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7360 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7361 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7363 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7364 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7367 // If there was a promotion, "unpromote" into a temporary.
7368 // TODO: can we just use a pointer into a subset of the original slot?
7370 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7371 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7373 // Truncate down to the right width.
7374 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7376 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7377 if (OrigTy->isPointerType())
7378 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7380 CGF.Builder.CreateStore(V, Temp);
7387 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
7388 int TySize = getContext().getTypeSize(Ty);
7390 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7391 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7392 return ABIArgInfo::getSignExtend(Ty);
7394 return ABIArgInfo::getExtend(Ty);
7398 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7399 llvm::Value *Address) const {
7400 // This information comes from gcc's implementation, which seems to
7401 // as canonical as it gets.
7403 // Everything on MIPS is 4 bytes. Double-precision FP registers
7404 // are aliased to pairs of single-precision FP registers.
7405 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
7407 // 0-31 are the general purpose registers, $0 - $31.
7408 // 32-63 are the floating-point registers, $f0 - $f31.
7409 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7410 // 66 is the (notional, I think) register for signal-handler return.
7411 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
7413 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7414 // They are one bit wide and ignored here.
7416 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7417 // (coprocessor 1 is the FP unit)
7418 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7419 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7420 // 176-181 are the DSP accumulator registers.
7421 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
7425 //===----------------------------------------------------------------------===//
7426 // AVR ABI Implementation.
7427 //===----------------------------------------------------------------------===//
7430 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7432 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7433 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7435 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7436 CodeGen::CodeGenModule &CGM) const override {
7437 if (GV->isDeclaration())
7439 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7441 auto *Fn = cast<llvm::Function>(GV);
7443 if (FD->getAttr<AVRInterruptAttr>())
7444 Fn->addFnAttr("interrupt");
7446 if (FD->getAttr<AVRSignalAttr>())
7447 Fn->addFnAttr("signal");
7452 //===----------------------------------------------------------------------===//
7453 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
7454 // Currently subclassed only to implement custom OpenCL C function attribute
7456 //===----------------------------------------------------------------------===//
7460 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7462 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7463 : DefaultTargetCodeGenInfo(CGT) {}
7465 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7466 CodeGen::CodeGenModule &M) const override;
7469 void TCETargetCodeGenInfo::setTargetAttributes(
7470 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7471 if (GV->isDeclaration())
7473 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7476 llvm::Function *F = cast<llvm::Function>(GV);
7478 if (M.getLangOpts().OpenCL) {
7479 if (FD->hasAttr<OpenCLKernelAttr>()) {
7480 // OpenCL C Kernel functions are not subject to inlining
7481 F->addFnAttr(llvm::Attribute::NoInline);
7482 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7484 // Convert the reqd_work_group_size() attributes to metadata.
7485 llvm::LLVMContext &Context = F->getContext();
7486 llvm::NamedMDNode *OpenCLMetadata =
7487 M.getModule().getOrInsertNamedMetadata(
7488 "opencl.kernel_wg_size_info");
7490 SmallVector<llvm::Metadata *, 5> Operands;
7491 Operands.push_back(llvm::ConstantAsMetadata::get(F));
7494 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7495 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7497 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7498 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7500 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7501 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7503 // Add a boolean constant operand for "required" (true) or "hint"
7504 // (false) for implementing the work_group_size_hint attr later.
7505 // Currently always true as the hint is not yet implemented.
7507 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7508 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7516 //===----------------------------------------------------------------------===//
7517 // Hexagon ABI Implementation
7518 //===----------------------------------------------------------------------===//
7522 class HexagonABIInfo : public ABIInfo {
7526 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7530 ABIArgInfo classifyReturnType(QualType RetTy) const;
7531 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7533 void computeInfo(CGFunctionInfo &FI) const override;
7535 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7536 QualType Ty) const override;
7539 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7541 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7542 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7544 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7551 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7552 if (!getCXXABI().classifyReturnType(FI))
7553 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7554 for (auto &I : FI.arguments())
7555 I.info = classifyArgumentType(I.type);
7558 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7559 if (!isAggregateTypeForABI(Ty)) {
7560 // Treat an enum type as its underlying type.
7561 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7562 Ty = EnumTy->getDecl()->getIntegerType();
7564 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7565 : ABIArgInfo::getDirect());
7568 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7569 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7571 // Ignore empty records.
7572 if (isEmptyRecord(getContext(), Ty, true))
7573 return ABIArgInfo::getIgnore();
7575 uint64_t Size = getContext().getTypeSize(Ty);
7577 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7578 // Pass in the smallest viable integer type.
7580 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7582 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7584 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7586 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7589 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7590 if (RetTy->isVoidType())
7591 return ABIArgInfo::getIgnore();
7593 // Large vector types should be returned via memory.
7594 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7595 return getNaturalAlignIndirect(RetTy);
7597 if (!isAggregateTypeForABI(RetTy)) {
7598 // Treat an enum type as its underlying type.
7599 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7600 RetTy = EnumTy->getDecl()->getIntegerType();
7602 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7603 : ABIArgInfo::getDirect());
7606 if (isEmptyRecord(getContext(), RetTy, true))
7607 return ABIArgInfo::getIgnore();
7609 // Aggregates <= 8 bytes are returned in r0; other aggregates
7610 // are returned indirectly.
7611 uint64_t Size = getContext().getTypeSize(RetTy);
7613 // Return in the smallest viable integer type.
7615 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7617 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7619 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7620 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7623 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7626 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7627 QualType Ty) const {
7628 // FIXME: Someone needs to audit that this handle alignment correctly.
7629 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7630 getContext().getTypeInfoInChars(Ty),
7631 CharUnits::fromQuantity(4),
7632 /*AllowHigherAlign*/ true);
7635 //===----------------------------------------------------------------------===//
7636 // Lanai ABI Implementation
7637 //===----------------------------------------------------------------------===//
7640 class LanaiABIInfo : public DefaultABIInfo {
7642 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7644 bool shouldUseInReg(QualType Ty, CCState &State) const;
7646 void computeInfo(CGFunctionInfo &FI) const override {
7648 // Lanai uses 4 registers to pass arguments unless the function has the
7649 // regparm attribute set.
7650 if (FI.getHasRegParm()) {
7651 State.FreeRegs = FI.getRegParm();
7656 if (!getCXXABI().classifyReturnType(FI))
7657 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7658 for (auto &I : FI.arguments())
7659 I.info = classifyArgumentType(I.type, State);
7662 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7663 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7665 } // end anonymous namespace
7667 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7668 unsigned Size = getContext().getTypeSize(Ty);
7669 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7671 if (SizeInRegs == 0)
7674 if (SizeInRegs > State.FreeRegs) {
7679 State.FreeRegs -= SizeInRegs;
7684 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7685 CCState &State) const {
7687 if (State.FreeRegs) {
7688 --State.FreeRegs; // Non-byval indirects just use one pointer.
7689 return getNaturalAlignIndirectInReg(Ty);
7691 return getNaturalAlignIndirect(Ty, false);
7694 // Compute the byval alignment.
7695 const unsigned MinABIStackAlignInBytes = 4;
7696 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7697 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7698 /*Realign=*/TypeAlign >
7699 MinABIStackAlignInBytes);
7702 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7703 CCState &State) const {
7704 // Check with the C++ ABI first.
7705 const RecordType *RT = Ty->getAs<RecordType>();
7707 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7708 if (RAA == CGCXXABI::RAA_Indirect) {
7709 return getIndirectResult(Ty, /*ByVal=*/false, State);
7710 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7711 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7715 if (isAggregateTypeForABI(Ty)) {
7716 // Structures with flexible arrays are always indirect.
7717 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7718 return getIndirectResult(Ty, /*ByVal=*/true, State);
7720 // Ignore empty structs/unions.
7721 if (isEmptyRecord(getContext(), Ty, true))
7722 return ABIArgInfo::getIgnore();
7724 llvm::LLVMContext &LLVMContext = getVMContext();
7725 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7726 if (SizeInRegs <= State.FreeRegs) {
7727 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7728 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7729 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7730 State.FreeRegs -= SizeInRegs;
7731 return ABIArgInfo::getDirectInReg(Result);
7735 return getIndirectResult(Ty, true, State);
7738 // Treat an enum type as its underlying type.
7739 if (const auto *EnumTy = Ty->getAs<EnumType>())
7740 Ty = EnumTy->getDecl()->getIntegerType();
7742 bool InReg = shouldUseInReg(Ty, State);
7743 if (Ty->isPromotableIntegerType()) {
7745 return ABIArgInfo::getDirectInReg();
7746 return ABIArgInfo::getExtend(Ty);
7749 return ABIArgInfo::getDirectInReg();
7750 return ABIArgInfo::getDirect();
7754 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7756 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7757 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7761 //===----------------------------------------------------------------------===//
7762 // AMDGPU ABI Implementation
7763 //===----------------------------------------------------------------------===//
7767 class AMDGPUABIInfo final : public DefaultABIInfo {
7769 static const unsigned MaxNumRegsForArgsRet = 16;
7771 unsigned numRegsForType(QualType Ty) const;
7773 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7774 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7775 uint64_t Members) const override;
7777 // Coerce HIP pointer arguments from generic pointers to global ones.
7778 llvm::Type *coerceKernelArgumentType(llvm::Type *Ty, unsigned FromAS,
7779 unsigned ToAS) const {
7781 if (auto STy = dyn_cast<llvm::StructType>(Ty)) {
7782 SmallVector<llvm::Type *, 8> EltTys;
7783 bool Changed = false;
7784 for (auto T : STy->elements()) {
7785 auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
7786 EltTys.push_back(NT);
7787 Changed |= (NT != T);
7789 // Skip if there is no change in element types.
7793 return llvm::StructType::create(
7794 EltTys, (STy->getName() + ".coerce").str(), STy->isPacked());
7795 return llvm::StructType::get(getVMContext(), EltTys, STy->isPacked());
7798 if (auto ATy = dyn_cast<llvm::ArrayType>(Ty)) {
7799 auto T = ATy->getElementType();
7800 auto NT = coerceKernelArgumentType(T, FromAS, ToAS);
7801 // Skip if there is no change in that element type.
7804 return llvm::ArrayType::get(NT, ATy->getNumElements());
7806 // Single value types.
7807 if (Ty->isPointerTy() && Ty->getPointerAddressSpace() == FromAS)
7808 return llvm::PointerType::get(
7809 cast<llvm::PointerType>(Ty)->getElementType(), ToAS);
7814 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7815 DefaultABIInfo(CGT) {}
7817 ABIArgInfo classifyReturnType(QualType RetTy) const;
7818 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7819 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
7821 void computeInfo(CGFunctionInfo &FI) const override;
7822 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7823 QualType Ty) const override;
7826 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7830 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7831 const Type *Base, uint64_t Members) const {
7832 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7834 // Homogeneous Aggregates may occupy at most 16 registers.
7835 return Members * NumRegs <= MaxNumRegsForArgsRet;
7838 /// Estimate number of registers the type will use when passed in registers.
7839 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7840 unsigned NumRegs = 0;
7842 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7843 // Compute from the number of elements. The reported size is based on the
7844 // in-memory size, which includes the padding 4th element for 3-vectors.
7845 QualType EltTy = VT->getElementType();
7846 unsigned EltSize = getContext().getTypeSize(EltTy);
7848 // 16-bit element vectors should be passed as packed.
7850 return (VT->getNumElements() + 1) / 2;
7852 unsigned EltNumRegs = (EltSize + 31) / 32;
7853 return EltNumRegs * VT->getNumElements();
7856 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7857 const RecordDecl *RD = RT->getDecl();
7858 assert(!RD->hasFlexibleArrayMember());
7860 for (const FieldDecl *Field : RD->fields()) {
7861 QualType FieldTy = Field->getType();
7862 NumRegs += numRegsForType(FieldTy);
7868 return (getContext().getTypeSize(Ty) + 31) / 32;
7871 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7872 llvm::CallingConv::ID CC = FI.getCallingConvention();
7874 if (!getCXXABI().classifyReturnType(FI))
7875 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7877 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7878 for (auto &Arg : FI.arguments()) {
7879 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7880 Arg.info = classifyKernelArgumentType(Arg.type);
7882 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7887 Address AMDGPUABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7888 QualType Ty) const {
7889 llvm_unreachable("AMDGPU does not support varargs");
7892 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7893 if (isAggregateTypeForABI(RetTy)) {
7894 // Records with non-trivial destructors/copy-constructors should not be
7895 // returned by value.
7896 if (!getRecordArgABI(RetTy, getCXXABI())) {
7897 // Ignore empty structs/unions.
7898 if (isEmptyRecord(getContext(), RetTy, true))
7899 return ABIArgInfo::getIgnore();
7901 // Lower single-element structs to just return a regular value.
7902 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7903 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7905 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7906 const RecordDecl *RD = RT->getDecl();
7907 if (RD->hasFlexibleArrayMember())
7908 return DefaultABIInfo::classifyReturnType(RetTy);
7911 // Pack aggregates <= 4 bytes into single VGPR or pair.
7912 uint64_t Size = getContext().getTypeSize(RetTy);
7914 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7917 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7920 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7921 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7924 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7925 return ABIArgInfo::getDirect();
7929 // Otherwise just do the default thing.
7930 return DefaultABIInfo::classifyReturnType(RetTy);
7933 /// For kernels all parameters are really passed in a special buffer. It doesn't
7934 /// make sense to pass anything byval, so everything must be direct.
7935 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7936 Ty = useFirstFieldIfTransparentUnion(Ty);
7938 // TODO: Can we omit empty structs?
7940 llvm::Type *LTy = nullptr;
7941 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7942 LTy = CGT.ConvertType(QualType(SeltTy, 0));
7944 if (getContext().getLangOpts().HIP) {
7946 LTy = CGT.ConvertType(Ty);
7947 LTy = coerceKernelArgumentType(
7948 LTy, /*FromAS=*/getContext().getTargetAddressSpace(LangAS::Default),
7949 /*ToAS=*/getContext().getTargetAddressSpace(LangAS::cuda_device));
7952 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7953 // individual elements, which confuses the Clover OpenCL backend; therefore we
7954 // have to set it to false here. Other args of getDirect() are just defaults.
7955 return ABIArgInfo::getDirect(LTy, 0, nullptr, false);
7958 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7959 unsigned &NumRegsLeft) const {
7960 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7962 Ty = useFirstFieldIfTransparentUnion(Ty);
7964 if (isAggregateTypeForABI(Ty)) {
7965 // Records with non-trivial destructors/copy-constructors should not be
7967 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7968 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7970 // Ignore empty structs/unions.
7971 if (isEmptyRecord(getContext(), Ty, true))
7972 return ABIArgInfo::getIgnore();
7974 // Lower single-element structs to just pass a regular value. TODO: We
7975 // could do reasonable-size multiple-element structs too, using getExpand(),
7976 // though watch out for things like bitfields.
7977 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7978 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7980 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7981 const RecordDecl *RD = RT->getDecl();
7982 if (RD->hasFlexibleArrayMember())
7983 return DefaultABIInfo::classifyArgumentType(Ty);
7986 // Pack aggregates <= 8 bytes into single VGPR or pair.
7987 uint64_t Size = getContext().getTypeSize(Ty);
7989 unsigned NumRegs = (Size + 31) / 32;
7990 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7993 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7996 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7998 // XXX: Should this be i64 instead, and should the limit increase?
7999 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
8000 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
8003 if (NumRegsLeft > 0) {
8004 unsigned NumRegs = numRegsForType(Ty);
8005 if (NumRegsLeft >= NumRegs) {
8006 NumRegsLeft -= NumRegs;
8007 return ABIArgInfo::getDirect();
8012 // Otherwise just do the default thing.
8013 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
8014 if (!ArgInfo.isIndirect()) {
8015 unsigned NumRegs = numRegsForType(Ty);
8016 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
8022 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
8024 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
8025 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
8026 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8027 CodeGen::CodeGenModule &M) const override;
8028 unsigned getOpenCLKernelCallingConv() const override;
8030 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
8031 llvm::PointerType *T, QualType QT) const override;
8033 LangAS getASTAllocaAddressSpace() const override {
8034 return getLangASFromTargetAS(
8035 getABIInfo().getDataLayout().getAllocaAddrSpace());
8037 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
8038 const VarDecl *D) const override;
8039 llvm::SyncScope::ID getLLVMSyncScopeID(const LangOptions &LangOpts,
8041 llvm::AtomicOrdering Ordering,
8042 llvm::LLVMContext &Ctx) const override;
8044 createEnqueuedBlockKernel(CodeGenFunction &CGF,
8045 llvm::Function *BlockInvokeFunc,
8046 llvm::Value *BlockLiteral) const override;
8047 bool shouldEmitStaticExternCAliases() const override;
8048 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
8052 static bool requiresAMDGPUProtectedVisibility(const Decl *D,
8053 llvm::GlobalValue *GV) {
8054 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8057 return D->hasAttr<OpenCLKernelAttr>() ||
8058 (isa<FunctionDecl>(D) && D->hasAttr<CUDAGlobalAttr>()) ||
8060 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
8061 D->hasAttr<HIPPinnedShadowAttr>()));
8064 static bool requiresAMDGPUDefaultVisibility(const Decl *D,
8065 llvm::GlobalValue *GV) {
8066 if (GV->getVisibility() != llvm::GlobalValue::HiddenVisibility)
8069 return isa<VarDecl>(D) && D->hasAttr<HIPPinnedShadowAttr>();
8072 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
8073 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
8074 if (requiresAMDGPUDefaultVisibility(D, GV)) {
8075 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
8076 GV->setDSOLocal(false);
8077 } else if (requiresAMDGPUProtectedVisibility(D, GV)) {
8078 GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
8079 GV->setDSOLocal(true);
8082 if (GV->isDeclaration())
8084 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
8088 llvm::Function *F = cast<llvm::Function>(GV);
8090 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
8091 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
8094 const bool IsOpenCLKernel = M.getLangOpts().OpenCL &&
8095 FD->hasAttr<OpenCLKernelAttr>();
8096 const bool IsHIPKernel = M.getLangOpts().HIP &&
8097 FD->hasAttr<CUDAGlobalAttr>();
8098 if ((IsOpenCLKernel || IsHIPKernel) &&
8099 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
8100 F->addFnAttr("amdgpu-implicitarg-num-bytes", "56");
8102 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
8103 if (ReqdWGS || FlatWGS) {
8107 Min = FlatWGS->getMin()
8108 ->EvaluateKnownConstInt(M.getContext())
8110 Max = FlatWGS->getMax()
8111 ->EvaluateKnownConstInt(M.getContext())
8114 if (ReqdWGS && Min == 0 && Max == 0)
8115 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
8118 assert(Min <= Max && "Min must be less than or equal Max");
8120 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
8121 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8123 assert(Max == 0 && "Max must be zero");
8124 } else if (IsOpenCLKernel || IsHIPKernel) {
8125 // By default, restrict the maximum size to a value specified by
8126 // --gpu-max-threads-per-block=n or its default value.
8127 std::string AttrVal =
8128 std::string("1,") + llvm::utostr(M.getLangOpts().GPUMaxThreadsPerBlock);
8129 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
8132 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
8134 Attr->getMin()->EvaluateKnownConstInt(M.getContext()).getExtValue();
8135 unsigned Max = Attr->getMax() ? Attr->getMax()
8136 ->EvaluateKnownConstInt(M.getContext())
8141 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
8143 std::string AttrVal = llvm::utostr(Min);
8145 AttrVal = AttrVal + "," + llvm::utostr(Max);
8146 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
8148 assert(Max == 0 && "Max must be zero");
8151 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
8152 unsigned NumSGPR = Attr->getNumSGPR();
8155 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
8158 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
8159 uint32_t NumVGPR = Attr->getNumVGPR();
8162 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
8166 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8167 return llvm::CallingConv::AMDGPU_KERNEL;
8170 // Currently LLVM assumes null pointers always have value 0,
8171 // which results in incorrectly transformed IR. Therefore, instead of
8172 // emitting null pointers in private and local address spaces, a null
8173 // pointer in generic address space is emitted which is casted to a
8174 // pointer in local or private address space.
8175 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
8176 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
8177 QualType QT) const {
8178 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
8179 return llvm::ConstantPointerNull::get(PT);
8181 auto &Ctx = CGM.getContext();
8182 auto NPT = llvm::PointerType::get(PT->getElementType(),
8183 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
8184 return llvm::ConstantExpr::getAddrSpaceCast(
8185 llvm::ConstantPointerNull::get(NPT), PT);
8189 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
8190 const VarDecl *D) const {
8191 assert(!CGM.getLangOpts().OpenCL &&
8192 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
8193 "Address space agnostic languages only");
8194 LangAS DefaultGlobalAS = getLangASFromTargetAS(
8195 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
8197 return DefaultGlobalAS;
8199 LangAS AddrSpace = D->getType().getAddressSpace();
8200 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
8201 if (AddrSpace != LangAS::Default)
8204 if (CGM.isTypeConstant(D->getType(), false)) {
8205 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
8206 return ConstAS.getValue();
8208 return DefaultGlobalAS;
8212 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(const LangOptions &LangOpts,
8214 llvm::AtomicOrdering Ordering,
8215 llvm::LLVMContext &Ctx) const {
8218 case SyncScope::OpenCLWorkGroup:
8221 case SyncScope::OpenCLDevice:
8224 case SyncScope::OpenCLAllSVMDevices:
8227 case SyncScope::OpenCLSubGroup:
8231 if (Ordering != llvm::AtomicOrdering::SequentiallyConsistent) {
8233 Name = Twine(Twine(Name) + Twine("-")).str();
8235 Name = Twine(Twine(Name) + Twine("one-as")).str();
8238 return Ctx.getOrInsertSyncScopeID(Name);
8241 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
8245 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
8246 const FunctionType *&FT) const {
8247 FT = getABIInfo().getContext().adjustFunctionType(
8248 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
8251 //===----------------------------------------------------------------------===//
8252 // SPARC v8 ABI Implementation.
8253 // Based on the SPARC Compliance Definition version 2.4.1.
8255 // Ensures that complex values are passed in registers.
8258 class SparcV8ABIInfo : public DefaultABIInfo {
8260 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8263 ABIArgInfo classifyReturnType(QualType RetTy) const;
8264 void computeInfo(CGFunctionInfo &FI) const override;
8266 } // end anonymous namespace
8270 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
8271 if (Ty->isAnyComplexType()) {
8272 return ABIArgInfo::getDirect();
8275 return DefaultABIInfo::classifyReturnType(Ty);
8279 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8281 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8282 for (auto &Arg : FI.arguments())
8283 Arg.info = classifyArgumentType(Arg.type);
8287 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
8289 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
8290 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
8292 } // end anonymous namespace
8294 //===----------------------------------------------------------------------===//
8295 // SPARC v9 ABI Implementation.
8296 // Based on the SPARC Compliance Definition version 2.4.1.
8298 // Function arguments a mapped to a nominal "parameter array" and promoted to
8299 // registers depending on their type. Each argument occupies 8 or 16 bytes in
8300 // the array, structs larger than 16 bytes are passed indirectly.
8302 // One case requires special care:
8309 // When a struct mixed is passed by value, it only occupies 8 bytes in the
8310 // parameter array, but the int is passed in an integer register, and the float
8311 // is passed in a floating point register. This is represented as two arguments
8312 // with the LLVM IR inreg attribute:
8314 // declare void f(i32 inreg %i, float inreg %f)
8316 // The code generator will only allocate 4 bytes from the parameter array for
8317 // the inreg arguments. All other arguments are allocated a multiple of 8
8321 class SparcV9ABIInfo : public ABIInfo {
8323 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
8326 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
8327 void computeInfo(CGFunctionInfo &FI) const override;
8328 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8329 QualType Ty) const override;
8331 // Coercion type builder for structs passed in registers. The coercion type
8332 // serves two purposes:
8334 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
8336 // 2. Expose aligned floating point elements as first-level elements, so the
8337 // code generator knows to pass them in floating point registers.
8339 // We also compute the InReg flag which indicates that the struct contains
8340 // aligned 32-bit floats.
8342 struct CoerceBuilder {
8343 llvm::LLVMContext &Context;
8344 const llvm::DataLayout &DL;
8345 SmallVector<llvm::Type*, 8> Elems;
8349 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
8350 : Context(c), DL(dl), Size(0), InReg(false) {}
8352 // Pad Elems with integers until Size is ToSize.
8353 void pad(uint64_t ToSize) {
8354 assert(ToSize >= Size && "Cannot remove elements");
8358 // Finish the current 64-bit word.
8359 uint64_t Aligned = llvm::alignTo(Size, 64);
8360 if (Aligned > Size && Aligned <= ToSize) {
8361 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
8365 // Add whole 64-bit words.
8366 while (Size + 64 <= ToSize) {
8367 Elems.push_back(llvm::Type::getInt64Ty(Context));
8371 // Final in-word padding.
8372 if (Size < ToSize) {
8373 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
8378 // Add a floating point element at Offset.
8379 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
8380 // Unaligned floats are treated as integers.
8383 // The InReg flag is only required if there are any floats < 64 bits.
8387 Elems.push_back(Ty);
8388 Size = Offset + Bits;
8391 // Add a struct type to the coercion type, starting at Offset (in bits).
8392 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
8393 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
8394 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
8395 llvm::Type *ElemTy = StrTy->getElementType(i);
8396 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
8397 switch (ElemTy->getTypeID()) {
8398 case llvm::Type::StructTyID:
8399 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
8401 case llvm::Type::FloatTyID:
8402 addFloat(ElemOffset, ElemTy, 32);
8404 case llvm::Type::DoubleTyID:
8405 addFloat(ElemOffset, ElemTy, 64);
8407 case llvm::Type::FP128TyID:
8408 addFloat(ElemOffset, ElemTy, 128);
8410 case llvm::Type::PointerTyID:
8411 if (ElemOffset % 64 == 0) {
8413 Elems.push_back(ElemTy);
8423 // Check if Ty is a usable substitute for the coercion type.
8424 bool isUsableType(llvm::StructType *Ty) const {
8425 return llvm::makeArrayRef(Elems) == Ty->elements();
8428 // Get the coercion type as a literal struct type.
8429 llvm::Type *getType() const {
8430 if (Elems.size() == 1)
8431 return Elems.front();
8433 return llvm::StructType::get(Context, Elems);
8437 } // end anonymous namespace
8440 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
8441 if (Ty->isVoidType())
8442 return ABIArgInfo::getIgnore();
8444 uint64_t Size = getContext().getTypeSize(Ty);
8446 // Anything too big to fit in registers is passed with an explicit indirect
8447 // pointer / sret pointer.
8448 if (Size > SizeLimit)
8449 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
8451 // Treat an enum type as its underlying type.
8452 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8453 Ty = EnumTy->getDecl()->getIntegerType();
8455 // Integer types smaller than a register are extended.
8456 if (Size < 64 && Ty->isIntegerType())
8457 return ABIArgInfo::getExtend(Ty);
8459 // Other non-aggregates go in registers.
8460 if (!isAggregateTypeForABI(Ty))
8461 return ABIArgInfo::getDirect();
8463 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8464 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8465 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8466 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8468 // This is a small aggregate type that should be passed in registers.
8469 // Build a coercion type from the LLVM struct type.
8470 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8472 return ABIArgInfo::getDirect();
8474 CoerceBuilder CB(getVMContext(), getDataLayout());
8475 CB.addStruct(0, StrTy);
8476 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
8478 // Try to use the original type for coercion.
8479 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8482 return ABIArgInfo::getDirectInReg(CoerceTy);
8484 return ABIArgInfo::getDirect(CoerceTy);
8487 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8488 QualType Ty) const {
8489 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8490 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8491 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8492 AI.setCoerceToType(ArgTy);
8494 CharUnits SlotSize = CharUnits::fromQuantity(8);
8496 CGBuilderTy &Builder = CGF.Builder;
8497 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8498 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8500 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8502 Address ArgAddr = Address::invalid();
8504 switch (AI.getKind()) {
8505 case ABIArgInfo::Expand:
8506 case ABIArgInfo::CoerceAndExpand:
8507 case ABIArgInfo::InAlloca:
8508 llvm_unreachable("Unsupported ABI kind for va_arg");
8510 case ABIArgInfo::Extend: {
8512 CharUnits Offset = SlotSize - TypeInfo.first;
8513 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
8517 case ABIArgInfo::Direct: {
8518 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
8519 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
8524 case ABIArgInfo::Indirect:
8526 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8527 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8531 case ABIArgInfo::Ignore:
8532 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
8536 Address NextPtr = Builder.CreateConstInBoundsByteGEP(Addr, Stride, "ap.next");
8537 Builder.CreateStore(NextPtr.getPointer(), VAListAddr);
8539 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
8542 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8543 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
8544 for (auto &I : FI.arguments())
8545 I.info = classifyType(I.type, 16 * 8);
8549 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8551 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8552 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
8554 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8558 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8559 llvm::Value *Address) const override;
8561 } // end anonymous namespace
8564 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8565 llvm::Value *Address) const {
8566 // This is calculated from the LLVM and GCC tables and verified
8567 // against gcc output. AFAIK all ABIs use the same encoding.
8569 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8571 llvm::IntegerType *i8 = CGF.Int8Ty;
8572 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8573 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8575 // 0-31: the 8-byte general-purpose registers
8576 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8578 // 32-63: f0-31, the 4-byte floating-point registers
8579 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8589 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
8591 // 72-87: d0-15, the 8-byte floating-point registers
8592 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8597 // ARC ABI implementation.
8600 class ARCABIInfo : public DefaultABIInfo {
8602 using DefaultABIInfo::DefaultABIInfo;
8605 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8606 QualType Ty) const override;
8608 void updateState(const ABIArgInfo &Info, QualType Ty, CCState &State) const {
8609 if (!State.FreeRegs)
8611 if (Info.isIndirect() && Info.getInReg())
8613 else if (Info.isDirect() && Info.getInReg()) {
8614 unsigned sz = (getContext().getTypeSize(Ty) + 31) / 32;
8615 if (sz < State.FreeRegs)
8616 State.FreeRegs -= sz;
8622 void computeInfo(CGFunctionInfo &FI) const override {
8624 // ARC uses 8 registers to pass arguments.
8627 if (!getCXXABI().classifyReturnType(FI))
8628 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
8629 updateState(FI.getReturnInfo(), FI.getReturnType(), State);
8630 for (auto &I : FI.arguments()) {
8631 I.info = classifyArgumentType(I.type, State.FreeRegs);
8632 updateState(I.info, I.type, State);
8636 ABIArgInfo getIndirectByRef(QualType Ty, bool HasFreeRegs) const;
8637 ABIArgInfo getIndirectByValue(QualType Ty) const;
8638 ABIArgInfo classifyArgumentType(QualType Ty, uint8_t FreeRegs) const;
8639 ABIArgInfo classifyReturnType(QualType RetTy) const;
8642 class ARCTargetCodeGenInfo : public TargetCodeGenInfo {
8644 ARCTargetCodeGenInfo(CodeGenTypes &CGT)
8645 : TargetCodeGenInfo(new ARCABIInfo(CGT)) {}
8649 ABIArgInfo ARCABIInfo::getIndirectByRef(QualType Ty, bool HasFreeRegs) const {
8650 return HasFreeRegs ? getNaturalAlignIndirectInReg(Ty) :
8651 getNaturalAlignIndirect(Ty, false);
8654 ABIArgInfo ARCABIInfo::getIndirectByValue(QualType Ty) const {
8655 // Compute the byval alignment.
8656 const unsigned MinABIStackAlignInBytes = 4;
8657 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
8658 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
8659 TypeAlign > MinABIStackAlignInBytes);
8662 Address ARCABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8663 QualType Ty) const {
8664 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
8665 getContext().getTypeInfoInChars(Ty),
8666 CharUnits::fromQuantity(4), true);
8669 ABIArgInfo ARCABIInfo::classifyArgumentType(QualType Ty,
8670 uint8_t FreeRegs) const {
8671 // Handle the generic C++ ABI.
8672 const RecordType *RT = Ty->getAs<RecordType>();
8674 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
8675 if (RAA == CGCXXABI::RAA_Indirect)
8676 return getIndirectByRef(Ty, FreeRegs > 0);
8678 if (RAA == CGCXXABI::RAA_DirectInMemory)
8679 return getIndirectByValue(Ty);
8682 // Treat an enum type as its underlying type.
8683 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8684 Ty = EnumTy->getDecl()->getIntegerType();
8686 auto SizeInRegs = llvm::alignTo(getContext().getTypeSize(Ty), 32) / 32;
8688 if (isAggregateTypeForABI(Ty)) {
8689 // Structures with flexible arrays are always indirect.
8690 if (RT && RT->getDecl()->hasFlexibleArrayMember())
8691 return getIndirectByValue(Ty);
8693 // Ignore empty structs/unions.
8694 if (isEmptyRecord(getContext(), Ty, true))
8695 return ABIArgInfo::getIgnore();
8697 llvm::LLVMContext &LLVMContext = getVMContext();
8699 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
8700 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
8701 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
8703 return FreeRegs >= SizeInRegs ?
8704 ABIArgInfo::getDirectInReg(Result) :
8705 ABIArgInfo::getDirect(Result, 0, nullptr, false);
8708 return Ty->isPromotableIntegerType() ?
8709 (FreeRegs >= SizeInRegs ? ABIArgInfo::getExtendInReg(Ty) :
8710 ABIArgInfo::getExtend(Ty)) :
8711 (FreeRegs >= SizeInRegs ? ABIArgInfo::getDirectInReg() :
8712 ABIArgInfo::getDirect());
8715 ABIArgInfo ARCABIInfo::classifyReturnType(QualType RetTy) const {
8716 if (RetTy->isAnyComplexType())
8717 return ABIArgInfo::getDirectInReg();
8719 // Arguments of size > 4 registers are indirect.
8720 auto RetSize = llvm::alignTo(getContext().getTypeSize(RetTy), 32) / 32;
8722 return getIndirectByRef(RetTy, /*HasFreeRegs*/ true);
8724 return DefaultABIInfo::classifyReturnType(RetTy);
8727 } // End anonymous namespace.
8729 //===----------------------------------------------------------------------===//
8730 // XCore ABI Implementation
8731 //===----------------------------------------------------------------------===//
8735 /// A SmallStringEnc instance is used to build up the TypeString by passing
8736 /// it by reference between functions that append to it.
8737 typedef llvm::SmallString<128> SmallStringEnc;
8739 /// TypeStringCache caches the meta encodings of Types.
8741 /// The reason for caching TypeStrings is two fold:
8742 /// 1. To cache a type's encoding for later uses;
8743 /// 2. As a means to break recursive member type inclusion.
8745 /// A cache Entry can have a Status of:
8746 /// NonRecursive: The type encoding is not recursive;
8747 /// Recursive: The type encoding is recursive;
8748 /// Incomplete: An incomplete TypeString;
8749 /// IncompleteUsed: An incomplete TypeString that has been used in a
8750 /// Recursive type encoding.
8752 /// A NonRecursive entry will have all of its sub-members expanded as fully
8753 /// as possible. Whilst it may contain types which are recursive, the type
8754 /// itself is not recursive and thus its encoding may be safely used whenever
8755 /// the type is encountered.
8757 /// A Recursive entry will have all of its sub-members expanded as fully as
8758 /// possible. The type itself is recursive and it may contain other types which
8759 /// are recursive. The Recursive encoding must not be used during the expansion
8760 /// of a recursive type's recursive branch. For simplicity the code uses
8761 /// IncompleteCount to reject all usage of Recursive encodings for member types.
8763 /// An Incomplete entry is always a RecordType and only encodes its
8764 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8765 /// are placed into the cache during type expansion as a means to identify and
8766 /// handle recursive inclusion of types as sub-members. If there is recursion
8767 /// the entry becomes IncompleteUsed.
8769 /// During the expansion of a RecordType's members:
8771 /// If the cache contains a NonRecursive encoding for the member type, the
8772 /// cached encoding is used;
8774 /// If the cache contains a Recursive encoding for the member type, the
8775 /// cached encoding is 'Swapped' out, as it may be incorrect, and...
8777 /// If the member is a RecordType, an Incomplete encoding is placed into the
8778 /// cache to break potential recursive inclusion of itself as a sub-member;
8780 /// Once a member RecordType has been expanded, its temporary incomplete
8781 /// entry is removed from the cache. If a Recursive encoding was swapped out
8782 /// it is swapped back in;
8784 /// If an incomplete entry is used to expand a sub-member, the incomplete
8785 /// entry is marked as IncompleteUsed. The cache keeps count of how many
8786 /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8788 /// If a member's encoding is found to be a NonRecursive or Recursive viz:
8789 /// IncompleteUsedCount==0, the member's encoding is added to the cache.
8790 /// Else the member is part of a recursive type and thus the recursion has
8791 /// been exited too soon for the encoding to be correct for the member.
8793 class TypeStringCache {
8794 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8796 std::string Str; // The encoded TypeString for the type.
8797 enum Status State; // Information about the encoding in 'Str'.
8798 std::string Swapped; // A temporary place holder for a Recursive encoding
8799 // during the expansion of RecordType's members.
8801 std::map<const IdentifierInfo *, struct Entry> Map;
8802 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8803 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8805 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
8806 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8807 bool removeIncomplete(const IdentifierInfo *ID);
8808 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8810 StringRef lookupStr(const IdentifierInfo *ID);
8813 /// TypeString encodings for enum & union fields must be order.
8814 /// FieldEncoding is a helper for this ordering process.
8815 class FieldEncoding {
8819 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
8820 StringRef str() { return Enc; }
8821 bool operator<(const FieldEncoding &rhs) const {
8822 if (HasName != rhs.HasName) return HasName;
8823 return Enc < rhs.Enc;
8827 class XCoreABIInfo : public DefaultABIInfo {
8829 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8830 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8831 QualType Ty) const override;
8834 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
8835 mutable TypeStringCache TSC;
8837 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
8838 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
8839 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8840 CodeGen::CodeGenModule &M) const override;
8843 } // End anonymous namespace.
8845 // TODO: this implementation is likely now redundant with the default
8847 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8848 QualType Ty) const {
8849 CGBuilderTy &Builder = CGF.Builder;
8852 CharUnits SlotSize = CharUnits::fromQuantity(4);
8853 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
8855 // Handle the argument.
8856 ABIArgInfo AI = classifyArgumentType(Ty);
8857 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
8858 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8859 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8860 AI.setCoerceToType(ArgTy);
8861 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8863 Address Val = Address::invalid();
8864 CharUnits ArgSize = CharUnits::Zero();
8865 switch (AI.getKind()) {
8866 case ABIArgInfo::Expand:
8867 case ABIArgInfo::CoerceAndExpand:
8868 case ABIArgInfo::InAlloca:
8869 llvm_unreachable("Unsupported ABI kind for va_arg");
8870 case ABIArgInfo::Ignore:
8871 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8872 ArgSize = CharUnits::Zero();
8874 case ABIArgInfo::Extend:
8875 case ABIArgInfo::Direct:
8876 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8877 ArgSize = CharUnits::fromQuantity(
8878 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
8879 ArgSize = ArgSize.alignTo(SlotSize);
8881 case ABIArgInfo::Indirect:
8882 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8883 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8888 // Increment the VAList.
8889 if (!ArgSize.isZero()) {
8890 Address APN = Builder.CreateConstInBoundsByteGEP(AP, ArgSize);
8891 Builder.CreateStore(APN.getPointer(), VAListAddr);
8897 /// During the expansion of a RecordType, an incomplete TypeString is placed
8898 /// into the cache as a means to identify and break recursion.
8899 /// If there is a Recursive encoding in the cache, it is swapped out and will
8900 /// be reinserted by removeIncomplete().
8901 /// All other types of encoding should have been used rather than arriving here.
8902 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8903 std::string StubEnc) {
8907 assert( (E.Str.empty() || E.State == Recursive) &&
8908 "Incorrectly use of addIncomplete");
8909 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8910 E.Swapped.swap(E.Str); // swap out the Recursive
8911 E.Str.swap(StubEnc);
8912 E.State = Incomplete;
8916 /// Once the RecordType has been expanded, the temporary incomplete TypeString
8917 /// must be removed from the cache.
8918 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8919 /// Returns true if the RecordType was defined recursively.
8920 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8923 auto I = Map.find(ID);
8924 assert(I != Map.end() && "Entry not present");
8925 Entry &E = I->second;
8926 assert( (E.State == Incomplete ||
8927 E.State == IncompleteUsed) &&
8928 "Entry must be an incomplete type");
8929 bool IsRecursive = false;
8930 if (E.State == IncompleteUsed) {
8931 // We made use of our Incomplete encoding, thus we are recursive.
8933 --IncompleteUsedCount;
8935 if (E.Swapped.empty())
8938 // Swap the Recursive back.
8939 E.Swapped.swap(E.Str);
8941 E.State = Recursive;
8947 /// Add the encoded TypeString to the cache only if it is NonRecursive or
8948 /// Recursive (viz: all sub-members were expanded as fully as possible).
8949 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8951 if (!ID || IncompleteUsedCount)
8952 return; // No key or it is is an incomplete sub-type so don't add.
8954 if (IsRecursive && !E.Str.empty()) {
8955 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8956 "This is not the same Recursive entry");
8957 // The parent container was not recursive after all, so we could have used
8958 // this Recursive sub-member entry after all, but we assumed the worse when
8959 // we started viz: IncompleteCount!=0.
8962 assert(E.Str.empty() && "Entry already present");
8964 E.State = IsRecursive? Recursive : NonRecursive;
8967 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
8968 /// are recursively expanding a type (IncompleteCount != 0) and the cached
8969 /// encoding is Recursive, return an empty StringRef.
8970 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8972 return StringRef(); // We have no key.
8973 auto I = Map.find(ID);
8975 return StringRef(); // We have no encoding.
8976 Entry &E = I->second;
8977 if (E.State == Recursive && IncompleteCount)
8978 return StringRef(); // We don't use Recursive encodings for member types.
8980 if (E.State == Incomplete) {
8981 // The incomplete type is being used to break out of recursion.
8982 E.State = IncompleteUsed;
8983 ++IncompleteUsedCount;
8988 /// The XCore ABI includes a type information section that communicates symbol
8989 /// type information to the linker. The linker uses this information to verify
8990 /// safety/correctness of things such as array bound and pointers et al.
8991 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
8992 /// This type information (TypeString) is emitted into meta data for all global
8993 /// symbols: definitions, declarations, functions & variables.
8995 /// The TypeString carries type, qualifier, name, size & value details.
8996 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
8997 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
8998 /// The output is tested by test/CodeGen/xcore-stringtype.c.
9000 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9001 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
9003 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
9004 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
9005 CodeGen::CodeGenModule &CGM) const {
9007 if (getTypeString(Enc, D, CGM, TSC)) {
9008 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
9009 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
9010 llvm::MDString::get(Ctx, Enc.str())};
9011 llvm::NamedMDNode *MD =
9012 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
9013 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
9017 //===----------------------------------------------------------------------===//
9018 // SPIR ABI Implementation
9019 //===----------------------------------------------------------------------===//
9022 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
9024 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
9025 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
9026 unsigned getOpenCLKernelCallingConv() const override;
9029 } // End anonymous namespace.
9033 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
9034 DefaultABIInfo SPIRABI(CGM.getTypes());
9035 SPIRABI.computeInfo(FI);
9040 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
9041 return llvm::CallingConv::SPIR_KERNEL;
9044 static bool appendType(SmallStringEnc &Enc, QualType QType,
9045 const CodeGen::CodeGenModule &CGM,
9046 TypeStringCache &TSC);
9048 /// Helper function for appendRecordType().
9049 /// Builds a SmallVector containing the encoded field types in declaration
9051 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
9052 const RecordDecl *RD,
9053 const CodeGen::CodeGenModule &CGM,
9054 TypeStringCache &TSC) {
9055 for (const auto *Field : RD->fields()) {
9058 Enc += Field->getName();
9060 if (Field->isBitField()) {
9062 llvm::raw_svector_ostream OS(Enc);
9063 OS << Field->getBitWidthValue(CGM.getContext());
9066 if (!appendType(Enc, Field->getType(), CGM, TSC))
9068 if (Field->isBitField())
9071 FE.emplace_back(!Field->getName().empty(), Enc);
9076 /// Appends structure and union types to Enc and adds encoding to cache.
9077 /// Recursively calls appendType (via extractFieldType) for each field.
9078 /// Union types have their fields ordered according to the ABI.
9079 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
9080 const CodeGen::CodeGenModule &CGM,
9081 TypeStringCache &TSC, const IdentifierInfo *ID) {
9082 // Append the cached TypeString if we have one.
9083 StringRef TypeString = TSC.lookupStr(ID);
9084 if (!TypeString.empty()) {
9089 // Start to emit an incomplete TypeString.
9090 size_t Start = Enc.size();
9091 Enc += (RT->isUnionType()? 'u' : 's');
9094 Enc += ID->getName();
9097 // We collect all encoded fields and order as necessary.
9098 bool IsRecursive = false;
9099 const RecordDecl *RD = RT->getDecl()->getDefinition();
9100 if (RD && !RD->field_empty()) {
9101 // An incomplete TypeString stub is placed in the cache for this RecordType
9102 // so that recursive calls to this RecordType will use it whilst building a
9103 // complete TypeString for this RecordType.
9104 SmallVector<FieldEncoding, 16> FE;
9105 std::string StubEnc(Enc.substr(Start).str());
9106 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
9107 TSC.addIncomplete(ID, std::move(StubEnc));
9108 if (!extractFieldType(FE, RD, CGM, TSC)) {
9109 (void) TSC.removeIncomplete(ID);
9112 IsRecursive = TSC.removeIncomplete(ID);
9113 // The ABI requires unions to be sorted but not structures.
9114 // See FieldEncoding::operator< for sort algorithm.
9115 if (RT->isUnionType())
9117 // We can now complete the TypeString.
9118 unsigned E = FE.size();
9119 for (unsigned I = 0; I != E; ++I) {
9126 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
9130 /// Appends enum types to Enc and adds the encoding to the cache.
9131 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
9132 TypeStringCache &TSC,
9133 const IdentifierInfo *ID) {
9134 // Append the cached TypeString if we have one.
9135 StringRef TypeString = TSC.lookupStr(ID);
9136 if (!TypeString.empty()) {
9141 size_t Start = Enc.size();
9144 Enc += ID->getName();
9147 // We collect all encoded enumerations and order them alphanumerically.
9148 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
9149 SmallVector<FieldEncoding, 16> FE;
9150 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
9152 SmallStringEnc EnumEnc;
9154 EnumEnc += I->getName();
9156 I->getInitVal().toString(EnumEnc);
9158 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
9161 unsigned E = FE.size();
9162 for (unsigned I = 0; I != E; ++I) {
9169 TSC.addIfComplete(ID, Enc.substr(Start), false);
9173 /// Appends type's qualifier to Enc.
9174 /// This is done prior to appending the type's encoding.
9175 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
9176 // Qualifiers are emitted in alphabetical order.
9177 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
9179 if (QT.isConstQualified())
9181 if (QT.isRestrictQualified())
9183 if (QT.isVolatileQualified())
9185 Enc += Table[Lookup];
9188 /// Appends built-in types to Enc.
9189 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
9190 const char *EncType;
9191 switch (BT->getKind()) {
9192 case BuiltinType::Void:
9195 case BuiltinType::Bool:
9198 case BuiltinType::Char_U:
9201 case BuiltinType::UChar:
9204 case BuiltinType::SChar:
9207 case BuiltinType::UShort:
9210 case BuiltinType::Short:
9213 case BuiltinType::UInt:
9216 case BuiltinType::Int:
9219 case BuiltinType::ULong:
9222 case BuiltinType::Long:
9225 case BuiltinType::ULongLong:
9228 case BuiltinType::LongLong:
9231 case BuiltinType::Float:
9234 case BuiltinType::Double:
9237 case BuiltinType::LongDouble:
9247 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
9248 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
9249 const CodeGen::CodeGenModule &CGM,
9250 TypeStringCache &TSC) {
9252 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
9258 /// Appends array encoding to Enc before calling appendType for the element.
9259 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
9260 const ArrayType *AT,
9261 const CodeGen::CodeGenModule &CGM,
9262 TypeStringCache &TSC, StringRef NoSizeEnc) {
9263 if (AT->getSizeModifier() != ArrayType::Normal)
9266 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
9267 CAT->getSize().toStringUnsigned(Enc);
9269 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
9271 // The Qualifiers should be attached to the type rather than the array.
9272 appendQualifier(Enc, QT);
9273 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
9279 /// Appends a function encoding to Enc, calling appendType for the return type
9280 /// and the arguments.
9281 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
9282 const CodeGen::CodeGenModule &CGM,
9283 TypeStringCache &TSC) {
9285 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
9288 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
9289 // N.B. we are only interested in the adjusted param types.
9290 auto I = FPT->param_type_begin();
9291 auto E = FPT->param_type_end();
9294 if (!appendType(Enc, *I, CGM, TSC))
9300 if (FPT->isVariadic())
9303 if (FPT->isVariadic())
9313 /// Handles the type's qualifier before dispatching a call to handle specific
9315 static bool appendType(SmallStringEnc &Enc, QualType QType,
9316 const CodeGen::CodeGenModule &CGM,
9317 TypeStringCache &TSC) {
9319 QualType QT = QType.getCanonicalType();
9321 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
9322 // The Qualifiers should be attached to the type rather than the array.
9323 // Thus we don't call appendQualifier() here.
9324 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
9326 appendQualifier(Enc, QT);
9328 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
9329 return appendBuiltinType(Enc, BT);
9331 if (const PointerType *PT = QT->getAs<PointerType>())
9332 return appendPointerType(Enc, PT, CGM, TSC);
9334 if (const EnumType *ET = QT->getAs<EnumType>())
9335 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
9337 if (const RecordType *RT = QT->getAsStructureType())
9338 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9340 if (const RecordType *RT = QT->getAsUnionType())
9341 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
9343 if (const FunctionType *FT = QT->getAs<FunctionType>())
9344 return appendFunctionType(Enc, FT, CGM, TSC);
9349 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
9350 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
9354 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
9355 if (FD->getLanguageLinkage() != CLanguageLinkage)
9357 return appendType(Enc, FD->getType(), CGM, TSC);
9360 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
9361 if (VD->getLanguageLinkage() != CLanguageLinkage)
9363 QualType QT = VD->getType().getCanonicalType();
9364 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
9365 // Global ArrayTypes are given a size of '*' if the size is unknown.
9366 // The Qualifiers should be attached to the type rather than the array.
9367 // Thus we don't call appendQualifier() here.
9368 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
9370 return appendType(Enc, QT, CGM, TSC);
9375 //===----------------------------------------------------------------------===//
9376 // RISCV ABI Implementation
9377 //===----------------------------------------------------------------------===//
9380 class RISCVABIInfo : public DefaultABIInfo {
9382 // Size of the integer ('x') registers in bits.
9384 // Size of the floating point ('f') registers in bits. Note that the target
9385 // ISA might have a wider FLen than the selected ABI (e.g. an RV32IF target
9386 // with soft float ABI has FLen==0).
9388 static const int NumArgGPRs = 8;
9389 static const int NumArgFPRs = 8;
9390 bool detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9391 llvm::Type *&Field1Ty,
9392 CharUnits &Field1Off,
9393 llvm::Type *&Field2Ty,
9394 CharUnits &Field2Off) const;
9397 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen, unsigned FLen)
9398 : DefaultABIInfo(CGT), XLen(XLen), FLen(FLen) {}
9400 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
9401 // non-virtual, but computeInfo is virtual, so we overload it.
9402 void computeInfo(CGFunctionInfo &FI) const override;
9404 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed, int &ArgGPRsLeft,
9405 int &ArgFPRsLeft) const;
9406 ABIArgInfo classifyReturnType(QualType RetTy) const;
9408 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9409 QualType Ty) const override;
9411 ABIArgInfo extendType(QualType Ty) const;
9413 bool detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9414 CharUnits &Field1Off, llvm::Type *&Field2Ty,
9415 CharUnits &Field2Off, int &NeededArgGPRs,
9416 int &NeededArgFPRs) const;
9417 ABIArgInfo coerceAndExpandFPCCEligibleStruct(llvm::Type *Field1Ty,
9418 CharUnits Field1Off,
9419 llvm::Type *Field2Ty,
9420 CharUnits Field2Off) const;
9422 } // end anonymous namespace
9424 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
9425 QualType RetTy = FI.getReturnType();
9426 if (!getCXXABI().classifyReturnType(FI))
9427 FI.getReturnInfo() = classifyReturnType(RetTy);
9429 // IsRetIndirect is true if classifyArgumentType indicated the value should
9430 // be passed indirect, or if the type size is a scalar greater than 2*XLen
9431 // and not a complex type with elements <= FLen. e.g. fp128 is passed direct
9432 // in LLVM IR, relying on the backend lowering code to rewrite the argument
9433 // list and pass indirectly on RV32.
9434 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect;
9435 if (!IsRetIndirect && RetTy->isScalarType() &&
9436 getContext().getTypeSize(RetTy) > (2 * XLen)) {
9437 if (RetTy->isComplexType() && FLen) {
9438 QualType EltTy = RetTy->getAs<ComplexType>()->getElementType();
9439 IsRetIndirect = getContext().getTypeSize(EltTy) > FLen;
9441 // This is a normal scalar > 2*XLen, such as fp128 on RV32.
9442 IsRetIndirect = true;
9446 // We must track the number of GPRs used in order to conform to the RISC-V
9447 // ABI, as integer scalars passed in registers should have signext/zeroext
9448 // when promoted, but are anyext if passed on the stack. As GPR usage is
9449 // different for variadic arguments, we must also track whether we are
9450 // examining a vararg or not.
9451 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
9452 int ArgFPRsLeft = FLen ? NumArgFPRs : 0;
9453 int NumFixedArgs = FI.getNumRequiredArgs();
9456 for (auto &ArgInfo : FI.arguments()) {
9457 bool IsFixed = ArgNum < NumFixedArgs;
9459 classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft, ArgFPRsLeft);
9464 // Returns true if the struct is a potential candidate for the floating point
9465 // calling convention. If this function returns true, the caller is
9466 // responsible for checking that if there is only a single field then that
9467 // field is a float.
9468 bool RISCVABIInfo::detectFPCCEligibleStructHelper(QualType Ty, CharUnits CurOff,
9469 llvm::Type *&Field1Ty,
9470 CharUnits &Field1Off,
9471 llvm::Type *&Field2Ty,
9472 CharUnits &Field2Off) const {
9473 bool IsInt = Ty->isIntegralOrEnumerationType();
9474 bool IsFloat = Ty->isRealFloatingType();
9476 if (IsInt || IsFloat) {
9477 uint64_t Size = getContext().getTypeSize(Ty);
9478 if (IsInt && Size > XLen)
9480 // Can't be eligible if larger than the FP registers. Half precision isn't
9481 // currently supported on RISC-V and the ABI hasn't been confirmed, so
9482 // default to the integer ABI in that case.
9483 if (IsFloat && (Size > FLen || Size < 32))
9485 // Can't be eligible if an integer type was already found (int+int pairs
9486 // are not eligible).
9487 if (IsInt && Field1Ty && Field1Ty->isIntegerTy())
9490 Field1Ty = CGT.ConvertType(Ty);
9495 Field2Ty = CGT.ConvertType(Ty);
9502 if (auto CTy = Ty->getAs<ComplexType>()) {
9505 QualType EltTy = CTy->getElementType();
9506 if (getContext().getTypeSize(EltTy) > FLen)
9508 Field1Ty = CGT.ConvertType(EltTy);
9510 assert(CurOff.isZero() && "Unexpected offset for first field");
9511 Field2Ty = Field1Ty;
9512 Field2Off = Field1Off + getContext().getTypeSizeInChars(EltTy);
9516 if (const ConstantArrayType *ATy = getContext().getAsConstantArrayType(Ty)) {
9517 uint64_t ArraySize = ATy->getSize().getZExtValue();
9518 QualType EltTy = ATy->getElementType();
9519 CharUnits EltSize = getContext().getTypeSizeInChars(EltTy);
9520 for (uint64_t i = 0; i < ArraySize; ++i) {
9521 bool Ret = detectFPCCEligibleStructHelper(EltTy, CurOff, Field1Ty,
9522 Field1Off, Field2Ty, Field2Off);
9530 if (const auto *RTy = Ty->getAs<RecordType>()) {
9531 // Structures with either a non-trivial destructor or a non-trivial
9532 // copy constructor are not eligible for the FP calling convention.
9533 if (getRecordArgABI(Ty, CGT.getCXXABI()))
9535 if (isEmptyRecord(getContext(), Ty, true))
9537 const RecordDecl *RD = RTy->getDecl();
9538 // Unions aren't eligible unless they're empty (which is caught above).
9541 int ZeroWidthBitFieldCount = 0;
9542 for (const FieldDecl *FD : RD->fields()) {
9543 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
9544 uint64_t FieldOffInBits = Layout.getFieldOffset(FD->getFieldIndex());
9545 QualType QTy = FD->getType();
9546 if (FD->isBitField()) {
9547 unsigned BitWidth = FD->getBitWidthValue(getContext());
9548 // Allow a bitfield with a type greater than XLen as long as the
9549 // bitwidth is XLen or less.
9550 if (getContext().getTypeSize(QTy) > XLen && BitWidth <= XLen)
9551 QTy = getContext().getIntTypeForBitwidth(XLen, false);
9552 if (BitWidth == 0) {
9553 ZeroWidthBitFieldCount++;
9558 bool Ret = detectFPCCEligibleStructHelper(
9559 QTy, CurOff + getContext().toCharUnitsFromBits(FieldOffInBits),
9560 Field1Ty, Field1Off, Field2Ty, Field2Off);
9564 // As a quirk of the ABI, zero-width bitfields aren't ignored for fp+fp
9565 // or int+fp structs, but are ignored for a struct with an fp field and
9566 // any number of zero-width bitfields.
9567 if (Field2Ty && ZeroWidthBitFieldCount > 0)
9570 return Field1Ty != nullptr;
9576 // Determine if a struct is eligible for passing according to the floating
9577 // point calling convention (i.e., when flattened it contains a single fp
9578 // value, fp+fp, or int+fp of appropriate size). If so, NeededArgFPRs and
9579 // NeededArgGPRs are incremented appropriately.
9580 bool RISCVABIInfo::detectFPCCEligibleStruct(QualType Ty, llvm::Type *&Field1Ty,
9581 CharUnits &Field1Off,
9582 llvm::Type *&Field2Ty,
9583 CharUnits &Field2Off,
9585 int &NeededArgFPRs) const {
9590 bool IsCandidate = detectFPCCEligibleStructHelper(
9591 Ty, CharUnits::Zero(), Field1Ty, Field1Off, Field2Ty, Field2Off);
9592 // Not really a candidate if we have a single int but no float.
9593 if (Field1Ty && !Field2Ty && !Field1Ty->isFloatingPointTy())
9597 if (Field1Ty && Field1Ty->isFloatingPointTy())
9601 if (Field2Ty && Field2Ty->isFloatingPointTy())
9608 // Call getCoerceAndExpand for the two-element flattened struct described by
9609 // Field1Ty, Field1Off, Field2Ty, Field2Off. This method will create an
9610 // appropriate coerceToType and unpaddedCoerceToType.
9611 ABIArgInfo RISCVABIInfo::coerceAndExpandFPCCEligibleStruct(
9612 llvm::Type *Field1Ty, CharUnits Field1Off, llvm::Type *Field2Ty,
9613 CharUnits Field2Off) const {
9614 SmallVector<llvm::Type *, 3> CoerceElts;
9615 SmallVector<llvm::Type *, 2> UnpaddedCoerceElts;
9616 if (!Field1Off.isZero())
9617 CoerceElts.push_back(llvm::ArrayType::get(
9618 llvm::Type::getInt8Ty(getVMContext()), Field1Off.getQuantity()));
9620 CoerceElts.push_back(Field1Ty);
9621 UnpaddedCoerceElts.push_back(Field1Ty);
9624 return ABIArgInfo::getCoerceAndExpand(
9625 llvm::StructType::get(getVMContext(), CoerceElts, !Field1Off.isZero()),
9626 UnpaddedCoerceElts[0]);
9629 CharUnits Field2Align =
9630 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(Field2Ty));
9631 CharUnits Field1Size =
9632 CharUnits::fromQuantity(getDataLayout().getTypeStoreSize(Field1Ty));
9633 CharUnits Field2OffNoPadNoPack = Field1Size.alignTo(Field2Align);
9635 CharUnits Padding = CharUnits::Zero();
9636 if (Field2Off > Field2OffNoPadNoPack)
9637 Padding = Field2Off - Field2OffNoPadNoPack;
9638 else if (Field2Off != Field2Align && Field2Off > Field1Size)
9639 Padding = Field2Off - Field1Size;
9641 bool IsPacked = !Field2Off.isMultipleOf(Field2Align);
9643 if (!Padding.isZero())
9644 CoerceElts.push_back(llvm::ArrayType::get(
9645 llvm::Type::getInt8Ty(getVMContext()), Padding.getQuantity()));
9647 CoerceElts.push_back(Field2Ty);
9648 UnpaddedCoerceElts.push_back(Field2Ty);
9651 llvm::StructType::get(getVMContext(), CoerceElts, IsPacked);
9652 auto UnpaddedCoerceToType =
9653 llvm::StructType::get(getVMContext(), UnpaddedCoerceElts, IsPacked);
9655 return ABIArgInfo::getCoerceAndExpand(CoerceToType, UnpaddedCoerceToType);
9658 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
9660 int &ArgFPRsLeft) const {
9661 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
9662 Ty = useFirstFieldIfTransparentUnion(Ty);
9664 // Structures with either a non-trivial destructor or a non-trivial
9665 // copy constructor are always passed indirectly.
9666 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
9669 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
9670 CGCXXABI::RAA_DirectInMemory);
9673 // Ignore empty structs/unions.
9674 if (isEmptyRecord(getContext(), Ty, true))
9675 return ABIArgInfo::getIgnore();
9677 uint64_t Size = getContext().getTypeSize(Ty);
9679 // Pass floating point values via FPRs if possible.
9680 if (IsFixed && Ty->isFloatingType() && !Ty->isComplexType() &&
9681 FLen >= Size && ArgFPRsLeft) {
9683 return ABIArgInfo::getDirect();
9686 // Complex types for the hard float ABI must be passed direct rather than
9687 // using CoerceAndExpand.
9688 if (IsFixed && Ty->isComplexType() && FLen && ArgFPRsLeft >= 2) {
9689 QualType EltTy = Ty->castAs<ComplexType>()->getElementType();
9690 if (getContext().getTypeSize(EltTy) <= FLen) {
9692 return ABIArgInfo::getDirect();
9696 if (IsFixed && FLen && Ty->isStructureOrClassType()) {
9697 llvm::Type *Field1Ty = nullptr;
9698 llvm::Type *Field2Ty = nullptr;
9699 CharUnits Field1Off = CharUnits::Zero();
9700 CharUnits Field2Off = CharUnits::Zero();
9704 detectFPCCEligibleStruct(Ty, Field1Ty, Field1Off, Field2Ty, Field2Off,
9705 NeededArgGPRs, NeededArgFPRs);
9706 if (IsCandidate && NeededArgGPRs <= ArgGPRsLeft &&
9707 NeededArgFPRs <= ArgFPRsLeft) {
9708 ArgGPRsLeft -= NeededArgGPRs;
9709 ArgFPRsLeft -= NeededArgFPRs;
9710 return coerceAndExpandFPCCEligibleStruct(Field1Ty, Field1Off, Field2Ty,
9715 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
9716 bool MustUseStack = false;
9717 // Determine the number of GPRs needed to pass the current argument
9718 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
9719 // register pairs, so may consume 3 registers.
9720 int NeededArgGPRs = 1;
9721 if (!IsFixed && NeededAlign == 2 * XLen)
9722 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
9723 else if (Size > XLen && Size <= 2 * XLen)
9726 if (NeededArgGPRs > ArgGPRsLeft) {
9727 MustUseStack = true;
9728 NeededArgGPRs = ArgGPRsLeft;
9731 ArgGPRsLeft -= NeededArgGPRs;
9733 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
9734 // Treat an enum type as its underlying type.
9735 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
9736 Ty = EnumTy->getDecl()->getIntegerType();
9738 // All integral types are promoted to XLen width, unless passed on the
9740 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
9741 return extendType(Ty);
9744 return ABIArgInfo::getDirect();
9747 // Aggregates which are <= 2*XLen will be passed in registers if possible,
9748 // so coerce to integers.
9749 if (Size <= 2 * XLen) {
9750 unsigned Alignment = getContext().getTypeAlign(Ty);
9752 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
9753 // required, and a 2-element XLen array if only XLen alignment is required.
9755 return ABIArgInfo::getDirect(
9756 llvm::IntegerType::get(getVMContext(), XLen));
9757 } else if (Alignment == 2 * XLen) {
9758 return ABIArgInfo::getDirect(
9759 llvm::IntegerType::get(getVMContext(), 2 * XLen));
9761 return ABIArgInfo::getDirect(llvm::ArrayType::get(
9762 llvm::IntegerType::get(getVMContext(), XLen), 2));
9765 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
9768 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
9769 if (RetTy->isVoidType())
9770 return ABIArgInfo::getIgnore();
9772 int ArgGPRsLeft = 2;
9773 int ArgFPRsLeft = FLen ? 2 : 0;
9775 // The rules for return and argument types are the same, so defer to
9776 // classifyArgumentType.
9777 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft,
9781 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
9782 QualType Ty) const {
9783 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
9785 // Empty records are ignored for parameter passing purposes.
9786 if (isEmptyRecord(getContext(), Ty, true)) {
9787 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
9788 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
9792 std::pair<CharUnits, CharUnits> SizeAndAlign =
9793 getContext().getTypeInfoInChars(Ty);
9795 // Arguments bigger than 2*Xlen bytes are passed indirectly.
9796 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
9798 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
9799 SlotSize, /*AllowHigherAlign=*/true);
9802 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
9803 int TySize = getContext().getTypeSize(Ty);
9804 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
9805 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
9806 return ABIArgInfo::getSignExtend(Ty);
9807 return ABIArgInfo::getExtend(Ty);
9811 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
9813 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen,
9815 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen, FLen)) {}
9817 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
9818 CodeGen::CodeGenModule &CGM) const override {
9819 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
9822 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
9827 switch (Attr->getInterrupt()) {
9828 case RISCVInterruptAttr::user: Kind = "user"; break;
9829 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
9830 case RISCVInterruptAttr::machine: Kind = "machine"; break;
9833 auto *Fn = cast<llvm::Function>(GV);
9835 Fn->addFnAttr("interrupt", Kind);
9840 //===----------------------------------------------------------------------===//
9842 //===----------------------------------------------------------------------===//
9844 bool CodeGenModule::supportsCOMDAT() const {
9845 return getTriple().supportsCOMDAT();
9848 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
9849 if (TheTargetCodeGenInfo)
9850 return *TheTargetCodeGenInfo;
9852 // Helper to set the unique_ptr while still keeping the return value.
9853 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9854 this->TheTargetCodeGenInfo.reset(P);
9858 const llvm::Triple &Triple = getTarget().getTriple();
9859 switch (Triple.getArch()) {
9861 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
9863 case llvm::Triple::le32:
9864 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9865 case llvm::Triple::mips:
9866 case llvm::Triple::mipsel:
9867 if (Triple.getOS() == llvm::Triple::NaCl)
9868 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9869 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
9871 case llvm::Triple::mips64:
9872 case llvm::Triple::mips64el:
9873 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
9875 case llvm::Triple::avr:
9876 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9878 case llvm::Triple::aarch64:
9879 case llvm::Triple::aarch64_32:
9880 case llvm::Triple::aarch64_be: {
9881 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
9882 if (getTarget().getABI() == "darwinpcs")
9883 Kind = AArch64ABIInfo::DarwinPCS;
9884 else if (Triple.isOSWindows())
9886 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
9888 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
9891 case llvm::Triple::wasm32:
9892 case llvm::Triple::wasm64:
9893 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
9895 case llvm::Triple::arm:
9896 case llvm::Triple::armeb:
9897 case llvm::Triple::thumb:
9898 case llvm::Triple::thumbeb: {
9899 if (Triple.getOS() == llvm::Triple::Win32) {
9901 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
9904 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9905 StringRef ABIStr = getTarget().getABI();
9906 if (ABIStr == "apcs-gnu")
9907 Kind = ARMABIInfo::APCS;
9908 else if (ABIStr == "aapcs16")
9909 Kind = ARMABIInfo::AAPCS16_VFP;
9910 else if (CodeGenOpts.FloatABI == "hard" ||
9911 (CodeGenOpts.FloatABI != "soft" &&
9912 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
9913 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
9914 Triple.getEnvironment() == llvm::Triple::EABIHF)))
9915 Kind = ARMABIInfo::AAPCS_VFP;
9917 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9920 case llvm::Triple::ppc: {
9922 CodeGenOpts.FloatABI == "soft" || getTarget().hasFeature("spe");
9923 bool RetSmallStructInRegABI =
9924 PPC32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
9926 new PPC32TargetCodeGenInfo(Types, IsSoftFloat, RetSmallStructInRegABI));
9928 case llvm::Triple::ppc64:
9929 if (Triple.isOSBinFormatELF()) {
9930 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
9931 if (getTarget().getABI() == "elfv2")
9932 Kind = PPC64_SVR4_ABIInfo::ELFv2;
9933 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
9934 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
9936 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9939 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
9940 case llvm::Triple::ppc64le: {
9941 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
9942 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
9943 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
9944 Kind = PPC64_SVR4_ABIInfo::ELFv1;
9945 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
9946 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
9948 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9952 case llvm::Triple::nvptx:
9953 case llvm::Triple::nvptx64:
9954 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
9956 case llvm::Triple::msp430:
9957 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
9959 case llvm::Triple::riscv32:
9960 case llvm::Triple::riscv64: {
9961 StringRef ABIStr = getTarget().getABI();
9962 unsigned XLen = getTarget().getPointerWidth(0);
9963 unsigned ABIFLen = 0;
9964 if (ABIStr.endswith("f"))
9966 else if (ABIStr.endswith("d"))
9968 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, XLen, ABIFLen));
9971 case llvm::Triple::systemz: {
9972 bool HasVector = getTarget().getABI() == "vector";
9973 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
9976 case llvm::Triple::tce:
9977 case llvm::Triple::tcele:
9978 return SetCGInfo(new TCETargetCodeGenInfo(Types));
9980 case llvm::Triple::x86: {
9981 bool IsDarwinVectorABI = Triple.isOSDarwin();
9982 bool RetSmallStructInRegABI =
9983 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
9984 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
9986 if (Triple.getOS() == llvm::Triple::Win32) {
9987 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9988 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9989 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
9991 return SetCGInfo(new X86_32TargetCodeGenInfo(
9992 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9993 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9994 CodeGenOpts.FloatABI == "soft"));
9998 case llvm::Triple::x86_64: {
9999 StringRef ABI = getTarget().getABI();
10000 X86AVXABILevel AVXLevel =
10002 ? X86AVXABILevel::AVX512
10003 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
10005 switch (Triple.getOS()) {
10006 case llvm::Triple::Win32:
10007 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
10009 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
10012 case llvm::Triple::hexagon:
10013 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
10014 case llvm::Triple::lanai:
10015 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
10016 case llvm::Triple::r600:
10017 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10018 case llvm::Triple::amdgcn:
10019 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
10020 case llvm::Triple::sparc:
10021 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
10022 case llvm::Triple::sparcv9:
10023 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
10024 case llvm::Triple::xcore:
10025 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
10026 case llvm::Triple::arc:
10027 return SetCGInfo(new ARCTargetCodeGenInfo(Types));
10028 case llvm::Triple::spir:
10029 case llvm::Triple::spir64:
10030 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
10034 /// Create an OpenCL kernel for an enqueued block.
10036 /// The kernel has the same function type as the block invoke function. Its
10037 /// name is the name of the block invoke function postfixed with "_kernel".
10038 /// It simply calls the block invoke function then returns.
10040 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
10041 llvm::Function *Invoke,
10042 llvm::Value *BlockLiteral) const {
10043 auto *InvokeFT = Invoke->getFunctionType();
10044 llvm::SmallVector<llvm::Type *, 2> ArgTys;
10045 for (auto &P : InvokeFT->params())
10046 ArgTys.push_back(P);
10047 auto &C = CGF.getLLVMContext();
10048 std::string Name = Invoke->getName().str() + "_kernel";
10049 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10050 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10051 &CGF.CGM.getModule());
10052 auto IP = CGF.Builder.saveIP();
10053 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10054 auto &Builder = CGF.Builder;
10055 Builder.SetInsertPoint(BB);
10056 llvm::SmallVector<llvm::Value *, 2> Args;
10057 for (auto &A : F->args())
10058 Args.push_back(&A);
10059 Builder.CreateCall(Invoke, Args);
10060 Builder.CreateRetVoid();
10061 Builder.restoreIP(IP);
10065 /// Create an OpenCL kernel for an enqueued block.
10067 /// The type of the first argument (the block literal) is the struct type
10068 /// of the block literal instead of a pointer type. The first argument
10069 /// (block literal) is passed directly by value to the kernel. The kernel
10070 /// allocates the same type of struct on stack and stores the block literal
10071 /// to it and passes its pointer to the block invoke function. The kernel
10072 /// has "enqueued-block" function attribute and kernel argument metadata.
10073 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
10074 CodeGenFunction &CGF, llvm::Function *Invoke,
10075 llvm::Value *BlockLiteral) const {
10076 auto &Builder = CGF.Builder;
10077 auto &C = CGF.getLLVMContext();
10079 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
10080 auto *InvokeFT = Invoke->getFunctionType();
10081 llvm::SmallVector<llvm::Type *, 2> ArgTys;
10082 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
10083 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
10084 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
10085 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
10086 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
10087 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
10089 ArgTys.push_back(BlockTy);
10090 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10091 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
10092 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
10093 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10094 AccessQuals.push_back(llvm::MDString::get(C, "none"));
10095 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
10096 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
10097 ArgTys.push_back(InvokeFT->getParamType(I));
10098 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
10099 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
10100 AccessQuals.push_back(llvm::MDString::get(C, "none"));
10101 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
10102 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
10103 ArgNames.push_back(
10104 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
10106 std::string Name = Invoke->getName().str() + "_kernel";
10107 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
10108 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
10109 &CGF.CGM.getModule());
10110 F->addFnAttr("enqueued-block");
10111 auto IP = CGF.Builder.saveIP();
10112 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
10113 Builder.SetInsertPoint(BB);
10114 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
10115 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
10116 BlockPtr->setAlignment(llvm::MaybeAlign(BlockAlign));
10117 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
10118 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
10119 llvm::SmallVector<llvm::Value *, 2> Args;
10120 Args.push_back(Cast);
10121 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
10123 Builder.CreateCall(Invoke, Args);
10124 Builder.CreateRetVoid();
10125 Builder.restoreIP(IP);
10127 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
10128 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
10129 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
10130 F->setMetadata("kernel_arg_base_type",
10131 llvm::MDNode::get(C, ArgBaseTypeNames));
10132 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
10133 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
10134 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));