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 {
736 DefaultABIInfo defaultInfo;
740 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind)
741 : SwiftABIInfo(CGT), defaultInfo(CGT), Kind(Kind) {}
744 ABIArgInfo classifyReturnType(QualType RetTy) const;
745 ABIArgInfo classifyArgumentType(QualType Ty) const;
747 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
748 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
750 void computeInfo(CGFunctionInfo &FI) const override {
751 if (!getCXXABI().classifyReturnType(FI))
752 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
753 for (auto &Arg : FI.arguments())
754 Arg.info = classifyArgumentType(Arg.type);
757 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
758 QualType Ty) const override;
760 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
761 bool asReturnValue) const override {
762 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
765 bool isSwiftErrorInRegister() const override {
770 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
772 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
773 WebAssemblyABIInfo::ABIKind K)
774 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT, K)) {}
776 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
777 CodeGen::CodeGenModule &CGM) const override {
778 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
779 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
780 if (const auto *Attr = FD->getAttr<WebAssemblyImportModuleAttr>()) {
781 llvm::Function *Fn = cast<llvm::Function>(GV);
783 B.addAttribute("wasm-import-module", Attr->getImportModule());
784 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
786 if (const auto *Attr = FD->getAttr<WebAssemblyImportNameAttr>()) {
787 llvm::Function *Fn = cast<llvm::Function>(GV);
789 B.addAttribute("wasm-import-name", Attr->getImportName());
790 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
792 if (const auto *Attr = FD->getAttr<WebAssemblyExportNameAttr>()) {
793 llvm::Function *Fn = cast<llvm::Function>(GV);
795 B.addAttribute("wasm-export-name", Attr->getExportName());
796 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
800 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
801 llvm::Function *Fn = cast<llvm::Function>(GV);
802 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
803 Fn->addFnAttr("no-prototype");
808 /// Classify argument of given type \p Ty.
809 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
810 Ty = useFirstFieldIfTransparentUnion(Ty);
812 if (isAggregateTypeForABI(Ty)) {
813 // Records with non-trivial destructors/copy-constructors should not be
815 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
816 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
817 // Ignore empty structs/unions.
818 if (isEmptyRecord(getContext(), Ty, true))
819 return ABIArgInfo::getIgnore();
820 // Lower single-element structs to just pass a regular value. TODO: We
821 // could do reasonable-size multiple-element structs too, using getExpand(),
822 // though watch out for things like bitfields.
823 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
824 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
825 // For the experimental multivalue ABI, fully expand all other aggregates
826 if (Kind == ABIKind::ExperimentalMV) {
827 const RecordType *RT = Ty->getAs<RecordType>();
829 bool HasBitField = false;
830 for (auto *Field : RT->getDecl()->fields()) {
831 if (Field->isBitField()) {
837 return ABIArgInfo::getExpand();
841 // Otherwise just do the default thing.
842 return defaultInfo.classifyArgumentType(Ty);
845 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
846 if (isAggregateTypeForABI(RetTy)) {
847 // Records with non-trivial destructors/copy-constructors should not be
848 // returned by value.
849 if (!getRecordArgABI(RetTy, getCXXABI())) {
850 // Ignore empty structs/unions.
851 if (isEmptyRecord(getContext(), RetTy, true))
852 return ABIArgInfo::getIgnore();
853 // Lower single-element structs to just return a regular value. TODO: We
854 // could do reasonable-size multiple-element structs too, using
855 // ABIArgInfo::getDirect().
856 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
857 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
858 // For the experimental multivalue ABI, return all other aggregates
859 if (Kind == ABIKind::ExperimentalMV)
860 return ABIArgInfo::getDirect();
864 // Otherwise just do the default thing.
865 return defaultInfo.classifyReturnType(RetTy);
868 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
870 bool IsIndirect = isAggregateTypeForABI(Ty) &&
871 !isEmptyRecord(getContext(), Ty, true) &&
872 !isSingleElementStruct(Ty, getContext());
873 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
874 getContext().getTypeInfoInChars(Ty),
875 CharUnits::fromQuantity(4),
876 /*AllowHigherAlign=*/true);
879 //===----------------------------------------------------------------------===//
880 // le32/PNaCl bitcode ABI Implementation
882 // This is a simplified version of the x86_32 ABI. Arguments and return values
883 // are always passed on the stack.
884 //===----------------------------------------------------------------------===//
886 class PNaClABIInfo : public ABIInfo {
888 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
890 ABIArgInfo classifyReturnType(QualType RetTy) const;
891 ABIArgInfo classifyArgumentType(QualType RetTy) const;
893 void computeInfo(CGFunctionInfo &FI) const override;
894 Address EmitVAArg(CodeGenFunction &CGF,
895 Address VAListAddr, QualType Ty) const override;
898 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
900 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
901 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
904 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
905 if (!getCXXABI().classifyReturnType(FI))
906 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
908 for (auto &I : FI.arguments())
909 I.info = classifyArgumentType(I.type);
912 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
914 // The PNaCL ABI is a bit odd, in that varargs don't use normal
915 // function classification. Structs get passed directly for varargs
916 // functions, through a rewriting transform in
917 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
918 // this target to actually support a va_arg instructions with an
919 // aggregate type, unlike other targets.
920 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
923 /// Classify argument of given type \p Ty.
924 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
925 if (isAggregateTypeForABI(Ty)) {
926 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
927 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
928 return getNaturalAlignIndirect(Ty);
929 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
930 // Treat an enum type as its underlying type.
931 Ty = EnumTy->getDecl()->getIntegerType();
932 } else if (Ty->isFloatingType()) {
933 // Floating-point types don't go inreg.
934 return ABIArgInfo::getDirect();
937 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
938 : ABIArgInfo::getDirect());
941 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
942 if (RetTy->isVoidType())
943 return ABIArgInfo::getIgnore();
945 // In the PNaCl ABI we always return records/structures on the stack.
946 if (isAggregateTypeForABI(RetTy))
947 return getNaturalAlignIndirect(RetTy);
949 // Treat an enum type as its underlying type.
950 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
951 RetTy = EnumTy->getDecl()->getIntegerType();
953 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
954 : ABIArgInfo::getDirect());
957 /// IsX86_MMXType - Return true if this is an MMX type.
958 bool IsX86_MMXType(llvm::Type *IRType) {
959 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
960 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
961 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
962 IRType->getScalarSizeInBits() != 64;
965 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
966 StringRef Constraint,
968 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
969 .Cases("y", "&y", "^Ym", true)
971 if (IsMMXCons && Ty->isVectorTy()) {
972 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
973 // Invalid MMX constraint
977 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
980 // No operation needed
984 /// Returns true if this type can be passed in SSE registers with the
985 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
986 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
987 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
988 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
989 if (BT->getKind() == BuiltinType::LongDouble) {
990 if (&Context.getTargetInfo().getLongDoubleFormat() ==
991 &llvm::APFloat::x87DoubleExtended())
996 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
997 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
998 // registers specially.
999 unsigned VecSize = Context.getTypeSize(VT);
1000 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
1006 /// Returns true if this aggregate is small enough to be passed in SSE registers
1007 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
1008 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
1009 return NumMembers <= 4;
1012 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
1013 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
1014 auto AI = ABIArgInfo::getDirect(T);
1016 AI.setCanBeFlattened(false);
1020 //===----------------------------------------------------------------------===//
1021 // X86-32 ABI Implementation
1022 //===----------------------------------------------------------------------===//
1024 /// Similar to llvm::CCState, but for Clang.
1026 CCState(CGFunctionInfo &FI)
1027 : IsPreassigned(FI.arg_size()), CC(FI.getCallingConvention()) {}
1029 llvm::SmallBitVector IsPreassigned;
1030 unsigned CC = CallingConv::CC_C;
1031 unsigned FreeRegs = 0;
1032 unsigned FreeSSERegs = 0;
1036 // Vectorcall only allows the first 6 parameters to be passed in registers.
1037 VectorcallMaxParamNumAsReg = 6
1040 /// X86_32ABIInfo - The X86-32 ABI information.
1041 class X86_32ABIInfo : public SwiftABIInfo {
1047 static const unsigned MinABIStackAlignInBytes = 4;
1049 bool IsDarwinVectorABI;
1050 bool IsRetSmallStructInRegABI;
1051 bool IsWin32StructABI;
1052 bool IsSoftFloatABI;
1054 unsigned DefaultNumRegisterParameters;
1056 static bool isRegisterSize(unsigned Size) {
1057 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
1060 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
1061 // FIXME: Assumes vectorcall is in use.
1062 return isX86VectorTypeForVectorCall(getContext(), Ty);
1065 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
1066 uint64_t NumMembers) const override {
1067 // FIXME: Assumes vectorcall is in use.
1068 return isX86VectorCallAggregateSmallEnough(NumMembers);
1071 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1073 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1074 /// such that the argument will be passed in memory.
1075 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1077 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1079 /// Return the alignment to use for the given type on the stack.
1080 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1082 Class classify(QualType Ty) const;
1083 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1084 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1086 /// Updates the number of available free registers, returns
1087 /// true if any registers were allocated.
1088 bool updateFreeRegs(QualType Ty, CCState &State) const;
1090 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1091 bool &NeedsPadding) const;
1092 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1094 bool canExpandIndirectArgument(QualType Ty) const;
1096 /// Rewrite the function info so that all memory arguments use
1098 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1100 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1101 CharUnits &StackOffset, ABIArgInfo &Info,
1102 QualType Type) const;
1103 void runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const;
1107 void computeInfo(CGFunctionInfo &FI) const override;
1108 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1109 QualType Ty) const override;
1111 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1112 bool RetSmallStructInRegABI, bool Win32StructABI,
1113 unsigned NumRegisterParameters, bool SoftFloatABI)
1114 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1115 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1116 IsWin32StructABI(Win32StructABI),
1117 IsSoftFloatABI(SoftFloatABI),
1118 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1119 DefaultNumRegisterParameters(NumRegisterParameters) {}
1121 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1122 bool asReturnValue) const override {
1123 // LLVM's x86-32 lowering currently only assigns up to three
1124 // integer registers and three fp registers. Oddly, it'll use up to
1125 // four vector registers for vectors, but those can overlap with the
1126 // scalar registers.
1127 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1130 bool isSwiftErrorInRegister() const override {
1131 // x86-32 lowering does not support passing swifterror in a register.
1136 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1138 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1139 bool RetSmallStructInRegABI, bool Win32StructABI,
1140 unsigned NumRegisterParameters, bool SoftFloatABI)
1141 : TargetCodeGenInfo(new X86_32ABIInfo(
1142 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1143 NumRegisterParameters, SoftFloatABI)) {}
1145 static bool isStructReturnInRegABI(
1146 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1148 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1149 CodeGen::CodeGenModule &CGM) const override;
1151 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1152 // Darwin uses different dwarf register numbers for EH.
1153 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1157 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1158 llvm::Value *Address) const override;
1160 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1161 StringRef Constraint,
1162 llvm::Type* Ty) const override {
1163 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1166 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1167 std::string &Constraints,
1168 std::vector<llvm::Type *> &ResultRegTypes,
1169 std::vector<llvm::Type *> &ResultTruncRegTypes,
1170 std::vector<LValue> &ResultRegDests,
1171 std::string &AsmString,
1172 unsigned NumOutputs) const override;
1175 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1176 unsigned Sig = (0xeb << 0) | // jmp rel8
1177 (0x06 << 8) | // .+0x08
1180 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1183 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1184 return "movl\t%ebp, %ebp"
1185 "\t\t// marker for objc_retainAutoreleaseReturnValue";
1191 /// Rewrite input constraint references after adding some output constraints.
1192 /// In the case where there is one output and one input and we add one output,
1193 /// we need to replace all operand references greater than or equal to 1:
1196 /// The result will be:
1199 static void rewriteInputConstraintReferences(unsigned FirstIn,
1200 unsigned NumNewOuts,
1201 std::string &AsmString) {
1203 llvm::raw_string_ostream OS(Buf);
1205 while (Pos < AsmString.size()) {
1206 size_t DollarStart = AsmString.find('$', Pos);
1207 if (DollarStart == std::string::npos)
1208 DollarStart = AsmString.size();
1209 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1210 if (DollarEnd == std::string::npos)
1211 DollarEnd = AsmString.size();
1212 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1214 size_t NumDollars = DollarEnd - DollarStart;
1215 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1216 // We have an operand reference.
1217 size_t DigitStart = Pos;
1218 if (AsmString[DigitStart] == '{') {
1222 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1223 if (DigitEnd == std::string::npos)
1224 DigitEnd = AsmString.size();
1225 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1226 unsigned OperandIndex;
1227 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1228 if (OperandIndex >= FirstIn)
1229 OperandIndex += NumNewOuts;
1237 AsmString = std::move(OS.str());
1240 /// Add output constraints for EAX:EDX because they are return registers.
1241 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1242 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1243 std::vector<llvm::Type *> &ResultRegTypes,
1244 std::vector<llvm::Type *> &ResultTruncRegTypes,
1245 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1246 unsigned NumOutputs) const {
1247 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1249 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1251 if (!Constraints.empty())
1253 if (RetWidth <= 32) {
1254 Constraints += "={eax}";
1255 ResultRegTypes.push_back(CGF.Int32Ty);
1257 // Use the 'A' constraint for EAX:EDX.
1258 Constraints += "=A";
1259 ResultRegTypes.push_back(CGF.Int64Ty);
1262 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1263 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1264 ResultTruncRegTypes.push_back(CoerceTy);
1266 // Coerce the integer by bitcasting the return slot pointer.
1267 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(CGF),
1268 CoerceTy->getPointerTo()));
1269 ResultRegDests.push_back(ReturnSlot);
1271 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1274 /// shouldReturnTypeInRegister - Determine if the given type should be
1275 /// returned in a register (for the Darwin and MCU ABI).
1276 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1277 ASTContext &Context) const {
1278 uint64_t Size = Context.getTypeSize(Ty);
1280 // For i386, type must be register sized.
1281 // For the MCU ABI, it only needs to be <= 8-byte
1282 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1285 if (Ty->isVectorType()) {
1286 // 64- and 128- bit vectors inside structures are not returned in
1288 if (Size == 64 || Size == 128)
1294 // If this is a builtin, pointer, enum, complex type, member pointer, or
1295 // member function pointer it is ok.
1296 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1297 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1298 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1301 // Arrays are treated like records.
1302 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1303 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1305 // Otherwise, it must be a record type.
1306 const RecordType *RT = Ty->getAs<RecordType>();
1307 if (!RT) return false;
1309 // FIXME: Traverse bases here too.
1311 // Structure types are passed in register if all fields would be
1312 // passed in a register.
1313 for (const auto *FD : RT->getDecl()->fields()) {
1314 // Empty fields are ignored.
1315 if (isEmptyField(Context, FD, true))
1318 // Check fields recursively.
1319 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1325 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1326 // Treat complex types as the element type.
1327 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1328 Ty = CTy->getElementType();
1330 // Check for a type which we know has a simple scalar argument-passing
1331 // convention without any padding. (We're specifically looking for 32
1332 // and 64-bit integer and integer-equivalents, float, and double.)
1333 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1334 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1337 uint64_t Size = Context.getTypeSize(Ty);
1338 return Size == 32 || Size == 64;
1341 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1343 for (const auto *FD : RD->fields()) {
1344 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1345 // argument is smaller than 32-bits, expanding the struct will create
1346 // alignment padding.
1347 if (!is32Or64BitBasicType(FD->getType(), Context))
1350 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1351 // how to expand them yet, and the predicate for telling if a bitfield still
1352 // counts as "basic" is more complicated than what we were doing previously.
1353 if (FD->isBitField())
1356 Size += Context.getTypeSize(FD->getType());
1361 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1363 // Don't do this if there are any non-empty bases.
1364 for (const CXXBaseSpecifier &Base : RD->bases()) {
1365 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1369 if (!addFieldSizes(Context, RD, Size))
1374 /// Test whether an argument type which is to be passed indirectly (on the
1375 /// stack) would have the equivalent layout if it was expanded into separate
1376 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1378 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1379 // We can only expand structure types.
1380 const RecordType *RT = Ty->getAs<RecordType>();
1383 const RecordDecl *RD = RT->getDecl();
1385 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1386 if (!IsWin32StructABI) {
1387 // On non-Windows, we have to conservatively match our old bitcode
1388 // prototypes in order to be ABI-compatible at the bitcode level.
1389 if (!CXXRD->isCLike())
1392 // Don't do this for dynamic classes.
1393 if (CXXRD->isDynamicClass())
1396 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1399 if (!addFieldSizes(getContext(), RD, Size))
1403 // We can do this if there was no alignment padding.
1404 return Size == getContext().getTypeSize(Ty);
1407 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1408 // If the return value is indirect, then the hidden argument is consuming one
1409 // integer register.
1410 if (State.FreeRegs) {
1413 return getNaturalAlignIndirectInReg(RetTy);
1415 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1418 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1419 CCState &State) const {
1420 if (RetTy->isVoidType())
1421 return ABIArgInfo::getIgnore();
1423 const Type *Base = nullptr;
1424 uint64_t NumElts = 0;
1425 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1426 State.CC == llvm::CallingConv::X86_RegCall) &&
1427 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1428 // The LLVM struct type for such an aggregate should lower properly.
1429 return ABIArgInfo::getDirect();
1432 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1433 // On Darwin, some vectors are returned in registers.
1434 if (IsDarwinVectorABI) {
1435 uint64_t Size = getContext().getTypeSize(RetTy);
1437 // 128-bit vectors are a special case; they are returned in
1438 // registers and we need to make sure to pick a type the LLVM
1439 // backend will like.
1441 return ABIArgInfo::getDirect(llvm::VectorType::get(
1442 llvm::Type::getInt64Ty(getVMContext()), 2));
1444 // Always return in register if it fits in a general purpose
1445 // register, or if it is 64 bits and has a single element.
1446 if ((Size == 8 || Size == 16 || Size == 32) ||
1447 (Size == 64 && VT->getNumElements() == 1))
1448 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1451 return getIndirectReturnResult(RetTy, State);
1454 return ABIArgInfo::getDirect();
1457 if (isAggregateTypeForABI(RetTy)) {
1458 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1459 // Structures with flexible arrays are always indirect.
1460 if (RT->getDecl()->hasFlexibleArrayMember())
1461 return getIndirectReturnResult(RetTy, State);
1464 // If specified, structs and unions are always indirect.
1465 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1466 return getIndirectReturnResult(RetTy, State);
1468 // Ignore empty structs/unions.
1469 if (isEmptyRecord(getContext(), RetTy, true))
1470 return ABIArgInfo::getIgnore();
1472 // Small structures which are register sized are generally returned
1474 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1475 uint64_t Size = getContext().getTypeSize(RetTy);
1477 // As a special-case, if the struct is a "single-element" struct, and
1478 // the field is of type "float" or "double", return it in a
1479 // floating-point register. (MSVC does not apply this special case.)
1480 // We apply a similar transformation for pointer types to improve the
1481 // quality of the generated IR.
1482 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1483 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1484 || SeltTy->hasPointerRepresentation())
1485 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1487 // FIXME: We should be able to narrow this integer in cases with dead
1489 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1492 return getIndirectReturnResult(RetTy, State);
1495 // Treat an enum type as its underlying type.
1496 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1497 RetTy = EnumTy->getDecl()->getIntegerType();
1499 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1500 : ABIArgInfo::getDirect());
1503 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1504 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1507 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1508 const RecordType *RT = Ty->getAs<RecordType>();
1511 const RecordDecl *RD = RT->getDecl();
1513 // If this is a C++ record, check the bases first.
1514 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1515 for (const auto &I : CXXRD->bases())
1516 if (!isRecordWithSSEVectorType(Context, I.getType()))
1519 for (const auto *i : RD->fields()) {
1520 QualType FT = i->getType();
1522 if (isSSEVectorType(Context, FT))
1525 if (isRecordWithSSEVectorType(Context, FT))
1532 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1533 unsigned Align) const {
1534 // Otherwise, if the alignment is less than or equal to the minimum ABI
1535 // alignment, just use the default; the backend will handle this.
1536 if (Align <= MinABIStackAlignInBytes)
1537 return 0; // Use default alignment.
1539 // On non-Darwin, the stack type alignment is always 4.
1540 if (!IsDarwinVectorABI) {
1541 // Set explicit alignment, since we may need to realign the top.
1542 return MinABIStackAlignInBytes;
1545 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1546 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1547 isRecordWithSSEVectorType(getContext(), Ty)))
1550 return MinABIStackAlignInBytes;
1553 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1554 CCState &State) const {
1556 if (State.FreeRegs) {
1557 --State.FreeRegs; // Non-byval indirects just use one pointer.
1559 return getNaturalAlignIndirectInReg(Ty);
1561 return getNaturalAlignIndirect(Ty, false);
1564 // Compute the byval alignment.
1565 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1566 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1567 if (StackAlign == 0)
1568 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1570 // If the stack alignment is less than the type alignment, realign the
1572 bool Realign = TypeAlign > StackAlign;
1573 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1574 /*ByVal=*/true, Realign);
1577 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1578 const Type *T = isSingleElementStruct(Ty, getContext());
1580 T = Ty.getTypePtr();
1582 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1583 BuiltinType::Kind K = BT->getKind();
1584 if (K == BuiltinType::Float || K == BuiltinType::Double)
1590 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1591 if (!IsSoftFloatABI) {
1592 Class C = classify(Ty);
1597 unsigned Size = getContext().getTypeSize(Ty);
1598 unsigned SizeInRegs = (Size + 31) / 32;
1600 if (SizeInRegs == 0)
1604 if (SizeInRegs > State.FreeRegs) {
1609 // The MCU psABI allows passing parameters in-reg even if there are
1610 // earlier parameters that are passed on the stack. Also,
1611 // it does not allow passing >8-byte structs in-register,
1612 // even if there are 3 free registers available.
1613 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1617 State.FreeRegs -= SizeInRegs;
1621 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1623 bool &NeedsPadding) const {
1624 // On Windows, aggregates other than HFAs are never passed in registers, and
1625 // they do not consume register slots. Homogenous floating-point aggregates
1626 // (HFAs) have already been dealt with at this point.
1627 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1630 NeedsPadding = false;
1633 if (!updateFreeRegs(Ty, State))
1639 if (State.CC == llvm::CallingConv::X86_FastCall ||
1640 State.CC == llvm::CallingConv::X86_VectorCall ||
1641 State.CC == llvm::CallingConv::X86_RegCall) {
1642 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1643 NeedsPadding = true;
1651 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1652 if (!updateFreeRegs(Ty, State))
1658 if (State.CC == llvm::CallingConv::X86_FastCall ||
1659 State.CC == llvm::CallingConv::X86_VectorCall ||
1660 State.CC == llvm::CallingConv::X86_RegCall) {
1661 if (getContext().getTypeSize(Ty) > 32)
1664 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1665 Ty->isReferenceType());
1671 void X86_32ABIInfo::runVectorCallFirstPass(CGFunctionInfo &FI, CCState &State) const {
1672 // Vectorcall x86 works subtly different than in x64, so the format is
1673 // a bit different than the x64 version. First, all vector types (not HVAs)
1674 // are assigned, with the first 6 ending up in the [XYZ]MM0-5 registers.
1675 // This differs from the x64 implementation, where the first 6 by INDEX get
1677 // In the second pass over the arguments, HVAs are passed in the remaining
1678 // vector registers if possible, or indirectly by address. The address will be
1679 // passed in ECX/EDX if available. Any other arguments are passed according to
1680 // the usual fastcall rules.
1681 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1682 for (int I = 0, E = Args.size(); I < E; ++I) {
1683 const Type *Base = nullptr;
1684 uint64_t NumElts = 0;
1685 const QualType &Ty = Args[I].type;
1686 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1687 isHomogeneousAggregate(Ty, Base, NumElts)) {
1688 if (State.FreeSSERegs >= NumElts) {
1689 State.FreeSSERegs -= NumElts;
1690 Args[I].info = ABIArgInfo::getDirectInReg();
1691 State.IsPreassigned.set(I);
1697 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1698 CCState &State) const {
1699 // FIXME: Set alignment on indirect arguments.
1700 bool IsFastCall = State.CC == llvm::CallingConv::X86_FastCall;
1701 bool IsRegCall = State.CC == llvm::CallingConv::X86_RegCall;
1702 bool IsVectorCall = State.CC == llvm::CallingConv::X86_VectorCall;
1704 Ty = useFirstFieldIfTransparentUnion(Ty);
1705 TypeInfo TI = getContext().getTypeInfo(Ty);
1707 // Check with the C++ ABI first.
1708 const RecordType *RT = Ty->getAs<RecordType>();
1710 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1711 if (RAA == CGCXXABI::RAA_Indirect) {
1712 return getIndirectResult(Ty, false, State);
1713 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1714 // The field index doesn't matter, we'll fix it up later.
1715 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1719 // Regcall uses the concept of a homogenous vector aggregate, similar
1720 // to other targets.
1721 const Type *Base = nullptr;
1722 uint64_t NumElts = 0;
1723 if ((IsRegCall || IsVectorCall) &&
1724 isHomogeneousAggregate(Ty, Base, NumElts)) {
1725 if (State.FreeSSERegs >= NumElts) {
1726 State.FreeSSERegs -= NumElts;
1728 // Vectorcall passes HVAs directly and does not flatten them, but regcall
1731 return getDirectX86Hva();
1733 if (Ty->isBuiltinType() || Ty->isVectorType())
1734 return ABIArgInfo::getDirect();
1735 return ABIArgInfo::getExpand();
1737 return getIndirectResult(Ty, /*ByVal=*/false, State);
1740 if (isAggregateTypeForABI(Ty)) {
1741 // Structures with flexible arrays are always indirect.
1742 // FIXME: This should not be byval!
1743 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1744 return getIndirectResult(Ty, true, State);
1746 // Ignore empty structs/unions on non-Windows.
1747 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1748 return ABIArgInfo::getIgnore();
1750 llvm::LLVMContext &LLVMContext = getVMContext();
1751 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1752 bool NeedsPadding = false;
1754 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1755 unsigned SizeInRegs = (TI.Width + 31) / 32;
1756 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1757 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1759 return ABIArgInfo::getDirectInReg(Result);
1761 return ABIArgInfo::getDirect(Result);
1763 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1765 // Pass over-aligned aggregates on Windows indirectly. This behavior was
1766 // added in MSVC 2015.
1767 if (IsWin32StructABI && TI.AlignIsRequired && TI.Align > 32)
1768 return getIndirectResult(Ty, /*ByVal=*/false, State);
1770 // Expand small (<= 128-bit) record types when we know that the stack layout
1771 // of those arguments will match the struct. This is important because the
1772 // LLVM backend isn't smart enough to remove byval, which inhibits many
1774 // Don't do this for the MCU if there are still free integer registers
1775 // (see X86_64 ABI for full explanation).
1776 if (TI.Width <= 4 * 32 && (!IsMCUABI || State.FreeRegs == 0) &&
1777 canExpandIndirectArgument(Ty))
1778 return ABIArgInfo::getExpandWithPadding(
1779 IsFastCall || IsVectorCall || IsRegCall, PaddingType);
1781 return getIndirectResult(Ty, true, State);
1784 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1785 // On Windows, vectors are passed directly if registers are available, or
1786 // indirectly if not. This avoids the need to align argument memory. Pass
1787 // user-defined vector types larger than 512 bits indirectly for simplicity.
1788 if (IsWin32StructABI) {
1789 if (TI.Width <= 512 && State.FreeSSERegs > 0) {
1790 --State.FreeSSERegs;
1791 return ABIArgInfo::getDirectInReg();
1793 return getIndirectResult(Ty, /*ByVal=*/false, State);
1796 // On Darwin, some vectors are passed in memory, we handle this by passing
1797 // it as an i8/i16/i32/i64.
1798 if (IsDarwinVectorABI) {
1799 if ((TI.Width == 8 || TI.Width == 16 || TI.Width == 32) ||
1800 (TI.Width == 64 && VT->getNumElements() == 1))
1801 return ABIArgInfo::getDirect(
1802 llvm::IntegerType::get(getVMContext(), TI.Width));
1805 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1806 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1808 return ABIArgInfo::getDirect();
1812 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1813 Ty = EnumTy->getDecl()->getIntegerType();
1815 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1817 if (Ty->isPromotableIntegerType()) {
1819 return ABIArgInfo::getExtendInReg(Ty);
1820 return ABIArgInfo::getExtend(Ty);
1824 return ABIArgInfo::getDirectInReg();
1825 return ABIArgInfo::getDirect();
1828 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1832 else if (State.CC == llvm::CallingConv::X86_FastCall) {
1834 State.FreeSSERegs = 3;
1835 } else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1837 State.FreeSSERegs = 6;
1838 } else if (FI.getHasRegParm())
1839 State.FreeRegs = FI.getRegParm();
1840 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1842 State.FreeSSERegs = 8;
1843 } else if (IsWin32StructABI) {
1844 // Since MSVC 2015, the first three SSE vectors have been passed in
1845 // registers. The rest are passed indirectly.
1846 State.FreeRegs = DefaultNumRegisterParameters;
1847 State.FreeSSERegs = 3;
1849 State.FreeRegs = DefaultNumRegisterParameters;
1851 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1852 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1853 } else if (FI.getReturnInfo().isIndirect()) {
1854 // The C++ ABI is not aware of register usage, so we have to check if the
1855 // return value was sret and put it in a register ourselves if appropriate.
1856 if (State.FreeRegs) {
1857 --State.FreeRegs; // The sret parameter consumes a register.
1859 FI.getReturnInfo().setInReg(true);
1863 // The chain argument effectively gives us another free register.
1864 if (FI.isChainCall())
1867 // For vectorcall, do a first pass over the arguments, assigning FP and vector
1868 // arguments to XMM registers as available.
1869 if (State.CC == llvm::CallingConv::X86_VectorCall)
1870 runVectorCallFirstPass(FI, State);
1872 bool UsedInAlloca = false;
1873 MutableArrayRef<CGFunctionInfoArgInfo> Args = FI.arguments();
1874 for (int I = 0, E = Args.size(); I < E; ++I) {
1875 // Skip arguments that have already been assigned.
1876 if (State.IsPreassigned.test(I))
1879 Args[I].info = classifyArgumentType(Args[I].type, State);
1880 UsedInAlloca |= (Args[I].info.getKind() == ABIArgInfo::InAlloca);
1883 // If we needed to use inalloca for any argument, do a second pass and rewrite
1884 // all the memory arguments to use inalloca.
1886 rewriteWithInAlloca(FI);
1890 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1891 CharUnits &StackOffset, ABIArgInfo &Info,
1892 QualType Type) const {
1893 // Arguments are always 4-byte-aligned.
1894 CharUnits WordSize = CharUnits::fromQuantity(4);
1895 assert(StackOffset.isMultipleOf(WordSize) && "unaligned inalloca struct");
1897 // sret pointers and indirect things will require an extra pointer
1898 // indirection, unless they are byval. Most things are byval, and will not
1899 // require this indirection.
1900 bool IsIndirect = false;
1901 if (Info.isIndirect() && !Info.getIndirectByVal())
1903 Info = ABIArgInfo::getInAlloca(FrameFields.size(), IsIndirect);
1904 llvm::Type *LLTy = CGT.ConvertTypeForMem(Type);
1906 LLTy = LLTy->getPointerTo(0);
1907 FrameFields.push_back(LLTy);
1908 StackOffset += IsIndirect ? WordSize : getContext().getTypeSizeInChars(Type);
1910 // Insert padding bytes to respect alignment.
1911 CharUnits FieldEnd = StackOffset;
1912 StackOffset = FieldEnd.alignTo(WordSize);
1913 if (StackOffset != FieldEnd) {
1914 CharUnits NumBytes = StackOffset - FieldEnd;
1915 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1916 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1917 FrameFields.push_back(Ty);
1921 static bool isArgInAlloca(const ABIArgInfo &Info) {
1922 // Leave ignored and inreg arguments alone.
1923 switch (Info.getKind()) {
1924 case ABIArgInfo::InAlloca:
1926 case ABIArgInfo::Ignore:
1928 case ABIArgInfo::Indirect:
1929 case ABIArgInfo::Direct:
1930 case ABIArgInfo::Extend:
1931 return !Info.getInReg();
1932 case ABIArgInfo::Expand:
1933 case ABIArgInfo::CoerceAndExpand:
1934 // These are aggregate types which are never passed in registers when
1935 // inalloca is involved.
1938 llvm_unreachable("invalid enum");
1941 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1942 assert(IsWin32StructABI && "inalloca only supported on win32");
1944 // Build a packed struct type for all of the arguments in memory.
1945 SmallVector<llvm::Type *, 6> FrameFields;
1947 // The stack alignment is always 4.
1948 CharUnits StackAlign = CharUnits::fromQuantity(4);
1950 CharUnits StackOffset;
1951 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1953 // Put 'this' into the struct before 'sret', if necessary.
1955 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1956 ABIArgInfo &Ret = FI.getReturnInfo();
1957 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1958 isArgInAlloca(I->info)) {
1959 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1963 // Put the sret parameter into the inalloca struct if it's in memory.
1964 if (Ret.isIndirect() && !Ret.getInReg()) {
1965 addFieldToArgStruct(FrameFields, StackOffset, Ret, FI.getReturnType());
1966 // On Windows, the hidden sret parameter is always returned in eax.
1967 Ret.setInAllocaSRet(IsWin32StructABI);
1970 // Skip the 'this' parameter in ecx.
1974 // Put arguments passed in memory into the struct.
1975 for (; I != E; ++I) {
1976 if (isArgInAlloca(I->info))
1977 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1980 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1985 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1986 Address VAListAddr, QualType Ty) const {
1988 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1990 // x86-32 changes the alignment of certain arguments on the stack.
1992 // Just messing with TypeInfo like this works because we never pass
1993 // anything indirectly.
1994 TypeInfo.second = CharUnits::fromQuantity(
1995 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1997 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1998 TypeInfo, CharUnits::fromQuantity(4),
1999 /*AllowHigherAlign*/ true);
2002 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
2003 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
2004 assert(Triple.getArch() == llvm::Triple::x86);
2006 switch (Opts.getStructReturnConvention()) {
2007 case CodeGenOptions::SRCK_Default:
2009 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
2011 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
2015 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
2018 switch (Triple.getOS()) {
2019 case llvm::Triple::DragonFly:
2020 case llvm::Triple::FreeBSD:
2021 case llvm::Triple::OpenBSD:
2022 case llvm::Triple::Win32:
2029 void X86_32TargetCodeGenInfo::setTargetAttributes(
2030 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2031 if (GV->isDeclaration())
2033 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2034 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2035 llvm::Function *Fn = cast<llvm::Function>(GV);
2036 Fn->addFnAttr("stackrealign");
2038 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2039 llvm::Function *Fn = cast<llvm::Function>(GV);
2040 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2045 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
2046 CodeGen::CodeGenFunction &CGF,
2047 llvm::Value *Address) const {
2048 CodeGen::CGBuilderTy &Builder = CGF.Builder;
2050 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
2052 // 0-7 are the eight integer registers; the order is different
2053 // on Darwin (for EH), but the range is the same.
2055 AssignToArrayRange(Builder, Address, Four8, 0, 8);
2057 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
2058 // 12-16 are st(0..4). Not sure why we stop at 4.
2059 // These have size 16, which is sizeof(long double) on
2060 // platforms with 8-byte alignment for that type.
2061 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
2062 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
2065 // 9 is %eflags, which doesn't get a size on Darwin for some
2067 Builder.CreateAlignedStore(
2068 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
2071 // 11-16 are st(0..5). Not sure why we stop at 5.
2072 // These have size 12, which is sizeof(long double) on
2073 // platforms with 4-byte alignment for that type.
2074 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
2075 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
2081 //===----------------------------------------------------------------------===//
2082 // X86-64 ABI Implementation
2083 //===----------------------------------------------------------------------===//
2087 /// The AVX ABI level for X86 targets.
2088 enum class X86AVXABILevel {
2094 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2095 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2097 case X86AVXABILevel::AVX512:
2099 case X86AVXABILevel::AVX:
2101 case X86AVXABILevel::None:
2104 llvm_unreachable("Unknown AVXLevel");
2107 /// X86_64ABIInfo - The X86_64 ABI information.
2108 class X86_64ABIInfo : public SwiftABIInfo {
2120 /// merge - Implement the X86_64 ABI merging algorithm.
2122 /// Merge an accumulating classification \arg Accum with a field
2123 /// classification \arg Field.
2125 /// \param Accum - The accumulating classification. This should
2126 /// always be either NoClass or the result of a previous merge
2127 /// call. In addition, this should never be Memory (the caller
2128 /// should just return Memory for the aggregate).
2129 static Class merge(Class Accum, Class Field);
2131 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2133 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2134 /// final MEMORY or SSE classes when necessary.
2136 /// \param AggregateSize - The size of the current aggregate in
2137 /// the classification process.
2139 /// \param Lo - The classification for the parts of the type
2140 /// residing in the low word of the containing object.
2142 /// \param Hi - The classification for the parts of the type
2143 /// residing in the higher words of the containing object.
2145 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2147 /// classify - Determine the x86_64 register classes in which the
2148 /// given type T should be passed.
2150 /// \param Lo - The classification for the parts of the type
2151 /// residing in the low word of the containing object.
2153 /// \param Hi - The classification for the parts of the type
2154 /// residing in the high word of the containing object.
2156 /// \param OffsetBase - The bit offset of this type in the
2157 /// containing object. Some parameters are classified different
2158 /// depending on whether they straddle an eightbyte boundary.
2160 /// \param isNamedArg - Whether the argument in question is a "named"
2161 /// argument, as used in AMD64-ABI 3.5.7.
2163 /// If a word is unused its result will be NoClass; if a type should
2164 /// be passed in Memory then at least the classification of \arg Lo
2167 /// The \arg Lo class will be NoClass iff the argument is ignored.
2169 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2170 /// also be ComplexX87.
2171 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2172 bool isNamedArg) const;
2174 llvm::Type *GetByteVectorType(QualType Ty) const;
2175 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2176 unsigned IROffset, QualType SourceTy,
2177 unsigned SourceOffset) const;
2178 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2179 unsigned IROffset, QualType SourceTy,
2180 unsigned SourceOffset) const;
2182 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2183 /// such that the argument will be returned in memory.
2184 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2186 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2187 /// such that the argument will be passed in memory.
2189 /// \param freeIntRegs - The number of free integer registers remaining
2191 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2193 ABIArgInfo classifyReturnType(QualType RetTy) const;
2195 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2196 unsigned &neededInt, unsigned &neededSSE,
2197 bool isNamedArg) const;
2199 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2200 unsigned &NeededSSE) const;
2202 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2203 unsigned &NeededSSE) const;
2205 bool IsIllegalVectorType(QualType Ty) const;
2207 /// The 0.98 ABI revision clarified a lot of ambiguities,
2208 /// unfortunately in ways that were not always consistent with
2209 /// certain previous compilers. In particular, platforms which
2210 /// required strict binary compatibility with older versions of GCC
2211 /// may need to exempt themselves.
2212 bool honorsRevision0_98() const {
2213 return !getTarget().getTriple().isOSDarwin();
2216 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2217 /// classify it as INTEGER (for compatibility with older clang compilers).
2218 bool classifyIntegerMMXAsSSE() const {
2219 // Clang <= 3.8 did not do this.
2220 if (getContext().getLangOpts().getClangABICompat() <=
2221 LangOptions::ClangABI::Ver3_8)
2224 const llvm::Triple &Triple = getTarget().getTriple();
2225 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2227 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2232 // GCC classifies vectors of __int128 as memory.
2233 bool passInt128VectorsInMem() const {
2234 // Clang <= 9.0 did not do this.
2235 if (getContext().getLangOpts().getClangABICompat() <=
2236 LangOptions::ClangABI::Ver9)
2239 const llvm::Triple &T = getTarget().getTriple();
2240 return T.isOSLinux() || T.isOSNetBSD();
2243 X86AVXABILevel AVXLevel;
2244 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2246 bool Has64BitPointers;
2249 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2250 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2251 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2254 bool isPassedUsingAVXType(QualType type) const {
2255 unsigned neededInt, neededSSE;
2256 // The freeIntRegs argument doesn't matter here.
2257 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2258 /*isNamedArg*/true);
2259 if (info.isDirect()) {
2260 llvm::Type *ty = info.getCoerceToType();
2261 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2262 return (vectorTy->getBitWidth() > 128);
2267 void computeInfo(CGFunctionInfo &FI) const override;
2269 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2270 QualType Ty) const override;
2271 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2272 QualType Ty) const override;
2274 bool has64BitPointers() const {
2275 return Has64BitPointers;
2278 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2279 bool asReturnValue) const override {
2280 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2282 bool isSwiftErrorInRegister() const override {
2287 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2288 class WinX86_64ABIInfo : public SwiftABIInfo {
2290 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2291 : SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2292 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2294 void computeInfo(CGFunctionInfo &FI) const override;
2296 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2297 QualType Ty) const override;
2299 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2300 // FIXME: Assumes vectorcall is in use.
2301 return isX86VectorTypeForVectorCall(getContext(), Ty);
2304 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2305 uint64_t NumMembers) const override {
2306 // FIXME: Assumes vectorcall is in use.
2307 return isX86VectorCallAggregateSmallEnough(NumMembers);
2310 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2311 bool asReturnValue) const override {
2312 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2315 bool isSwiftErrorInRegister() const override {
2320 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2321 bool IsVectorCall, bool IsRegCall) const;
2322 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2323 const ABIArgInfo ¤t) const;
2324 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2325 bool IsVectorCall, bool IsRegCall) const;
2327 X86AVXABILevel AVXLevel;
2332 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2334 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2335 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2337 const X86_64ABIInfo &getABIInfo() const {
2338 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2341 /// Disable tail call on x86-64. The epilogue code before the tail jump blocks
2342 /// the autoreleaseRV/retainRV optimization.
2343 bool shouldSuppressTailCallsOfRetainAutoreleasedReturnValue() const override {
2347 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2351 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2352 llvm::Value *Address) const override {
2353 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2355 // 0-15 are the 16 integer registers.
2357 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2361 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2362 StringRef Constraint,
2363 llvm::Type* Ty) const override {
2364 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2367 bool isNoProtoCallVariadic(const CallArgList &args,
2368 const FunctionNoProtoType *fnType) const override {
2369 // The default CC on x86-64 sets %al to the number of SSA
2370 // registers used, and GCC sets this when calling an unprototyped
2371 // function, so we override the default behavior. However, don't do
2372 // that when AVX types are involved: the ABI explicitly states it is
2373 // undefined, and it doesn't work in practice because of how the ABI
2374 // defines varargs anyway.
2375 if (fnType->getCallConv() == CC_C) {
2376 bool HasAVXType = false;
2377 for (CallArgList::const_iterator
2378 it = args.begin(), ie = args.end(); it != ie; ++it) {
2379 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2389 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2393 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2394 unsigned Sig = (0xeb << 0) | // jmp rel8
2395 (0x06 << 8) | // .+0x08
2398 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2401 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2402 CodeGen::CodeGenModule &CGM) const override {
2403 if (GV->isDeclaration())
2405 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2406 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2407 llvm::Function *Fn = cast<llvm::Function>(GV);
2408 Fn->addFnAttr("stackrealign");
2410 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2411 llvm::Function *Fn = cast<llvm::Function>(GV);
2412 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2418 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2419 // If the argument does not end in .lib, automatically add the suffix.
2420 // If the argument contains a space, enclose it in quotes.
2421 // This matches the behavior of MSVC.
2422 bool Quote = (Lib.find(" ") != StringRef::npos);
2423 std::string ArgStr = Quote ? "\"" : "";
2425 if (!Lib.endswith_lower(".lib") && !Lib.endswith_lower(".a"))
2427 ArgStr += Quote ? "\"" : "";
2431 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2433 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2434 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2435 unsigned NumRegisterParameters)
2436 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2437 Win32StructABI, NumRegisterParameters, false) {}
2439 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2440 CodeGen::CodeGenModule &CGM) const override;
2442 void getDependentLibraryOption(llvm::StringRef Lib,
2443 llvm::SmallString<24> &Opt) const override {
2444 Opt = "/DEFAULTLIB:";
2445 Opt += qualifyWindowsLibrary(Lib);
2448 void getDetectMismatchOption(llvm::StringRef Name,
2449 llvm::StringRef Value,
2450 llvm::SmallString<32> &Opt) const override {
2451 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2455 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2456 CodeGen::CodeGenModule &CGM) {
2457 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2459 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2460 Fn->addFnAttr("stack-probe-size",
2461 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2462 if (CGM.getCodeGenOpts().NoStackArgProbe)
2463 Fn->addFnAttr("no-stack-arg-probe");
2467 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2468 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2469 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2470 if (GV->isDeclaration())
2472 addStackProbeTargetAttributes(D, GV, CGM);
2475 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2477 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2478 X86AVXABILevel AVXLevel)
2479 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT, AVXLevel)) {}
2481 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2482 CodeGen::CodeGenModule &CGM) const override;
2484 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2488 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2489 llvm::Value *Address) const override {
2490 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2492 // 0-15 are the 16 integer registers.
2494 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2498 void getDependentLibraryOption(llvm::StringRef Lib,
2499 llvm::SmallString<24> &Opt) const override {
2500 Opt = "/DEFAULTLIB:";
2501 Opt += qualifyWindowsLibrary(Lib);
2504 void getDetectMismatchOption(llvm::StringRef Name,
2505 llvm::StringRef Value,
2506 llvm::SmallString<32> &Opt) const override {
2507 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2511 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2512 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2513 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2514 if (GV->isDeclaration())
2516 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2517 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2518 llvm::Function *Fn = cast<llvm::Function>(GV);
2519 Fn->addFnAttr("stackrealign");
2521 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2522 llvm::Function *Fn = cast<llvm::Function>(GV);
2523 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2527 addStackProbeTargetAttributes(D, GV, CGM);
2531 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2533 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2535 // (a) If one of the classes is Memory, the whole argument is passed in
2538 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2541 // (c) If the size of the aggregate exceeds two eightbytes and the first
2542 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2543 // argument is passed in memory. NOTE: This is necessary to keep the
2544 // ABI working for processors that don't support the __m256 type.
2546 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2548 // Some of these are enforced by the merging logic. Others can arise
2549 // only with unions; for example:
2550 // union { _Complex double; unsigned; }
2552 // Note that clauses (b) and (c) were added in 0.98.
2556 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2558 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2560 if (Hi == SSEUp && Lo != SSE)
2564 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2565 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2566 // classified recursively so that always two fields are
2567 // considered. The resulting class is calculated according to
2568 // the classes of the fields in the eightbyte:
2570 // (a) If both classes are equal, this is the resulting class.
2572 // (b) If one of the classes is NO_CLASS, the resulting class is
2575 // (c) If one of the classes is MEMORY, the result is the MEMORY
2578 // (d) If one of the classes is INTEGER, the result is the
2581 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2582 // MEMORY is used as class.
2584 // (f) Otherwise class SSE is used.
2586 // Accum should never be memory (we should have returned) or
2587 // ComplexX87 (because this cannot be passed in a structure).
2588 assert((Accum != Memory && Accum != ComplexX87) &&
2589 "Invalid accumulated classification during merge.");
2590 if (Accum == Field || Field == NoClass)
2592 if (Field == Memory)
2594 if (Accum == NoClass)
2596 if (Accum == Integer || Field == Integer)
2598 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2599 Accum == X87 || Accum == X87Up)
2604 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2605 Class &Lo, Class &Hi, bool isNamedArg) const {
2606 // FIXME: This code can be simplified by introducing a simple value class for
2607 // Class pairs with appropriate constructor methods for the various
2610 // FIXME: Some of the split computations are wrong; unaligned vectors
2611 // shouldn't be passed in registers for example, so there is no chance they
2612 // can straddle an eightbyte. Verify & simplify.
2616 Class &Current = OffsetBase < 64 ? Lo : Hi;
2619 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2620 BuiltinType::Kind k = BT->getKind();
2622 if (k == BuiltinType::Void) {
2624 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2627 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2629 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2631 } else if (k == BuiltinType::LongDouble) {
2632 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2633 if (LDF == &llvm::APFloat::IEEEquad()) {
2636 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2639 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2642 llvm_unreachable("unexpected long double representation!");
2644 // FIXME: _Decimal32 and _Decimal64 are SSE.
2645 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2649 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2650 // Classify the underlying integer type.
2651 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2655 if (Ty->hasPointerRepresentation()) {
2660 if (Ty->isMemberPointerType()) {
2661 if (Ty->isMemberFunctionPointerType()) {
2662 if (Has64BitPointers) {
2663 // If Has64BitPointers, this is an {i64, i64}, so classify both
2667 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2668 // straddles an eightbyte boundary, Hi should be classified as well.
2669 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2670 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2671 if (EB_FuncPtr != EB_ThisAdj) {
2683 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2684 uint64_t Size = getContext().getTypeSize(VT);
2685 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2686 // gcc passes the following as integer:
2687 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2688 // 2 bytes - <2 x char>, <1 x short>
2689 // 1 byte - <1 x char>
2692 // If this type crosses an eightbyte boundary, it should be
2694 uint64_t EB_Lo = (OffsetBase) / 64;
2695 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2698 } else if (Size == 64) {
2699 QualType ElementType = VT->getElementType();
2701 // gcc passes <1 x double> in memory. :(
2702 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2705 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2706 // pass them as integer. For platforms where clang is the de facto
2707 // platform compiler, we must continue to use integer.
2708 if (!classifyIntegerMMXAsSSE() &&
2709 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2710 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2711 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2712 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2717 // If this type crosses an eightbyte boundary, it should be
2719 if (OffsetBase && OffsetBase != 64)
2721 } else if (Size == 128 ||
2722 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2723 QualType ElementType = VT->getElementType();
2725 // gcc passes 256 and 512 bit <X x __int128> vectors in memory. :(
2726 if (passInt128VectorsInMem() && Size != 128 &&
2727 (ElementType->isSpecificBuiltinType(BuiltinType::Int128) ||
2728 ElementType->isSpecificBuiltinType(BuiltinType::UInt128)))
2731 // Arguments of 256-bits are split into four eightbyte chunks. The
2732 // least significant one belongs to class SSE and all the others to class
2733 // SSEUP. The original Lo and Hi design considers that types can't be
2734 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2735 // This design isn't correct for 256-bits, but since there're no cases
2736 // where the upper parts would need to be inspected, avoid adding
2737 // complexity and just consider Hi to match the 64-256 part.
2739 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2740 // registers if they are "named", i.e. not part of the "..." of a
2741 // variadic function.
2743 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2744 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2751 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2752 QualType ET = getContext().getCanonicalType(CT->getElementType());
2754 uint64_t Size = getContext().getTypeSize(Ty);
2755 if (ET->isIntegralOrEnumerationType()) {
2758 else if (Size <= 128)
2760 } else if (ET == getContext().FloatTy) {
2762 } else if (ET == getContext().DoubleTy) {
2764 } else if (ET == getContext().LongDoubleTy) {
2765 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2766 if (LDF == &llvm::APFloat::IEEEquad())
2768 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2769 Current = ComplexX87;
2770 else if (LDF == &llvm::APFloat::IEEEdouble())
2773 llvm_unreachable("unexpected long double representation!");
2776 // If this complex type crosses an eightbyte boundary then it
2778 uint64_t EB_Real = (OffsetBase) / 64;
2779 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2780 if (Hi == NoClass && EB_Real != EB_Imag)
2786 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2787 // Arrays are treated like structures.
2789 uint64_t Size = getContext().getTypeSize(Ty);
2791 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2792 // than eight eightbytes, ..., it has class MEMORY.
2796 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2797 // fields, it has class MEMORY.
2799 // Only need to check alignment of array base.
2800 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2803 // Otherwise implement simplified merge. We could be smarter about
2804 // this, but it isn't worth it and would be harder to verify.
2806 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2807 uint64_t ArraySize = AT->getSize().getZExtValue();
2809 // The only case a 256-bit wide vector could be used is when the array
2810 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2811 // to work for sizes wider than 128, early check and fallback to memory.
2814 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2817 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2818 Class FieldLo, FieldHi;
2819 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2820 Lo = merge(Lo, FieldLo);
2821 Hi = merge(Hi, FieldHi);
2822 if (Lo == Memory || Hi == Memory)
2826 postMerge(Size, Lo, Hi);
2827 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2831 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2832 uint64_t Size = getContext().getTypeSize(Ty);
2834 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2835 // than eight eightbytes, ..., it has class MEMORY.
2839 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2840 // copy constructor or a non-trivial destructor, it is passed by invisible
2842 if (getRecordArgABI(RT, getCXXABI()))
2845 const RecordDecl *RD = RT->getDecl();
2847 // Assume variable sized types are passed in memory.
2848 if (RD->hasFlexibleArrayMember())
2851 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2853 // Reset Lo class, this will be recomputed.
2856 // If this is a C++ record, classify the bases first.
2857 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2858 for (const auto &I : CXXRD->bases()) {
2859 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2860 "Unexpected base class!");
2862 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
2864 // Classify this field.
2866 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2867 // single eightbyte, each is classified separately. Each eightbyte gets
2868 // initialized to class NO_CLASS.
2869 Class FieldLo, FieldHi;
2871 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2872 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2873 Lo = merge(Lo, FieldLo);
2874 Hi = merge(Hi, FieldHi);
2875 if (Lo == Memory || Hi == Memory) {
2876 postMerge(Size, Lo, Hi);
2882 // Classify the fields one at a time, merging the results.
2884 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2885 i != e; ++i, ++idx) {
2886 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2887 bool BitField = i->isBitField();
2889 // Ignore padding bit-fields.
2890 if (BitField && i->isUnnamedBitfield())
2893 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2894 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2896 // The only case a 256-bit wide vector could be used is when the struct
2897 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2898 // to work for sizes wider than 128, early check and fallback to memory.
2900 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2901 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2903 postMerge(Size, Lo, Hi);
2906 // Note, skip this test for bit-fields, see below.
2907 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2909 postMerge(Size, Lo, Hi);
2913 // Classify this field.
2915 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2916 // exceeds a single eightbyte, each is classified
2917 // separately. Each eightbyte gets initialized to class
2919 Class FieldLo, FieldHi;
2921 // Bit-fields require special handling, they do not force the
2922 // structure to be passed in memory even if unaligned, and
2923 // therefore they can straddle an eightbyte.
2925 assert(!i->isUnnamedBitfield());
2926 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2927 uint64_t Size = i->getBitWidthValue(getContext());
2929 uint64_t EB_Lo = Offset / 64;
2930 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2933 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2938 FieldHi = EB_Hi ? Integer : NoClass;
2941 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2942 Lo = merge(Lo, FieldLo);
2943 Hi = merge(Hi, FieldHi);
2944 if (Lo == Memory || Hi == Memory)
2948 postMerge(Size, Lo, Hi);
2952 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2953 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2955 if (!isAggregateTypeForABI(Ty)) {
2956 // Treat an enum type as its underlying type.
2957 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2958 Ty = EnumTy->getDecl()->getIntegerType();
2960 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2961 : ABIArgInfo::getDirect());
2964 return getNaturalAlignIndirect(Ty);
2967 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2968 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2969 uint64_t Size = getContext().getTypeSize(VecTy);
2970 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2971 if (Size <= 64 || Size > LargestVector)
2973 QualType EltTy = VecTy->getElementType();
2974 if (passInt128VectorsInMem() &&
2975 (EltTy->isSpecificBuiltinType(BuiltinType::Int128) ||
2976 EltTy->isSpecificBuiltinType(BuiltinType::UInt128)))
2983 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2984 unsigned freeIntRegs) const {
2985 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2988 // This assumption is optimistic, as there could be free registers available
2989 // when we need to pass this argument in memory, and LLVM could try to pass
2990 // the argument in the free register. This does not seem to happen currently,
2991 // but this code would be much safer if we could mark the argument with
2992 // 'onstack'. See PR12193.
2993 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2994 // Treat an enum type as its underlying type.
2995 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2996 Ty = EnumTy->getDecl()->getIntegerType();
2998 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2999 : ABIArgInfo::getDirect());
3002 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
3003 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3005 // Compute the byval alignment. We specify the alignment of the byval in all
3006 // cases so that the mid-level optimizer knows the alignment of the byval.
3007 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
3009 // Attempt to avoid passing indirect results using byval when possible. This
3010 // is important for good codegen.
3012 // We do this by coercing the value into a scalar type which the backend can
3013 // handle naturally (i.e., without using byval).
3015 // For simplicity, we currently only do this when we have exhausted all of the
3016 // free integer registers. Doing this when there are free integer registers
3017 // would require more care, as we would have to ensure that the coerced value
3018 // did not claim the unused register. That would require either reording the
3019 // arguments to the function (so that any subsequent inreg values came first),
3020 // or only doing this optimization when there were no following arguments that
3023 // We currently expect it to be rare (particularly in well written code) for
3024 // arguments to be passed on the stack when there are still free integer
3025 // registers available (this would typically imply large structs being passed
3026 // by value), so this seems like a fair tradeoff for now.
3028 // We can revisit this if the backend grows support for 'onstack' parameter
3029 // attributes. See PR12193.
3030 if (freeIntRegs == 0) {
3031 uint64_t Size = getContext().getTypeSize(Ty);
3033 // If this type fits in an eightbyte, coerce it into the matching integral
3034 // type, which will end up on the stack (with alignment 8).
3035 if (Align == 8 && Size <= 64)
3036 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
3040 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
3043 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
3044 /// register. Pick an LLVM IR type that will be passed as a vector register.
3045 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
3046 // Wrapper structs/arrays that only contain vectors are passed just like
3047 // vectors; strip them off if present.
3048 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
3049 Ty = QualType(InnerTy, 0);
3051 llvm::Type *IRType = CGT.ConvertType(Ty);
3052 if (isa<llvm::VectorType>(IRType)) {
3053 // Don't pass vXi128 vectors in their native type, the backend can't
3055 if (passInt128VectorsInMem() &&
3056 IRType->getVectorElementType()->isIntegerTy(128)) {
3057 // Use a vXi64 vector.
3058 uint64_t Size = getContext().getTypeSize(Ty);
3059 return llvm::VectorType::get(llvm::Type::getInt64Ty(getVMContext()),
3066 if (IRType->getTypeID() == llvm::Type::FP128TyID)
3069 // We couldn't find the preferred IR vector type for 'Ty'.
3070 uint64_t Size = getContext().getTypeSize(Ty);
3071 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
3074 // Return a LLVM IR vector type based on the size of 'Ty'.
3075 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
3079 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
3080 /// is known to either be off the end of the specified type or being in
3081 /// alignment padding. The user type specified is known to be at most 128 bits
3082 /// in size, and have passed through X86_64ABIInfo::classify with a successful
3083 /// classification that put one of the two halves in the INTEGER class.
3085 /// It is conservatively correct to return false.
3086 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
3087 unsigned EndBit, ASTContext &Context) {
3088 // If the bytes being queried are off the end of the type, there is no user
3089 // data hiding here. This handles analysis of builtins, vectors and other
3090 // types that don't contain interesting padding.
3091 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
3092 if (TySize <= StartBit)
3095 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
3096 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
3097 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
3099 // Check each element to see if the element overlaps with the queried range.
3100 for (unsigned i = 0; i != NumElts; ++i) {
3101 // If the element is after the span we care about, then we're done..
3102 unsigned EltOffset = i*EltSize;
3103 if (EltOffset >= EndBit) break;
3105 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
3106 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
3107 EndBit-EltOffset, Context))
3110 // If it overlaps no elements, then it is safe to process as padding.
3114 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3115 const RecordDecl *RD = RT->getDecl();
3116 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3118 // If this is a C++ record, check the bases first.
3119 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3120 for (const auto &I : CXXRD->bases()) {
3121 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3122 "Unexpected base class!");
3124 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
3126 // If the base is after the span we care about, ignore it.
3127 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3128 if (BaseOffset >= EndBit) continue;
3130 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3131 if (!BitsContainNoUserData(I.getType(), BaseStart,
3132 EndBit-BaseOffset, Context))
3137 // Verify that no field has data that overlaps the region of interest. Yes
3138 // this could be sped up a lot by being smarter about queried fields,
3139 // however we're only looking at structs up to 16 bytes, so we don't care
3142 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3143 i != e; ++i, ++idx) {
3144 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3146 // If we found a field after the region we care about, then we're done.
3147 if (FieldOffset >= EndBit) break;
3149 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3150 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3155 // If nothing in this record overlapped the area of interest, then we're
3163 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3164 /// float member at the specified offset. For example, {int,{float}} has a
3165 /// float at offset 4. It is conservatively correct for this routine to return
3167 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3168 const llvm::DataLayout &TD) {
3169 // Base case if we find a float.
3170 if (IROffset == 0 && IRType->isFloatTy())
3173 // If this is a struct, recurse into the field at the specified offset.
3174 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3175 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3176 unsigned Elt = SL->getElementContainingOffset(IROffset);
3177 IROffset -= SL->getElementOffset(Elt);
3178 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3181 // If this is an array, recurse into the field at the specified offset.
3182 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3183 llvm::Type *EltTy = ATy->getElementType();
3184 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3185 IROffset -= IROffset/EltSize*EltSize;
3186 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3193 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3194 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3195 llvm::Type *X86_64ABIInfo::
3196 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3197 QualType SourceTy, unsigned SourceOffset) const {
3198 // The only three choices we have are either double, <2 x float>, or float. We
3199 // pass as float if the last 4 bytes is just padding. This happens for
3200 // structs that contain 3 floats.
3201 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3202 SourceOffset*8+64, getContext()))
3203 return llvm::Type::getFloatTy(getVMContext());
3205 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3206 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3208 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3209 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3210 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3212 return llvm::Type::getDoubleTy(getVMContext());
3216 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3217 /// an 8-byte GPR. This means that we either have a scalar or we are talking
3218 /// about the high or low part of an up-to-16-byte struct. This routine picks
3219 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3220 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3223 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3224 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
3225 /// the 8-byte value references. PrefType may be null.
3227 /// SourceTy is the source-level type for the entire argument. SourceOffset is
3228 /// an offset into this that we're processing (which is always either 0 or 8).
3230 llvm::Type *X86_64ABIInfo::
3231 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3232 QualType SourceTy, unsigned SourceOffset) const {
3233 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3234 // returning an 8-byte unit starting with it. See if we can safely use it.
3235 if (IROffset == 0) {
3236 // Pointers and int64's always fill the 8-byte unit.
3237 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3238 IRType->isIntegerTy(64))
3241 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3242 // goodness in the source type is just tail padding. This is allowed to
3243 // kick in for struct {double,int} on the int, but not on
3244 // struct{double,int,int} because we wouldn't return the second int. We
3245 // have to do this analysis on the source type because we can't depend on
3246 // unions being lowered a specific way etc.
3247 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3248 IRType->isIntegerTy(32) ||
3249 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3250 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3251 cast<llvm::IntegerType>(IRType)->getBitWidth();
3253 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3254 SourceOffset*8+64, getContext()))
3259 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3260 // If this is a struct, recurse into the field at the specified offset.
3261 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3262 if (IROffset < SL->getSizeInBytes()) {
3263 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3264 IROffset -= SL->getElementOffset(FieldIdx);
3266 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3267 SourceTy, SourceOffset);
3271 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3272 llvm::Type *EltTy = ATy->getElementType();
3273 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3274 unsigned EltOffset = IROffset/EltSize*EltSize;
3275 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3279 // Okay, we don't have any better idea of what to pass, so we pass this in an
3280 // integer register that isn't too big to fit the rest of the struct.
3281 unsigned TySizeInBytes =
3282 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3284 assert(TySizeInBytes != SourceOffset && "Empty field?");
3286 // It is always safe to classify this as an integer type up to i64 that
3287 // isn't larger than the structure.
3288 return llvm::IntegerType::get(getVMContext(),
3289 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3293 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3294 /// be used as elements of a two register pair to pass or return, return a
3295 /// first class aggregate to represent them. For example, if the low part of
3296 /// a by-value argument should be passed as i32* and the high part as float,
3297 /// return {i32*, float}.
3299 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3300 const llvm::DataLayout &TD) {
3301 // In order to correctly satisfy the ABI, we need to the high part to start
3302 // at offset 8. If the high and low parts we inferred are both 4-byte types
3303 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3304 // the second element at offset 8. Check for this:
3305 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3306 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3307 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3308 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3310 // To handle this, we have to increase the size of the low part so that the
3311 // second element will start at an 8 byte offset. We can't increase the size
3312 // of the second element because it might make us access off the end of the
3315 // There are usually two sorts of types the ABI generation code can produce
3316 // for the low part of a pair that aren't 8 bytes in size: float or
3317 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3319 // Promote these to a larger type.
3320 if (Lo->isFloatTy())
3321 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3323 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3324 && "Invalid/unknown lo type");
3325 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3329 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3331 // Verify that the second element is at an 8-byte offset.
3332 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3333 "Invalid x86-64 argument pair!");
3337 ABIArgInfo X86_64ABIInfo::
3338 classifyReturnType(QualType RetTy) const {
3339 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3340 // classification algorithm.
3341 X86_64ABIInfo::Class Lo, Hi;
3342 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3344 // Check some invariants.
3345 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3346 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3348 llvm::Type *ResType = nullptr;
3352 return ABIArgInfo::getIgnore();
3353 // If the low part is just padding, it takes no register, leave ResType
3355 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3356 "Unknown missing lo part");
3361 llvm_unreachable("Invalid classification for lo word.");
3363 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3366 return getIndirectReturnResult(RetTy);
3368 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3369 // available register of the sequence %rax, %rdx is used.
3371 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3373 // If we have a sign or zero extended integer, make sure to return Extend
3374 // so that the parameter gets the right LLVM IR attributes.
3375 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3376 // Treat an enum type as its underlying type.
3377 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3378 RetTy = EnumTy->getDecl()->getIntegerType();
3380 if (RetTy->isIntegralOrEnumerationType() &&
3381 RetTy->isPromotableIntegerType())
3382 return ABIArgInfo::getExtend(RetTy);
3386 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3387 // available SSE register of the sequence %xmm0, %xmm1 is used.
3389 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3392 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3393 // returned on the X87 stack in %st0 as 80-bit x87 number.
3395 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3398 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3399 // part of the value is returned in %st0 and the imaginary part in
3402 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3403 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3404 llvm::Type::getX86_FP80Ty(getVMContext()));
3408 llvm::Type *HighPart = nullptr;
3410 // Memory was handled previously and X87 should
3411 // never occur as a hi class.
3414 llvm_unreachable("Invalid classification for hi word.");
3416 case ComplexX87: // Previously handled.
3421 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3422 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3423 return ABIArgInfo::getDirect(HighPart, 8);
3426 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3427 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3428 return ABIArgInfo::getDirect(HighPart, 8);
3431 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3432 // is passed in the next available eightbyte chunk if the last used
3435 // SSEUP should always be preceded by SSE, just widen.
3437 assert(Lo == SSE && "Unexpected SSEUp classification.");
3438 ResType = GetByteVectorType(RetTy);
3441 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3442 // returned together with the previous X87 value in %st0.
3444 // If X87Up is preceded by X87, we don't need to do
3445 // anything. However, in some cases with unions it may not be
3446 // preceded by X87. In such situations we follow gcc and pass the
3447 // extra bits in an SSE reg.
3449 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3450 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3451 return ABIArgInfo::getDirect(HighPart, 8);
3456 // If a high part was specified, merge it together with the low part. It is
3457 // known to pass in the high eightbyte of the result. We do this by forming a
3458 // first class struct aggregate with the high and low part: {low, high}
3460 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3462 return ABIArgInfo::getDirect(ResType);
3465 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3466 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3470 Ty = useFirstFieldIfTransparentUnion(Ty);
3472 X86_64ABIInfo::Class Lo, Hi;
3473 classify(Ty, 0, Lo, Hi, isNamedArg);
3475 // Check some invariants.
3476 // FIXME: Enforce these by construction.
3477 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3478 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3482 llvm::Type *ResType = nullptr;
3486 return ABIArgInfo::getIgnore();
3487 // If the low part is just padding, it takes no register, leave ResType
3489 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3490 "Unknown missing lo part");
3493 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3497 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3498 // COMPLEX_X87, it is passed in memory.
3501 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3503 return getIndirectResult(Ty, freeIntRegs);
3507 llvm_unreachable("Invalid classification for lo word.");
3509 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3510 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3515 // Pick an 8-byte type based on the preferred type.
3516 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3518 // If we have a sign or zero extended integer, make sure to return Extend
3519 // so that the parameter gets the right LLVM IR attributes.
3520 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3521 // Treat an enum type as its underlying type.
3522 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3523 Ty = EnumTy->getDecl()->getIntegerType();
3525 if (Ty->isIntegralOrEnumerationType() &&
3526 Ty->isPromotableIntegerType())
3527 return ABIArgInfo::getExtend(Ty);
3532 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3533 // available SSE register is used, the registers are taken in the
3534 // order from %xmm0 to %xmm7.
3536 llvm::Type *IRType = CGT.ConvertType(Ty);
3537 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3543 llvm::Type *HighPart = nullptr;
3545 // Memory was handled previously, ComplexX87 and X87 should
3546 // never occur as hi classes, and X87Up must be preceded by X87,
3547 // which is passed in memory.
3551 llvm_unreachable("Invalid classification for hi word.");
3553 case NoClass: break;
3557 // Pick an 8-byte type based on the preferred type.
3558 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3560 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3561 return ABIArgInfo::getDirect(HighPart, 8);
3564 // X87Up generally doesn't occur here (long double is passed in
3565 // memory), except in situations