1 //===---- TargetInfo.cpp - Encapsulate target details -----------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // These classes wrap the information about a call or function
11 // definition used to handle ABI compliancy.
13 //===----------------------------------------------------------------------===//
15 #include "TargetInfo.h"
20 #include "CodeGenFunction.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/CodeGen/CGFunctionInfo.h"
23 #include "clang/CodeGen/SwiftCallingConv.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/ADT/Triple.h"
28 #include "llvm/ADT/Twine.h"
29 #include "llvm/IR/DataLayout.h"
30 #include "llvm/IR/Type.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <algorithm> // std::sort
34 using namespace clang;
35 using namespace CodeGen;
37 // Helper for coercing an aggregate argument or return value into an integer
38 // array of the same size (including padding) and alignment. This alternate
39 // coercion happens only for the RenderScript ABI and can be removed after
40 // runtimes that rely on it are no longer supported.
42 // RenderScript assumes that the size of the argument / return value in the IR
43 // is the same as the size of the corresponding qualified type. This helper
44 // coerces the aggregate type into an array of the same size (including
45 // padding). This coercion is used in lieu of expansion of struct members or
46 // other canonical coercions that return a coerced-type of larger size.
48 // Ty - The argument / return value type
49 // Context - The associated ASTContext
50 // LLVMContext - The associated LLVMContext
51 static ABIArgInfo coerceToIntArray(QualType Ty,
53 llvm::LLVMContext &LLVMContext) {
54 // Alignment and Size are measured in bits.
55 const uint64_t Size = Context.getTypeSize(Ty);
56 const uint64_t Alignment = Context.getTypeAlign(Ty);
57 llvm::Type *IntType = llvm::Type::getIntNTy(LLVMContext, Alignment);
58 const uint64_t NumElements = (Size + Alignment - 1) / Alignment;
59 return ABIArgInfo::getDirect(llvm::ArrayType::get(IntType, NumElements));
62 static void AssignToArrayRange(CodeGen::CGBuilderTy &Builder,
67 // Alternatively, we could emit this as a loop in the source.
68 for (unsigned I = FirstIndex; I <= LastIndex; ++I) {
70 Builder.CreateConstInBoundsGEP1_32(Builder.getInt8Ty(), Array, I);
71 Builder.CreateAlignedStore(Value, Cell, CharUnits::One());
75 static bool isAggregateTypeForABI(QualType T) {
76 return !CodeGenFunction::hasScalarEvaluationKind(T) ||
77 T->isMemberFunctionPointerType();
81 ABIInfo::getNaturalAlignIndirect(QualType Ty, bool ByRef, bool Realign,
82 llvm::Type *Padding) const {
83 return ABIArgInfo::getIndirect(getContext().getTypeAlignInChars(Ty),
84 ByRef, Realign, Padding);
88 ABIInfo::getNaturalAlignIndirectInReg(QualType Ty, bool Realign) const {
89 return ABIArgInfo::getIndirectInReg(getContext().getTypeAlignInChars(Ty),
90 /*ByRef*/ false, Realign);
93 Address ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
95 return Address::invalid();
98 ABIInfo::~ABIInfo() {}
100 /// Does the given lowering require more than the given number of
101 /// registers when expanded?
103 /// This is intended to be the basis of a reasonable basic implementation
104 /// of should{Pass,Return}IndirectlyForSwift.
106 /// For most targets, a limit of four total registers is reasonable; this
107 /// limits the amount of code required in order to move around the value
108 /// in case it wasn't produced immediately prior to the call by the caller
109 /// (or wasn't produced in exactly the right registers) or isn't used
110 /// immediately within the callee. But some targets may need to further
111 /// limit the register count due to an inability to support that many
112 /// return registers.
113 static bool occupiesMoreThan(CodeGenTypes &cgt,
114 ArrayRef<llvm::Type*> scalarTypes,
115 unsigned maxAllRegisters) {
116 unsigned intCount = 0, fpCount = 0;
117 for (llvm::Type *type : scalarTypes) {
118 if (type->isPointerTy()) {
120 } else if (auto intTy = dyn_cast<llvm::IntegerType>(type)) {
121 auto ptrWidth = cgt.getTarget().getPointerWidth(0);
122 intCount += (intTy->getBitWidth() + ptrWidth - 1) / ptrWidth;
124 assert(type->isVectorTy() || type->isFloatingPointTy());
129 return (intCount + fpCount > maxAllRegisters);
132 bool SwiftABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
134 unsigned numElts) const {
135 // The default implementation of this assumes that the target guarantees
136 // 128-bit SIMD support but nothing more.
137 return (vectorSize.getQuantity() > 8 && vectorSize.getQuantity() <= 16);
140 static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
142 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
144 if (!RT->getDecl()->canPassInRegisters())
145 return CGCXXABI::RAA_Indirect;
146 return CGCXXABI::RAA_Default;
148 return CXXABI.getRecordArgABI(RD);
151 static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
153 const RecordType *RT = T->getAs<RecordType>();
155 return CGCXXABI::RAA_Default;
156 return getRecordArgABI(RT, CXXABI);
159 static bool classifyReturnType(const CGCXXABI &CXXABI, CGFunctionInfo &FI,
160 const ABIInfo &Info) {
161 QualType Ty = FI.getReturnType();
163 if (const auto *RT = Ty->getAs<RecordType>())
164 if (!isa<CXXRecordDecl>(RT->getDecl()) &&
165 !RT->getDecl()->canPassInRegisters()) {
166 FI.getReturnInfo() = Info.getNaturalAlignIndirect(Ty);
170 return CXXABI.classifyReturnType(FI);
173 /// Pass transparent unions as if they were the type of the first element. Sema
174 /// should ensure that all elements of the union have the same "machine type".
175 static QualType useFirstFieldIfTransparentUnion(QualType Ty) {
176 if (const RecordType *UT = Ty->getAsUnionType()) {
177 const RecordDecl *UD = UT->getDecl();
178 if (UD->hasAttr<TransparentUnionAttr>()) {
179 assert(!UD->field_empty() && "sema created an empty transparent union");
180 return UD->field_begin()->getType();
186 CGCXXABI &ABIInfo::getCXXABI() const {
187 return CGT.getCXXABI();
190 ASTContext &ABIInfo::getContext() const {
191 return CGT.getContext();
194 llvm::LLVMContext &ABIInfo::getVMContext() const {
195 return CGT.getLLVMContext();
198 const llvm::DataLayout &ABIInfo::getDataLayout() const {
199 return CGT.getDataLayout();
202 const TargetInfo &ABIInfo::getTarget() const {
203 return CGT.getTarget();
206 const CodeGenOptions &ABIInfo::getCodeGenOpts() const {
207 return CGT.getCodeGenOpts();
210 bool ABIInfo::isAndroid() const { return getTarget().getTriple().isAndroid(); }
212 bool ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
216 bool ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
217 uint64_t Members) const {
221 LLVM_DUMP_METHOD void ABIArgInfo::dump() const {
222 raw_ostream &OS = llvm::errs();
223 OS << "(ABIArgInfo Kind=";
226 OS << "Direct Type=";
227 if (llvm::Type *Ty = getCoerceToType())
239 OS << "InAlloca Offset=" << getInAllocaFieldIndex();
242 OS << "Indirect Align=" << getIndirectAlign().getQuantity()
243 << " ByVal=" << getIndirectByVal()
244 << " Realign=" << getIndirectRealign();
249 case CoerceAndExpand:
250 OS << "CoerceAndExpand Type=";
251 getCoerceAndExpandType()->print(OS);
257 // Dynamically round a pointer up to a multiple of the given alignment.
258 static llvm::Value *emitRoundPointerUpToAlignment(CodeGenFunction &CGF,
261 llvm::Value *PtrAsInt = Ptr;
262 // OverflowArgArea = (OverflowArgArea + Align - 1) & -Align;
263 PtrAsInt = CGF.Builder.CreatePtrToInt(PtrAsInt, CGF.IntPtrTy);
264 PtrAsInt = CGF.Builder.CreateAdd(PtrAsInt,
265 llvm::ConstantInt::get(CGF.IntPtrTy, Align.getQuantity() - 1));
266 PtrAsInt = CGF.Builder.CreateAnd(PtrAsInt,
267 llvm::ConstantInt::get(CGF.IntPtrTy, -Align.getQuantity()));
268 PtrAsInt = CGF.Builder.CreateIntToPtr(PtrAsInt,
270 Ptr->getName() + ".aligned");
274 /// Emit va_arg for a platform using the common void* representation,
275 /// where arguments are simply emitted in an array of slots on the stack.
277 /// This version implements the core direct-value passing rules.
279 /// \param SlotSize - The size and alignment of a stack slot.
280 /// Each argument will be allocated to a multiple of this number of
281 /// slots, and all the slots will be aligned to this value.
282 /// \param AllowHigherAlign - The slot alignment is not a cap;
283 /// an argument type with an alignment greater than the slot size
284 /// will be emitted on a higher-alignment address, potentially
285 /// leaving one or more empty slots behind as padding. If this
286 /// is false, the returned address might be less-aligned than
288 static Address emitVoidPtrDirectVAArg(CodeGenFunction &CGF,
290 llvm::Type *DirectTy,
291 CharUnits DirectSize,
292 CharUnits DirectAlign,
294 bool AllowHigherAlign) {
295 // Cast the element type to i8* if necessary. Some platforms define
296 // va_list as a struct containing an i8* instead of just an i8*.
297 if (VAListAddr.getElementType() != CGF.Int8PtrTy)
298 VAListAddr = CGF.Builder.CreateElementBitCast(VAListAddr, CGF.Int8PtrTy);
300 llvm::Value *Ptr = CGF.Builder.CreateLoad(VAListAddr, "argp.cur");
302 // If the CC aligns values higher than the slot size, do so if needed.
303 Address Addr = Address::invalid();
304 if (AllowHigherAlign && DirectAlign > SlotSize) {
305 Addr = Address(emitRoundPointerUpToAlignment(CGF, Ptr, DirectAlign),
308 Addr = Address(Ptr, SlotSize);
311 // Advance the pointer past the argument, then store that back.
312 CharUnits FullDirectSize = DirectSize.alignTo(SlotSize);
313 llvm::Value *NextPtr =
314 CGF.Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), FullDirectSize,
316 CGF.Builder.CreateStore(NextPtr, 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 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DestTy);
458 TargetCodeGenInfo::performAddrSpaceCast(CodeGenModule &CGM, llvm::Constant *Src,
459 LangAS SrcAddr, LangAS DestAddr,
460 llvm::Type *DestTy) const {
461 // Since target may map different address spaces in AST to the same address
462 // space, an address space conversion may end up as a bitcast.
463 return llvm::ConstantExpr::getPointerCast(Src, DestTy);
467 TargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S, llvm::LLVMContext &C) const {
468 return C.getOrInsertSyncScopeID(""); /* default sync scope */
471 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays);
473 /// isEmptyField - Return true iff a the field is "empty", that is it
474 /// is an unnamed bit-field or an (array of) empty record(s).
475 static bool isEmptyField(ASTContext &Context, const FieldDecl *FD,
477 if (FD->isUnnamedBitfield())
480 QualType FT = FD->getType();
482 // Constant arrays of empty records count as empty, strip them off.
483 // Constant arrays of zero length always count as empty.
485 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
486 if (AT->getSize() == 0)
488 FT = AT->getElementType();
491 const RecordType *RT = FT->getAs<RecordType>();
495 // C++ record fields are never empty, at least in the Itanium ABI.
497 // FIXME: We should use a predicate for whether this behavior is true in the
499 if (isa<CXXRecordDecl>(RT->getDecl()))
502 return isEmptyRecord(Context, FT, AllowArrays);
505 /// isEmptyRecord - Return true iff a structure contains only empty
506 /// fields. Note that a structure with a flexible array member is not
507 /// considered empty.
508 static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
509 const RecordType *RT = T->getAs<RecordType>();
512 const RecordDecl *RD = RT->getDecl();
513 if (RD->hasFlexibleArrayMember())
516 // If this is a C++ record, check the bases first.
517 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
518 for (const auto &I : CXXRD->bases())
519 if (!isEmptyRecord(Context, I.getType(), true))
522 for (const auto *I : RD->fields())
523 if (!isEmptyField(Context, I, AllowArrays))
528 /// isSingleElementStruct - Determine if a structure is a "single
529 /// element struct", i.e. it has exactly one non-empty field or
530 /// exactly one field which is itself a single element
531 /// struct. Structures with flexible array members are never
532 /// considered single element structs.
534 /// \return The field declaration for the single non-empty field, if
536 static const Type *isSingleElementStruct(QualType T, ASTContext &Context) {
537 const RecordType *RT = T->getAs<RecordType>();
541 const RecordDecl *RD = RT->getDecl();
542 if (RD->hasFlexibleArrayMember())
545 const Type *Found = nullptr;
547 // If this is a C++ record, check the bases first.
548 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
549 for (const auto &I : CXXRD->bases()) {
550 // Ignore empty records.
551 if (isEmptyRecord(Context, I.getType(), true))
554 // If we already found an element then this isn't a single-element struct.
558 // If this is non-empty and not a single element struct, the composite
559 // cannot be a single element struct.
560 Found = isSingleElementStruct(I.getType(), Context);
566 // Check for single element.
567 for (const auto *FD : RD->fields()) {
568 QualType FT = FD->getType();
570 // Ignore empty fields.
571 if (isEmptyField(Context, FD, true))
574 // If we already found an element then this isn't a single-element
579 // Treat single element arrays as the element.
580 while (const ConstantArrayType *AT = Context.getAsConstantArrayType(FT)) {
581 if (AT->getSize().getZExtValue() != 1)
583 FT = AT->getElementType();
586 if (!isAggregateTypeForABI(FT)) {
587 Found = FT.getTypePtr();
589 Found = isSingleElementStruct(FT, Context);
595 // We don't consider a struct a single-element struct if it has
596 // padding beyond the element type.
597 if (Found && Context.getTypeSize(Found) != Context.getTypeSize(T))
604 Address EmitVAArgInstr(CodeGenFunction &CGF, Address VAListAddr, QualType Ty,
605 const ABIArgInfo &AI) {
606 // This default implementation defers to the llvm backend's va_arg
607 // instruction. It can handle only passing arguments directly
608 // (typically only handled in the backend for primitive types), or
609 // aggregates passed indirectly by pointer (NOTE: if the "byval"
610 // flag has ABI impact in the callee, this implementation cannot
613 // Only a few cases are covered here at the moment -- those needed
614 // by the default abi.
617 if (AI.isIndirect()) {
618 assert(!AI.getPaddingType() &&
619 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
621 !AI.getIndirectRealign() &&
622 "Unexpected IndirectRealign seen in arginfo in generic VAArg emitter!");
624 auto TyInfo = CGF.getContext().getTypeInfoInChars(Ty);
625 CharUnits TyAlignForABI = TyInfo.second;
628 llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
630 CGF.Builder.CreateVAArg(VAListAddr.getPointer(), BaseTy);
631 return Address(Addr, TyAlignForABI);
633 assert((AI.isDirect() || AI.isExtend()) &&
634 "Unexpected ArgInfo Kind in generic VAArg emitter!");
636 assert(!AI.getInReg() &&
637 "Unexpected InReg seen in arginfo in generic VAArg emitter!");
638 assert(!AI.getPaddingType() &&
639 "Unexpected PaddingType seen in arginfo in generic VAArg emitter!");
640 assert(!AI.getDirectOffset() &&
641 "Unexpected DirectOffset seen in arginfo in generic VAArg emitter!");
642 assert(!AI.getCoerceToType() &&
643 "Unexpected CoerceToType seen in arginfo in generic VAArg emitter!");
645 Address Temp = CGF.CreateMemTemp(Ty, "varet");
646 Val = CGF.Builder.CreateVAArg(VAListAddr.getPointer(), CGF.ConvertType(Ty));
647 CGF.Builder.CreateStore(Val, Temp);
652 /// DefaultABIInfo - The default implementation for ABI specific
653 /// details. This implementation provides information which results in
654 /// self-consistent and sensible LLVM IR generation, but does not
655 /// conform to any particular ABI.
656 class DefaultABIInfo : public ABIInfo {
658 DefaultABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
660 ABIArgInfo classifyReturnType(QualType RetTy) const;
661 ABIArgInfo classifyArgumentType(QualType RetTy) const;
663 void computeInfo(CGFunctionInfo &FI) const override {
664 if (!getCXXABI().classifyReturnType(FI))
665 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
666 for (auto &I : FI.arguments())
667 I.info = classifyArgumentType(I.type);
670 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
671 QualType Ty) const override {
672 return EmitVAArgInstr(CGF, VAListAddr, Ty, classifyArgumentType(Ty));
676 class DefaultTargetCodeGenInfo : public TargetCodeGenInfo {
678 DefaultTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
679 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
682 ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
683 Ty = useFirstFieldIfTransparentUnion(Ty);
685 if (isAggregateTypeForABI(Ty)) {
686 // Records with non-trivial destructors/copy-constructors should not be
688 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
689 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
691 return getNaturalAlignIndirect(Ty);
694 // Treat an enum type as its underlying type.
695 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
696 Ty = EnumTy->getDecl()->getIntegerType();
698 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
699 : ABIArgInfo::getDirect());
702 ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
703 if (RetTy->isVoidType())
704 return ABIArgInfo::getIgnore();
706 if (isAggregateTypeForABI(RetTy))
707 return getNaturalAlignIndirect(RetTy);
709 // Treat an enum type as its underlying type.
710 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
711 RetTy = EnumTy->getDecl()->getIntegerType();
713 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
714 : ABIArgInfo::getDirect());
717 //===----------------------------------------------------------------------===//
718 // WebAssembly ABI Implementation
720 // This is a very simple ABI that relies a lot on DefaultABIInfo.
721 //===----------------------------------------------------------------------===//
723 class WebAssemblyABIInfo final : public DefaultABIInfo {
725 explicit WebAssemblyABIInfo(CodeGen::CodeGenTypes &CGT)
726 : DefaultABIInfo(CGT) {}
729 ABIArgInfo classifyReturnType(QualType RetTy) const;
730 ABIArgInfo classifyArgumentType(QualType Ty) const;
732 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
733 // non-virtual, but computeInfo and EmitVAArg are virtual, so we
735 void computeInfo(CGFunctionInfo &FI) const override {
736 if (!getCXXABI().classifyReturnType(FI))
737 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
738 for (auto &Arg : FI.arguments())
739 Arg.info = classifyArgumentType(Arg.type);
742 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
743 QualType Ty) const override;
746 class WebAssemblyTargetCodeGenInfo final : public TargetCodeGenInfo {
748 explicit WebAssemblyTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
749 : TargetCodeGenInfo(new WebAssemblyABIInfo(CGT)) {}
751 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
752 CodeGen::CodeGenModule &CGM) const override {
753 if (auto *FD = dyn_cast_or_null<FunctionDecl>(D)) {
754 llvm::Function *Fn = cast<llvm::Function>(GV);
755 if (!FD->doesThisDeclarationHaveABody() && !FD->hasPrototype())
756 Fn->addFnAttr("no-prototype");
761 /// Classify argument of given type \p Ty.
762 ABIArgInfo WebAssemblyABIInfo::classifyArgumentType(QualType Ty) const {
763 Ty = useFirstFieldIfTransparentUnion(Ty);
765 if (isAggregateTypeForABI(Ty)) {
766 // Records with non-trivial destructors/copy-constructors should not be
768 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
769 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
770 // Ignore empty structs/unions.
771 if (isEmptyRecord(getContext(), Ty, true))
772 return ABIArgInfo::getIgnore();
773 // Lower single-element structs to just pass a regular value. TODO: We
774 // could do reasonable-size multiple-element structs too, using getExpand(),
775 // though watch out for things like bitfields.
776 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
777 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
780 // Otherwise just do the default thing.
781 return DefaultABIInfo::classifyArgumentType(Ty);
784 ABIArgInfo WebAssemblyABIInfo::classifyReturnType(QualType RetTy) const {
785 if (isAggregateTypeForABI(RetTy)) {
786 // Records with non-trivial destructors/copy-constructors should not be
787 // returned by value.
788 if (!getRecordArgABI(RetTy, getCXXABI())) {
789 // Ignore empty structs/unions.
790 if (isEmptyRecord(getContext(), RetTy, true))
791 return ABIArgInfo::getIgnore();
792 // Lower single-element structs to just return a regular value. TODO: We
793 // could do reasonable-size multiple-element structs too, using
794 // ABIArgInfo::getDirect().
795 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
796 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
800 // Otherwise just do the default thing.
801 return DefaultABIInfo::classifyReturnType(RetTy);
804 Address WebAssemblyABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
806 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect=*/ false,
807 getContext().getTypeInfoInChars(Ty),
808 CharUnits::fromQuantity(4),
809 /*AllowHigherAlign=*/ true);
812 //===----------------------------------------------------------------------===//
813 // le32/PNaCl bitcode ABI Implementation
815 // This is a simplified version of the x86_32 ABI. Arguments and return values
816 // are always passed on the stack.
817 //===----------------------------------------------------------------------===//
819 class PNaClABIInfo : public ABIInfo {
821 PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
823 ABIArgInfo classifyReturnType(QualType RetTy) const;
824 ABIArgInfo classifyArgumentType(QualType RetTy) const;
826 void computeInfo(CGFunctionInfo &FI) const override;
827 Address EmitVAArg(CodeGenFunction &CGF,
828 Address VAListAddr, QualType Ty) const override;
831 class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
833 PNaClTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
834 : TargetCodeGenInfo(new PNaClABIInfo(CGT)) {}
837 void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
838 if (!getCXXABI().classifyReturnType(FI))
839 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
841 for (auto &I : FI.arguments())
842 I.info = classifyArgumentType(I.type);
845 Address PNaClABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
847 // The PNaCL ABI is a bit odd, in that varargs don't use normal
848 // function classification. Structs get passed directly for varargs
849 // functions, through a rewriting transform in
850 // pnacl-llvm/lib/Transforms/NaCl/ExpandVarArgs.cpp, which allows
851 // this target to actually support a va_arg instructions with an
852 // aggregate type, unlike other targets.
853 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
856 /// Classify argument of given type \p Ty.
857 ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
858 if (isAggregateTypeForABI(Ty)) {
859 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
860 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
861 return getNaturalAlignIndirect(Ty);
862 } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
863 // Treat an enum type as its underlying type.
864 Ty = EnumTy->getDecl()->getIntegerType();
865 } else if (Ty->isFloatingType()) {
866 // Floating-point types don't go inreg.
867 return ABIArgInfo::getDirect();
870 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
871 : ABIArgInfo::getDirect());
874 ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
875 if (RetTy->isVoidType())
876 return ABIArgInfo::getIgnore();
878 // In the PNaCl ABI we always return records/structures on the stack.
879 if (isAggregateTypeForABI(RetTy))
880 return getNaturalAlignIndirect(RetTy);
882 // Treat an enum type as its underlying type.
883 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
884 RetTy = EnumTy->getDecl()->getIntegerType();
886 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
887 : ABIArgInfo::getDirect());
890 /// IsX86_MMXType - Return true if this is an MMX type.
891 bool IsX86_MMXType(llvm::Type *IRType) {
892 // Return true if the type is an MMX type <2 x i32>, <4 x i16>, or <8 x i8>.
893 return IRType->isVectorTy() && IRType->getPrimitiveSizeInBits() == 64 &&
894 cast<llvm::VectorType>(IRType)->getElementType()->isIntegerTy() &&
895 IRType->getScalarSizeInBits() != 64;
898 static llvm::Type* X86AdjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
899 StringRef Constraint,
901 bool IsMMXCons = llvm::StringSwitch<bool>(Constraint)
902 .Cases("y", "&y", "^Ym", true)
904 if (IsMMXCons && Ty->isVectorTy()) {
905 if (cast<llvm::VectorType>(Ty)->getBitWidth() != 64) {
906 // Invalid MMX constraint
910 return llvm::Type::getX86_MMXTy(CGF.getLLVMContext());
913 // No operation needed
917 /// Returns true if this type can be passed in SSE registers with the
918 /// X86_VectorCall calling convention. Shared between x86_32 and x86_64.
919 static bool isX86VectorTypeForVectorCall(ASTContext &Context, QualType Ty) {
920 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
921 if (BT->isFloatingPoint() && BT->getKind() != BuiltinType::Half) {
922 if (BT->getKind() == BuiltinType::LongDouble) {
923 if (&Context.getTargetInfo().getLongDoubleFormat() ==
924 &llvm::APFloat::x87DoubleExtended())
929 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
930 // vectorcall can pass XMM, YMM, and ZMM vectors. We don't pass SSE1 MMX
931 // registers specially.
932 unsigned VecSize = Context.getTypeSize(VT);
933 if (VecSize == 128 || VecSize == 256 || VecSize == 512)
939 /// Returns true if this aggregate is small enough to be passed in SSE registers
940 /// in the X86_VectorCall calling convention. Shared between x86_32 and x86_64.
941 static bool isX86VectorCallAggregateSmallEnough(uint64_t NumMembers) {
942 return NumMembers <= 4;
945 /// Returns a Homogeneous Vector Aggregate ABIArgInfo, used in X86.
946 static ABIArgInfo getDirectX86Hva(llvm::Type* T = nullptr) {
947 auto AI = ABIArgInfo::getDirect(T);
949 AI.setCanBeFlattened(false);
953 //===----------------------------------------------------------------------===//
954 // X86-32 ABI Implementation
955 //===----------------------------------------------------------------------===//
957 /// Similar to llvm::CCState, but for Clang.
959 CCState(unsigned CC) : CC(CC), FreeRegs(0), FreeSSERegs(0) {}
963 unsigned FreeSSERegs;
967 // Vectorcall only allows the first 6 parameters to be passed in registers.
968 VectorcallMaxParamNumAsReg = 6
971 /// X86_32ABIInfo - The X86-32 ABI information.
972 class X86_32ABIInfo : public SwiftABIInfo {
978 static const unsigned MinABIStackAlignInBytes = 4;
980 bool IsDarwinVectorABI;
981 bool IsRetSmallStructInRegABI;
982 bool IsWin32StructABI;
985 unsigned DefaultNumRegisterParameters;
987 static bool isRegisterSize(unsigned Size) {
988 return (Size == 8 || Size == 16 || Size == 32 || Size == 64);
991 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
992 // FIXME: Assumes vectorcall is in use.
993 return isX86VectorTypeForVectorCall(getContext(), Ty);
996 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
997 uint64_t NumMembers) const override {
998 // FIXME: Assumes vectorcall is in use.
999 return isX86VectorCallAggregateSmallEnough(NumMembers);
1002 bool shouldReturnTypeInRegister(QualType Ty, ASTContext &Context) const;
1004 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
1005 /// such that the argument will be passed in memory.
1006 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
1008 ABIArgInfo getIndirectReturnResult(QualType Ty, CCState &State) const;
1010 /// Return the alignment to use for the given type on the stack.
1011 unsigned getTypeStackAlignInBytes(QualType Ty, unsigned Align) const;
1013 Class classify(QualType Ty) const;
1014 ABIArgInfo classifyReturnType(QualType RetTy, CCState &State) const;
1015 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
1017 /// Updates the number of available free registers, returns
1018 /// true if any registers were allocated.
1019 bool updateFreeRegs(QualType Ty, CCState &State) const;
1021 bool shouldAggregateUseDirect(QualType Ty, CCState &State, bool &InReg,
1022 bool &NeedsPadding) const;
1023 bool shouldPrimitiveUseInReg(QualType Ty, CCState &State) const;
1025 bool canExpandIndirectArgument(QualType Ty) const;
1027 /// Rewrite the function info so that all memory arguments use
1029 void rewriteWithInAlloca(CGFunctionInfo &FI) const;
1031 void addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1032 CharUnits &StackOffset, ABIArgInfo &Info,
1033 QualType Type) const;
1034 void computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1035 bool &UsedInAlloca) const;
1039 void computeInfo(CGFunctionInfo &FI) const override;
1040 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
1041 QualType Ty) const override;
1043 X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1044 bool RetSmallStructInRegABI, bool Win32StructABI,
1045 unsigned NumRegisterParameters, bool SoftFloatABI)
1046 : SwiftABIInfo(CGT), IsDarwinVectorABI(DarwinVectorABI),
1047 IsRetSmallStructInRegABI(RetSmallStructInRegABI),
1048 IsWin32StructABI(Win32StructABI),
1049 IsSoftFloatABI(SoftFloatABI),
1050 IsMCUABI(CGT.getTarget().getTriple().isOSIAMCU()),
1051 DefaultNumRegisterParameters(NumRegisterParameters) {}
1053 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
1054 bool asReturnValue) const override {
1055 // LLVM's x86-32 lowering currently only assigns up to three
1056 // integer registers and three fp registers. Oddly, it'll use up to
1057 // four vector registers for vectors, but those can overlap with the
1058 // scalar registers.
1059 return occupiesMoreThan(CGT, scalars, /*total*/ 3);
1062 bool isSwiftErrorInRegister() const override {
1063 // x86-32 lowering does not support passing swifterror in a register.
1068 class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
1070 X86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, bool DarwinVectorABI,
1071 bool RetSmallStructInRegABI, bool Win32StructABI,
1072 unsigned NumRegisterParameters, bool SoftFloatABI)
1073 : TargetCodeGenInfo(new X86_32ABIInfo(
1074 CGT, DarwinVectorABI, RetSmallStructInRegABI, Win32StructABI,
1075 NumRegisterParameters, SoftFloatABI)) {}
1077 static bool isStructReturnInRegABI(
1078 const llvm::Triple &Triple, const CodeGenOptions &Opts);
1080 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
1081 CodeGen::CodeGenModule &CGM) const override;
1083 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
1084 // Darwin uses different dwarf register numbers for EH.
1085 if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
1089 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
1090 llvm::Value *Address) const override;
1092 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
1093 StringRef Constraint,
1094 llvm::Type* Ty) const override {
1095 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
1098 void addReturnRegisterOutputs(CodeGenFunction &CGF, LValue ReturnValue,
1099 std::string &Constraints,
1100 std::vector<llvm::Type *> &ResultRegTypes,
1101 std::vector<llvm::Type *> &ResultTruncRegTypes,
1102 std::vector<LValue> &ResultRegDests,
1103 std::string &AsmString,
1104 unsigned NumOutputs) const override;
1107 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
1108 unsigned Sig = (0xeb << 0) | // jmp rel8
1109 (0x06 << 8) | // .+0x08
1112 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
1115 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
1116 return "movl\t%ebp, %ebp"
1117 "\t\t// marker for objc_retainAutoreleaseReturnValue";
1123 /// Rewrite input constraint references after adding some output constraints.
1124 /// In the case where there is one output and one input and we add one output,
1125 /// we need to replace all operand references greater than or equal to 1:
1128 /// The result will be:
1131 static void rewriteInputConstraintReferences(unsigned FirstIn,
1132 unsigned NumNewOuts,
1133 std::string &AsmString) {
1135 llvm::raw_string_ostream OS(Buf);
1137 while (Pos < AsmString.size()) {
1138 size_t DollarStart = AsmString.find('$', Pos);
1139 if (DollarStart == std::string::npos)
1140 DollarStart = AsmString.size();
1141 size_t DollarEnd = AsmString.find_first_not_of('$', DollarStart);
1142 if (DollarEnd == std::string::npos)
1143 DollarEnd = AsmString.size();
1144 OS << StringRef(&AsmString[Pos], DollarEnd - Pos);
1146 size_t NumDollars = DollarEnd - DollarStart;
1147 if (NumDollars % 2 != 0 && Pos < AsmString.size()) {
1148 // We have an operand reference.
1149 size_t DigitStart = Pos;
1150 size_t DigitEnd = AsmString.find_first_not_of("0123456789", DigitStart);
1151 if (DigitEnd == std::string::npos)
1152 DigitEnd = AsmString.size();
1153 StringRef OperandStr(&AsmString[DigitStart], DigitEnd - DigitStart);
1154 unsigned OperandIndex;
1155 if (!OperandStr.getAsInteger(10, OperandIndex)) {
1156 if (OperandIndex >= FirstIn)
1157 OperandIndex += NumNewOuts;
1165 AsmString = std::move(OS.str());
1168 /// Add output constraints for EAX:EDX because they are return registers.
1169 void X86_32TargetCodeGenInfo::addReturnRegisterOutputs(
1170 CodeGenFunction &CGF, LValue ReturnSlot, std::string &Constraints,
1171 std::vector<llvm::Type *> &ResultRegTypes,
1172 std::vector<llvm::Type *> &ResultTruncRegTypes,
1173 std::vector<LValue> &ResultRegDests, std::string &AsmString,
1174 unsigned NumOutputs) const {
1175 uint64_t RetWidth = CGF.getContext().getTypeSize(ReturnSlot.getType());
1177 // Use the EAX constraint if the width is 32 or smaller and EAX:EDX if it is
1179 if (!Constraints.empty())
1181 if (RetWidth <= 32) {
1182 Constraints += "={eax}";
1183 ResultRegTypes.push_back(CGF.Int32Ty);
1185 // Use the 'A' constraint for EAX:EDX.
1186 Constraints += "=A";
1187 ResultRegTypes.push_back(CGF.Int64Ty);
1190 // Truncate EAX or EAX:EDX to an integer of the appropriate size.
1191 llvm::Type *CoerceTy = llvm::IntegerType::get(CGF.getLLVMContext(), RetWidth);
1192 ResultTruncRegTypes.push_back(CoerceTy);
1194 // Coerce the integer by bitcasting the return slot pointer.
1195 ReturnSlot.setAddress(CGF.Builder.CreateBitCast(ReturnSlot.getAddress(),
1196 CoerceTy->getPointerTo()));
1197 ResultRegDests.push_back(ReturnSlot);
1199 rewriteInputConstraintReferences(NumOutputs, 1, AsmString);
1202 /// shouldReturnTypeInRegister - Determine if the given type should be
1203 /// returned in a register (for the Darwin and MCU ABI).
1204 bool X86_32ABIInfo::shouldReturnTypeInRegister(QualType Ty,
1205 ASTContext &Context) const {
1206 uint64_t Size = Context.getTypeSize(Ty);
1208 // For i386, type must be register sized.
1209 // For the MCU ABI, it only needs to be <= 8-byte
1210 if ((IsMCUABI && Size > 64) || (!IsMCUABI && !isRegisterSize(Size)))
1213 if (Ty->isVectorType()) {
1214 // 64- and 128- bit vectors inside structures are not returned in
1216 if (Size == 64 || Size == 128)
1222 // If this is a builtin, pointer, enum, complex type, member pointer, or
1223 // member function pointer it is ok.
1224 if (Ty->getAs<BuiltinType>() || Ty->hasPointerRepresentation() ||
1225 Ty->isAnyComplexType() || Ty->isEnumeralType() ||
1226 Ty->isBlockPointerType() || Ty->isMemberPointerType())
1229 // Arrays are treated like records.
1230 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty))
1231 return shouldReturnTypeInRegister(AT->getElementType(), Context);
1233 // Otherwise, it must be a record type.
1234 const RecordType *RT = Ty->getAs<RecordType>();
1235 if (!RT) return false;
1237 // FIXME: Traverse bases here too.
1239 // Structure types are passed in register if all fields would be
1240 // passed in a register.
1241 for (const auto *FD : RT->getDecl()->fields()) {
1242 // Empty fields are ignored.
1243 if (isEmptyField(Context, FD, true))
1246 // Check fields recursively.
1247 if (!shouldReturnTypeInRegister(FD->getType(), Context))
1253 static bool is32Or64BitBasicType(QualType Ty, ASTContext &Context) {
1254 // Treat complex types as the element type.
1255 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
1256 Ty = CTy->getElementType();
1258 // Check for a type which we know has a simple scalar argument-passing
1259 // convention without any padding. (We're specifically looking for 32
1260 // and 64-bit integer and integer-equivalents, float, and double.)
1261 if (!Ty->getAs<BuiltinType>() && !Ty->hasPointerRepresentation() &&
1262 !Ty->isEnumeralType() && !Ty->isBlockPointerType())
1265 uint64_t Size = Context.getTypeSize(Ty);
1266 return Size == 32 || Size == 64;
1269 static bool addFieldSizes(ASTContext &Context, const RecordDecl *RD,
1271 for (const auto *FD : RD->fields()) {
1272 // Scalar arguments on the stack get 4 byte alignment on x86. If the
1273 // argument is smaller than 32-bits, expanding the struct will create
1274 // alignment padding.
1275 if (!is32Or64BitBasicType(FD->getType(), Context))
1278 // FIXME: Reject bit-fields wholesale; there are two problems, we don't know
1279 // how to expand them yet, and the predicate for telling if a bitfield still
1280 // counts as "basic" is more complicated than what we were doing previously.
1281 if (FD->isBitField())
1284 Size += Context.getTypeSize(FD->getType());
1289 static bool addBaseAndFieldSizes(ASTContext &Context, const CXXRecordDecl *RD,
1291 // Don't do this if there are any non-empty bases.
1292 for (const CXXBaseSpecifier &Base : RD->bases()) {
1293 if (!addBaseAndFieldSizes(Context, Base.getType()->getAsCXXRecordDecl(),
1297 if (!addFieldSizes(Context, RD, Size))
1302 /// Test whether an argument type which is to be passed indirectly (on the
1303 /// stack) would have the equivalent layout if it was expanded into separate
1304 /// arguments. If so, we prefer to do the latter to avoid inhibiting
1306 bool X86_32ABIInfo::canExpandIndirectArgument(QualType Ty) const {
1307 // We can only expand structure types.
1308 const RecordType *RT = Ty->getAs<RecordType>();
1311 const RecordDecl *RD = RT->getDecl();
1313 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1314 if (!IsWin32StructABI) {
1315 // On non-Windows, we have to conservatively match our old bitcode
1316 // prototypes in order to be ABI-compatible at the bitcode level.
1317 if (!CXXRD->isCLike())
1320 // Don't do this for dynamic classes.
1321 if (CXXRD->isDynamicClass())
1324 if (!addBaseAndFieldSizes(getContext(), CXXRD, Size))
1327 if (!addFieldSizes(getContext(), RD, Size))
1331 // We can do this if there was no alignment padding.
1332 return Size == getContext().getTypeSize(Ty);
1335 ABIArgInfo X86_32ABIInfo::getIndirectReturnResult(QualType RetTy, CCState &State) const {
1336 // If the return value is indirect, then the hidden argument is consuming one
1337 // integer register.
1338 if (State.FreeRegs) {
1341 return getNaturalAlignIndirectInReg(RetTy);
1343 return getNaturalAlignIndirect(RetTy, /*ByVal=*/false);
1346 ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
1347 CCState &State) const {
1348 if (RetTy->isVoidType())
1349 return ABIArgInfo::getIgnore();
1351 const Type *Base = nullptr;
1352 uint64_t NumElts = 0;
1353 if ((State.CC == llvm::CallingConv::X86_VectorCall ||
1354 State.CC == llvm::CallingConv::X86_RegCall) &&
1355 isHomogeneousAggregate(RetTy, Base, NumElts)) {
1356 // The LLVM struct type for such an aggregate should lower properly.
1357 return ABIArgInfo::getDirect();
1360 if (const VectorType *VT = RetTy->getAs<VectorType>()) {
1361 // On Darwin, some vectors are returned in registers.
1362 if (IsDarwinVectorABI) {
1363 uint64_t Size = getContext().getTypeSize(RetTy);
1365 // 128-bit vectors are a special case; they are returned in
1366 // registers and we need to make sure to pick a type the LLVM
1367 // backend will like.
1369 return ABIArgInfo::getDirect(llvm::VectorType::get(
1370 llvm::Type::getInt64Ty(getVMContext()), 2));
1372 // Always return in register if it fits in a general purpose
1373 // register, or if it is 64 bits and has a single element.
1374 if ((Size == 8 || Size == 16 || Size == 32) ||
1375 (Size == 64 && VT->getNumElements() == 1))
1376 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1379 return getIndirectReturnResult(RetTy, State);
1382 return ABIArgInfo::getDirect();
1385 if (isAggregateTypeForABI(RetTy)) {
1386 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
1387 // Structures with flexible arrays are always indirect.
1388 if (RT->getDecl()->hasFlexibleArrayMember())
1389 return getIndirectReturnResult(RetTy, State);
1392 // If specified, structs and unions are always indirect.
1393 if (!IsRetSmallStructInRegABI && !RetTy->isAnyComplexType())
1394 return getIndirectReturnResult(RetTy, State);
1396 // Ignore empty structs/unions.
1397 if (isEmptyRecord(getContext(), RetTy, true))
1398 return ABIArgInfo::getIgnore();
1400 // Small structures which are register sized are generally returned
1402 if (shouldReturnTypeInRegister(RetTy, getContext())) {
1403 uint64_t Size = getContext().getTypeSize(RetTy);
1405 // As a special-case, if the struct is a "single-element" struct, and
1406 // the field is of type "float" or "double", return it in a
1407 // floating-point register. (MSVC does not apply this special case.)
1408 // We apply a similar transformation for pointer types to improve the
1409 // quality of the generated IR.
1410 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
1411 if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
1412 || SeltTy->hasPointerRepresentation())
1413 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
1415 // FIXME: We should be able to narrow this integer in cases with dead
1417 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),Size));
1420 return getIndirectReturnResult(RetTy, State);
1423 // Treat an enum type as its underlying type.
1424 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
1425 RetTy = EnumTy->getDecl()->getIntegerType();
1427 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
1428 : ABIArgInfo::getDirect());
1431 static bool isSSEVectorType(ASTContext &Context, QualType Ty) {
1432 return Ty->getAs<VectorType>() && Context.getTypeSize(Ty) == 128;
1435 static bool isRecordWithSSEVectorType(ASTContext &Context, QualType Ty) {
1436 const RecordType *RT = Ty->getAs<RecordType>();
1439 const RecordDecl *RD = RT->getDecl();
1441 // If this is a C++ record, check the bases first.
1442 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
1443 for (const auto &I : CXXRD->bases())
1444 if (!isRecordWithSSEVectorType(Context, I.getType()))
1447 for (const auto *i : RD->fields()) {
1448 QualType FT = i->getType();
1450 if (isSSEVectorType(Context, FT))
1453 if (isRecordWithSSEVectorType(Context, FT))
1460 unsigned X86_32ABIInfo::getTypeStackAlignInBytes(QualType Ty,
1461 unsigned Align) const {
1462 // Otherwise, if the alignment is less than or equal to the minimum ABI
1463 // alignment, just use the default; the backend will handle this.
1464 if (Align <= MinABIStackAlignInBytes)
1465 return 0; // Use default alignment.
1467 // On non-Darwin, the stack type alignment is always 4.
1468 if (!IsDarwinVectorABI) {
1469 // Set explicit alignment, since we may need to realign the top.
1470 return MinABIStackAlignInBytes;
1473 // Otherwise, if the type contains an SSE vector type, the alignment is 16.
1474 if (Align >= 16 && (isSSEVectorType(getContext(), Ty) ||
1475 isRecordWithSSEVectorType(getContext(), Ty)))
1478 return MinABIStackAlignInBytes;
1481 ABIArgInfo X86_32ABIInfo::getIndirectResult(QualType Ty, bool ByVal,
1482 CCState &State) const {
1484 if (State.FreeRegs) {
1485 --State.FreeRegs; // Non-byval indirects just use one pointer.
1487 return getNaturalAlignIndirectInReg(Ty);
1489 return getNaturalAlignIndirect(Ty, false);
1492 // Compute the byval alignment.
1493 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
1494 unsigned StackAlign = getTypeStackAlignInBytes(Ty, TypeAlign);
1495 if (StackAlign == 0)
1496 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true);
1498 // If the stack alignment is less than the type alignment, realign the
1500 bool Realign = TypeAlign > StackAlign;
1501 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(StackAlign),
1502 /*ByVal=*/true, Realign);
1505 X86_32ABIInfo::Class X86_32ABIInfo::classify(QualType Ty) const {
1506 const Type *T = isSingleElementStruct(Ty, getContext());
1508 T = Ty.getTypePtr();
1510 if (const BuiltinType *BT = T->getAs<BuiltinType>()) {
1511 BuiltinType::Kind K = BT->getKind();
1512 if (K == BuiltinType::Float || K == BuiltinType::Double)
1518 bool X86_32ABIInfo::updateFreeRegs(QualType Ty, CCState &State) const {
1519 if (!IsSoftFloatABI) {
1520 Class C = classify(Ty);
1525 unsigned Size = getContext().getTypeSize(Ty);
1526 unsigned SizeInRegs = (Size + 31) / 32;
1528 if (SizeInRegs == 0)
1532 if (SizeInRegs > State.FreeRegs) {
1537 // The MCU psABI allows passing parameters in-reg even if there are
1538 // earlier parameters that are passed on the stack. Also,
1539 // it does not allow passing >8-byte structs in-register,
1540 // even if there are 3 free registers available.
1541 if (SizeInRegs > State.FreeRegs || SizeInRegs > 2)
1545 State.FreeRegs -= SizeInRegs;
1549 bool X86_32ABIInfo::shouldAggregateUseDirect(QualType Ty, CCState &State,
1551 bool &NeedsPadding) const {
1552 // On Windows, aggregates other than HFAs are never passed in registers, and
1553 // they do not consume register slots. Homogenous floating-point aggregates
1554 // (HFAs) have already been dealt with at this point.
1555 if (IsWin32StructABI && isAggregateTypeForABI(Ty))
1558 NeedsPadding = false;
1561 if (!updateFreeRegs(Ty, State))
1567 if (State.CC == llvm::CallingConv::X86_FastCall ||
1568 State.CC == llvm::CallingConv::X86_VectorCall ||
1569 State.CC == llvm::CallingConv::X86_RegCall) {
1570 if (getContext().getTypeSize(Ty) <= 32 && State.FreeRegs)
1571 NeedsPadding = true;
1579 bool X86_32ABIInfo::shouldPrimitiveUseInReg(QualType Ty, CCState &State) const {
1580 if (!updateFreeRegs(Ty, State))
1586 if (State.CC == llvm::CallingConv::X86_FastCall ||
1587 State.CC == llvm::CallingConv::X86_VectorCall ||
1588 State.CC == llvm::CallingConv::X86_RegCall) {
1589 if (getContext().getTypeSize(Ty) > 32)
1592 return (Ty->isIntegralOrEnumerationType() || Ty->isPointerType() ||
1593 Ty->isReferenceType());
1599 ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
1600 CCState &State) const {
1601 // FIXME: Set alignment on indirect arguments.
1603 Ty = useFirstFieldIfTransparentUnion(Ty);
1605 // Check with the C++ ABI first.
1606 const RecordType *RT = Ty->getAs<RecordType>();
1608 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
1609 if (RAA == CGCXXABI::RAA_Indirect) {
1610 return getIndirectResult(Ty, false, State);
1611 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
1612 // The field index doesn't matter, we'll fix it up later.
1613 return ABIArgInfo::getInAlloca(/*FieldIndex=*/0);
1617 // Regcall uses the concept of a homogenous vector aggregate, similar
1618 // to other targets.
1619 const Type *Base = nullptr;
1620 uint64_t NumElts = 0;
1621 if (State.CC == llvm::CallingConv::X86_RegCall &&
1622 isHomogeneousAggregate(Ty, Base, NumElts)) {
1624 if (State.FreeSSERegs >= NumElts) {
1625 State.FreeSSERegs -= NumElts;
1626 if (Ty->isBuiltinType() || Ty->isVectorType())
1627 return ABIArgInfo::getDirect();
1628 return ABIArgInfo::getExpand();
1630 return getIndirectResult(Ty, /*ByVal=*/false, State);
1633 if (isAggregateTypeForABI(Ty)) {
1634 // Structures with flexible arrays are always indirect.
1635 // FIXME: This should not be byval!
1636 if (RT && RT->getDecl()->hasFlexibleArrayMember())
1637 return getIndirectResult(Ty, true, State);
1639 // Ignore empty structs/unions on non-Windows.
1640 if (!IsWin32StructABI && isEmptyRecord(getContext(), Ty, true))
1641 return ABIArgInfo::getIgnore();
1643 llvm::LLVMContext &LLVMContext = getVMContext();
1644 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
1645 bool NeedsPadding = false;
1647 if (shouldAggregateUseDirect(Ty, State, InReg, NeedsPadding)) {
1648 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
1649 SmallVector<llvm::Type*, 3> Elements(SizeInRegs, Int32);
1650 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
1652 return ABIArgInfo::getDirectInReg(Result);
1654 return ABIArgInfo::getDirect(Result);
1656 llvm::IntegerType *PaddingType = NeedsPadding ? Int32 : nullptr;
1658 // Expand small (<= 128-bit) record types when we know that the stack layout
1659 // of those arguments will match the struct. This is important because the
1660 // LLVM backend isn't smart enough to remove byval, which inhibits many
1662 // Don't do this for the MCU if there are still free integer registers
1663 // (see X86_64 ABI for full explanation).
1664 if (getContext().getTypeSize(Ty) <= 4 * 32 &&
1665 (!IsMCUABI || State.FreeRegs == 0) && canExpandIndirectArgument(Ty))
1666 return ABIArgInfo::getExpandWithPadding(
1667 State.CC == llvm::CallingConv::X86_FastCall ||
1668 State.CC == llvm::CallingConv::X86_VectorCall ||
1669 State.CC == llvm::CallingConv::X86_RegCall,
1672 return getIndirectResult(Ty, true, State);
1675 if (const VectorType *VT = Ty->getAs<VectorType>()) {
1676 // On Darwin, some vectors are passed in memory, we handle this by passing
1677 // it as an i8/i16/i32/i64.
1678 if (IsDarwinVectorABI) {
1679 uint64_t Size = getContext().getTypeSize(Ty);
1680 if ((Size == 8 || Size == 16 || Size == 32) ||
1681 (Size == 64 && VT->getNumElements() == 1))
1682 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
1686 if (IsX86_MMXType(CGT.ConvertType(Ty)))
1687 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), 64));
1689 return ABIArgInfo::getDirect();
1693 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
1694 Ty = EnumTy->getDecl()->getIntegerType();
1696 bool InReg = shouldPrimitiveUseInReg(Ty, State);
1698 if (Ty->isPromotableIntegerType()) {
1700 return ABIArgInfo::getExtendInReg(Ty);
1701 return ABIArgInfo::getExtend(Ty);
1705 return ABIArgInfo::getDirectInReg();
1706 return ABIArgInfo::getDirect();
1709 void X86_32ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI, CCState &State,
1710 bool &UsedInAlloca) const {
1711 // Vectorcall x86 works subtly different than in x64, so the format is
1712 // a bit different than the x64 version. First, all vector types (not HVAs)
1713 // are assigned, with the first 6 ending up in the YMM0-5 or XMM0-5 registers.
1714 // This differs from the x64 implementation, where the first 6 by INDEX get
1716 // After that, integers AND HVAs are assigned Left to Right in the same pass.
1717 // Integers are passed as ECX/EDX if one is available (in order). HVAs will
1718 // first take up the remaining YMM/XMM registers. If insufficient registers
1719 // remain but an integer register (ECX/EDX) is available, it will be passed
1720 // in that, else, on the stack.
1721 for (auto &I : FI.arguments()) {
1722 // First pass do all the vector types.
1723 const Type *Base = nullptr;
1724 uint64_t NumElts = 0;
1725 const QualType& Ty = I.type;
1726 if ((Ty->isVectorType() || Ty->isBuiltinType()) &&
1727 isHomogeneousAggregate(Ty, Base, NumElts)) {
1728 if (State.FreeSSERegs >= NumElts) {
1729 State.FreeSSERegs -= NumElts;
1730 I.info = ABIArgInfo::getDirect();
1732 I.info = classifyArgumentType(Ty, State);
1734 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1738 for (auto &I : FI.arguments()) {
1739 // Second pass, do the rest!
1740 const Type *Base = nullptr;
1741 uint64_t NumElts = 0;
1742 const QualType& Ty = I.type;
1743 bool IsHva = isHomogeneousAggregate(Ty, Base, NumElts);
1745 if (IsHva && !Ty->isVectorType() && !Ty->isBuiltinType()) {
1746 // Assign true HVAs (non vector/native FP types).
1747 if (State.FreeSSERegs >= NumElts) {
1748 State.FreeSSERegs -= NumElts;
1749 I.info = getDirectX86Hva();
1751 I.info = getIndirectResult(Ty, /*ByVal=*/false, State);
1753 } else if (!IsHva) {
1754 // Assign all Non-HVAs, so this will exclude Vector/FP args.
1755 I.info = classifyArgumentType(Ty, State);
1756 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1761 void X86_32ABIInfo::computeInfo(CGFunctionInfo &FI) const {
1762 CCState State(FI.getCallingConvention());
1765 else if (State.CC == llvm::CallingConv::X86_FastCall)
1767 else if (State.CC == llvm::CallingConv::X86_VectorCall) {
1769 State.FreeSSERegs = 6;
1770 } else if (FI.getHasRegParm())
1771 State.FreeRegs = FI.getRegParm();
1772 else if (State.CC == llvm::CallingConv::X86_RegCall) {
1774 State.FreeSSERegs = 8;
1776 State.FreeRegs = DefaultNumRegisterParameters;
1778 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
1779 FI.getReturnInfo() = classifyReturnType(FI.getReturnType(), State);
1780 } else if (FI.getReturnInfo().isIndirect()) {
1781 // The C++ ABI is not aware of register usage, so we have to check if the
1782 // return value was sret and put it in a register ourselves if appropriate.
1783 if (State.FreeRegs) {
1784 --State.FreeRegs; // The sret parameter consumes a register.
1786 FI.getReturnInfo().setInReg(true);
1790 // The chain argument effectively gives us another free register.
1791 if (FI.isChainCall())
1794 bool UsedInAlloca = false;
1795 if (State.CC == llvm::CallingConv::X86_VectorCall) {
1796 computeVectorCallArgs(FI, State, UsedInAlloca);
1798 // If not vectorcall, revert to normal behavior.
1799 for (auto &I : FI.arguments()) {
1800 I.info = classifyArgumentType(I.type, State);
1801 UsedInAlloca |= (I.info.getKind() == ABIArgInfo::InAlloca);
1805 // If we needed to use inalloca for any argument, do a second pass and rewrite
1806 // all the memory arguments to use inalloca.
1808 rewriteWithInAlloca(FI);
1812 X86_32ABIInfo::addFieldToArgStruct(SmallVector<llvm::Type *, 6> &FrameFields,
1813 CharUnits &StackOffset, ABIArgInfo &Info,
1814 QualType Type) const {
1815 // Arguments are always 4-byte-aligned.
1816 CharUnits FieldAlign = CharUnits::fromQuantity(4);
1818 assert(StackOffset.isMultipleOf(FieldAlign) && "unaligned inalloca struct");
1819 Info = ABIArgInfo::getInAlloca(FrameFields.size());
1820 FrameFields.push_back(CGT.ConvertTypeForMem(Type));
1821 StackOffset += getContext().getTypeSizeInChars(Type);
1823 // Insert padding bytes to respect alignment.
1824 CharUnits FieldEnd = StackOffset;
1825 StackOffset = FieldEnd.alignTo(FieldAlign);
1826 if (StackOffset != FieldEnd) {
1827 CharUnits NumBytes = StackOffset - FieldEnd;
1828 llvm::Type *Ty = llvm::Type::getInt8Ty(getVMContext());
1829 Ty = llvm::ArrayType::get(Ty, NumBytes.getQuantity());
1830 FrameFields.push_back(Ty);
1834 static bool isArgInAlloca(const ABIArgInfo &Info) {
1835 // Leave ignored and inreg arguments alone.
1836 switch (Info.getKind()) {
1837 case ABIArgInfo::InAlloca:
1839 case ABIArgInfo::Indirect:
1840 assert(Info.getIndirectByVal());
1842 case ABIArgInfo::Ignore:
1844 case ABIArgInfo::Direct:
1845 case ABIArgInfo::Extend:
1846 if (Info.getInReg())
1849 case ABIArgInfo::Expand:
1850 case ABIArgInfo::CoerceAndExpand:
1851 // These are aggregate types which are never passed in registers when
1852 // inalloca is involved.
1855 llvm_unreachable("invalid enum");
1858 void X86_32ABIInfo::rewriteWithInAlloca(CGFunctionInfo &FI) const {
1859 assert(IsWin32StructABI && "inalloca only supported on win32");
1861 // Build a packed struct type for all of the arguments in memory.
1862 SmallVector<llvm::Type *, 6> FrameFields;
1864 // The stack alignment is always 4.
1865 CharUnits StackAlign = CharUnits::fromQuantity(4);
1867 CharUnits StackOffset;
1868 CGFunctionInfo::arg_iterator I = FI.arg_begin(), E = FI.arg_end();
1870 // Put 'this' into the struct before 'sret', if necessary.
1872 FI.getCallingConvention() == llvm::CallingConv::X86_ThisCall;
1873 ABIArgInfo &Ret = FI.getReturnInfo();
1874 if (Ret.isIndirect() && Ret.isSRetAfterThis() && !IsThisCall &&
1875 isArgInAlloca(I->info)) {
1876 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1880 // Put the sret parameter into the inalloca struct if it's in memory.
1881 if (Ret.isIndirect() && !Ret.getInReg()) {
1882 CanQualType PtrTy = getContext().getPointerType(FI.getReturnType());
1883 addFieldToArgStruct(FrameFields, StackOffset, Ret, PtrTy);
1884 // On Windows, the hidden sret parameter is always returned in eax.
1885 Ret.setInAllocaSRet(IsWin32StructABI);
1888 // Skip the 'this' parameter in ecx.
1892 // Put arguments passed in memory into the struct.
1893 for (; I != E; ++I) {
1894 if (isArgInAlloca(I->info))
1895 addFieldToArgStruct(FrameFields, StackOffset, I->info, I->type);
1898 FI.setArgStruct(llvm::StructType::get(getVMContext(), FrameFields,
1903 Address X86_32ABIInfo::EmitVAArg(CodeGenFunction &CGF,
1904 Address VAListAddr, QualType Ty) const {
1906 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
1908 // x86-32 changes the alignment of certain arguments on the stack.
1910 // Just messing with TypeInfo like this works because we never pass
1911 // anything indirectly.
1912 TypeInfo.second = CharUnits::fromQuantity(
1913 getTypeStackAlignInBytes(Ty, TypeInfo.second.getQuantity()));
1915 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
1916 TypeInfo, CharUnits::fromQuantity(4),
1917 /*AllowHigherAlign*/ true);
1920 bool X86_32TargetCodeGenInfo::isStructReturnInRegABI(
1921 const llvm::Triple &Triple, const CodeGenOptions &Opts) {
1922 assert(Triple.getArch() == llvm::Triple::x86);
1924 switch (Opts.getStructReturnConvention()) {
1925 case CodeGenOptions::SRCK_Default:
1927 case CodeGenOptions::SRCK_OnStack: // -fpcc-struct-return
1929 case CodeGenOptions::SRCK_InRegs: // -freg-struct-return
1933 if (Triple.isOSDarwin() || Triple.isOSIAMCU())
1936 switch (Triple.getOS()) {
1937 case llvm::Triple::DragonFly:
1938 case llvm::Triple::FreeBSD:
1939 case llvm::Triple::OpenBSD:
1940 case llvm::Triple::Win32:
1947 void X86_32TargetCodeGenInfo::setTargetAttributes(
1948 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
1949 if (GV->isDeclaration())
1951 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
1952 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
1953 llvm::Function *Fn = cast<llvm::Function>(GV);
1954 Fn->addFnAttr("stackrealign");
1956 if (FD->hasAttr<AnyX86InterruptAttr>()) {
1957 llvm::Function *Fn = cast<llvm::Function>(GV);
1958 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
1963 bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
1964 CodeGen::CodeGenFunction &CGF,
1965 llvm::Value *Address) const {
1966 CodeGen::CGBuilderTy &Builder = CGF.Builder;
1968 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
1970 // 0-7 are the eight integer registers; the order is different
1971 // on Darwin (for EH), but the range is the same.
1973 AssignToArrayRange(Builder, Address, Four8, 0, 8);
1975 if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
1976 // 12-16 are st(0..4). Not sure why we stop at 4.
1977 // These have size 16, which is sizeof(long double) on
1978 // platforms with 8-byte alignment for that type.
1979 llvm::Value *Sixteen8 = llvm::ConstantInt::get(CGF.Int8Ty, 16);
1980 AssignToArrayRange(Builder, Address, Sixteen8, 12, 16);
1983 // 9 is %eflags, which doesn't get a size on Darwin for some
1985 Builder.CreateAlignedStore(
1986 Four8, Builder.CreateConstInBoundsGEP1_32(CGF.Int8Ty, Address, 9),
1989 // 11-16 are st(0..5). Not sure why we stop at 5.
1990 // These have size 12, which is sizeof(long double) on
1991 // platforms with 4-byte alignment for that type.
1992 llvm::Value *Twelve8 = llvm::ConstantInt::get(CGF.Int8Ty, 12);
1993 AssignToArrayRange(Builder, Address, Twelve8, 11, 16);
1999 //===----------------------------------------------------------------------===//
2000 // X86-64 ABI Implementation
2001 //===----------------------------------------------------------------------===//
2005 /// The AVX ABI level for X86 targets.
2006 enum class X86AVXABILevel {
2012 /// \p returns the size in bits of the largest (native) vector for \p AVXLevel.
2013 static unsigned getNativeVectorSizeForAVXABI(X86AVXABILevel AVXLevel) {
2015 case X86AVXABILevel::AVX512:
2017 case X86AVXABILevel::AVX:
2019 case X86AVXABILevel::None:
2022 llvm_unreachable("Unknown AVXLevel");
2025 /// X86_64ABIInfo - The X86_64 ABI information.
2026 class X86_64ABIInfo : public SwiftABIInfo {
2038 /// merge - Implement the X86_64 ABI merging algorithm.
2040 /// Merge an accumulating classification \arg Accum with a field
2041 /// classification \arg Field.
2043 /// \param Accum - The accumulating classification. This should
2044 /// always be either NoClass or the result of a previous merge
2045 /// call. In addition, this should never be Memory (the caller
2046 /// should just return Memory for the aggregate).
2047 static Class merge(Class Accum, Class Field);
2049 /// postMerge - Implement the X86_64 ABI post merging algorithm.
2051 /// Post merger cleanup, reduces a malformed Hi and Lo pair to
2052 /// final MEMORY or SSE classes when necessary.
2054 /// \param AggregateSize - The size of the current aggregate in
2055 /// the classification process.
2057 /// \param Lo - The classification for the parts of the type
2058 /// residing in the low word of the containing object.
2060 /// \param Hi - The classification for the parts of the type
2061 /// residing in the higher words of the containing object.
2063 void postMerge(unsigned AggregateSize, Class &Lo, Class &Hi) const;
2065 /// classify - Determine the x86_64 register classes in which the
2066 /// given type T should be passed.
2068 /// \param Lo - The classification for the parts of the type
2069 /// residing in the low word of the containing object.
2071 /// \param Hi - The classification for the parts of the type
2072 /// residing in the high word of the containing object.
2074 /// \param OffsetBase - The bit offset of this type in the
2075 /// containing object. Some parameters are classified different
2076 /// depending on whether they straddle an eightbyte boundary.
2078 /// \param isNamedArg - Whether the argument in question is a "named"
2079 /// argument, as used in AMD64-ABI 3.5.7.
2081 /// If a word is unused its result will be NoClass; if a type should
2082 /// be passed in Memory then at least the classification of \arg Lo
2085 /// The \arg Lo class will be NoClass iff the argument is ignored.
2087 /// If the \arg Lo class is ComplexX87, then the \arg Hi class will
2088 /// also be ComplexX87.
2089 void classify(QualType T, uint64_t OffsetBase, Class &Lo, Class &Hi,
2090 bool isNamedArg) const;
2092 llvm::Type *GetByteVectorType(QualType Ty) const;
2093 llvm::Type *GetSSETypeAtOffset(llvm::Type *IRType,
2094 unsigned IROffset, QualType SourceTy,
2095 unsigned SourceOffset) const;
2096 llvm::Type *GetINTEGERTypeAtOffset(llvm::Type *IRType,
2097 unsigned IROffset, QualType SourceTy,
2098 unsigned SourceOffset) const;
2100 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2101 /// such that the argument will be returned in memory.
2102 ABIArgInfo getIndirectReturnResult(QualType Ty) const;
2104 /// getIndirectResult - Give a source type \arg Ty, return a suitable result
2105 /// such that the argument will be passed in memory.
2107 /// \param freeIntRegs - The number of free integer registers remaining
2109 ABIArgInfo getIndirectResult(QualType Ty, unsigned freeIntRegs) const;
2111 ABIArgInfo classifyReturnType(QualType RetTy) const;
2113 ABIArgInfo classifyArgumentType(QualType Ty, unsigned freeIntRegs,
2114 unsigned &neededInt, unsigned &neededSSE,
2115 bool isNamedArg) const;
2117 ABIArgInfo classifyRegCallStructType(QualType Ty, unsigned &NeededInt,
2118 unsigned &NeededSSE) const;
2120 ABIArgInfo classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
2121 unsigned &NeededSSE) const;
2123 bool IsIllegalVectorType(QualType Ty) const;
2125 /// The 0.98 ABI revision clarified a lot of ambiguities,
2126 /// unfortunately in ways that were not always consistent with
2127 /// certain previous compilers. In particular, platforms which
2128 /// required strict binary compatibility with older versions of GCC
2129 /// may need to exempt themselves.
2130 bool honorsRevision0_98() const {
2131 return !getTarget().getTriple().isOSDarwin();
2134 /// GCC classifies <1 x long long> as SSE but some platform ABIs choose to
2135 /// classify it as INTEGER (for compatibility with older clang compilers).
2136 bool classifyIntegerMMXAsSSE() const {
2137 // Clang <= 3.8 did not do this.
2138 if (getContext().getLangOpts().getClangABICompat() <=
2139 LangOptions::ClangABI::Ver3_8)
2142 const llvm::Triple &Triple = getTarget().getTriple();
2143 if (Triple.isOSDarwin() || Triple.getOS() == llvm::Triple::PS4)
2145 if (Triple.isOSFreeBSD() && Triple.getOSMajorVersion() >= 10)
2150 X86AVXABILevel AVXLevel;
2151 // Some ABIs (e.g. X32 ABI and Native Client OS) use 32 bit pointers on
2153 bool Has64BitPointers;
2156 X86_64ABIInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel) :
2157 SwiftABIInfo(CGT), AVXLevel(AVXLevel),
2158 Has64BitPointers(CGT.getDataLayout().getPointerSize(0) == 8) {
2161 bool isPassedUsingAVXType(QualType type) const {
2162 unsigned neededInt, neededSSE;
2163 // The freeIntRegs argument doesn't matter here.
2164 ABIArgInfo info = classifyArgumentType(type, 0, neededInt, neededSSE,
2165 /*isNamedArg*/true);
2166 if (info.isDirect()) {
2167 llvm::Type *ty = info.getCoerceToType();
2168 if (llvm::VectorType *vectorTy = dyn_cast_or_null<llvm::VectorType>(ty))
2169 return (vectorTy->getBitWidth() > 128);
2174 void computeInfo(CGFunctionInfo &FI) const override;
2176 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2177 QualType Ty) const override;
2178 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
2179 QualType Ty) const override;
2181 bool has64BitPointers() const {
2182 return Has64BitPointers;
2185 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
2186 bool asReturnValue) const override {
2187 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2189 bool isSwiftErrorInRegister() const override {
2194 /// WinX86_64ABIInfo - The Windows X86_64 ABI information.
2195 class WinX86_64ABIInfo : public SwiftABIInfo {
2197 WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT)
2198 : SwiftABIInfo(CGT),
2199 IsMingw64(getTarget().getTriple().isWindowsGNUEnvironment()) {}
2201 void computeInfo(CGFunctionInfo &FI) const override;
2203 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
2204 QualType Ty) const override;
2206 bool isHomogeneousAggregateBaseType(QualType Ty) const override {
2207 // FIXME: Assumes vectorcall is in use.
2208 return isX86VectorTypeForVectorCall(getContext(), Ty);
2211 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
2212 uint64_t NumMembers) const override {
2213 // FIXME: Assumes vectorcall is in use.
2214 return isX86VectorCallAggregateSmallEnough(NumMembers);
2217 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type *> scalars,
2218 bool asReturnValue) const override {
2219 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
2222 bool isSwiftErrorInRegister() const override {
2227 ABIArgInfo classify(QualType Ty, unsigned &FreeSSERegs, bool IsReturnType,
2228 bool IsVectorCall, bool IsRegCall) const;
2229 ABIArgInfo reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
2230 const ABIArgInfo ¤t) const;
2231 void computeVectorCallArgs(CGFunctionInfo &FI, unsigned FreeSSERegs,
2232 bool IsVectorCall, bool IsRegCall) const;
2237 class X86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2239 X86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2240 : TargetCodeGenInfo(new X86_64ABIInfo(CGT, AVXLevel)) {}
2242 const X86_64ABIInfo &getABIInfo() const {
2243 return static_cast<const X86_64ABIInfo&>(TargetCodeGenInfo::getABIInfo());
2246 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2250 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2251 llvm::Value *Address) const override {
2252 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2254 // 0-15 are the 16 integer registers.
2256 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2260 llvm::Type* adjustInlineAsmType(CodeGen::CodeGenFunction &CGF,
2261 StringRef Constraint,
2262 llvm::Type* Ty) const override {
2263 return X86AdjustInlineAsmType(CGF, Constraint, Ty);
2266 bool isNoProtoCallVariadic(const CallArgList &args,
2267 const FunctionNoProtoType *fnType) const override {
2268 // The default CC on x86-64 sets %al to the number of SSA
2269 // registers used, and GCC sets this when calling an unprototyped
2270 // function, so we override the default behavior. However, don't do
2271 // that when AVX types are involved: the ABI explicitly states it is
2272 // undefined, and it doesn't work in practice because of how the ABI
2273 // defines varargs anyway.
2274 if (fnType->getCallConv() == CC_C) {
2275 bool HasAVXType = false;
2276 for (CallArgList::const_iterator
2277 it = args.begin(), ie = args.end(); it != ie; ++it) {
2278 if (getABIInfo().isPassedUsingAVXType(it->Ty)) {
2288 return TargetCodeGenInfo::isNoProtoCallVariadic(args, fnType);
2292 getUBSanFunctionSignature(CodeGen::CodeGenModule &CGM) const override {
2293 unsigned Sig = (0xeb << 0) | // jmp rel8
2294 (0x06 << 8) | // .+0x08
2297 return llvm::ConstantInt::get(CGM.Int32Ty, Sig);
2300 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2301 CodeGen::CodeGenModule &CGM) const override {
2302 if (GV->isDeclaration())
2304 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2305 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2306 llvm::Function *Fn = cast<llvm::Function>(GV);
2307 Fn->addFnAttr("stackrealign");
2309 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2310 llvm::Function *Fn = cast<llvm::Function>(GV);
2311 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2317 class PS4TargetCodeGenInfo : public X86_64TargetCodeGenInfo {
2319 PS4TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, X86AVXABILevel AVXLevel)
2320 : X86_64TargetCodeGenInfo(CGT, AVXLevel) {}
2322 void getDependentLibraryOption(llvm::StringRef Lib,
2323 llvm::SmallString<24> &Opt) const override {
2325 // If the argument contains a space, enclose it in quotes.
2326 if (Lib.find(" ") != StringRef::npos)
2327 Opt += "\"" + Lib.str() + "\"";
2333 static std::string qualifyWindowsLibrary(llvm::StringRef Lib) {
2334 // If the argument does not end in .lib, automatically add the suffix.
2335 // If the argument contains a space, enclose it in quotes.
2336 // This matches the behavior of MSVC.
2337 bool Quote = (Lib.find(" ") != StringRef::npos);
2338 std::string ArgStr = Quote ? "\"" : "";
2340 if (!Lib.endswith_lower(".lib"))
2342 ArgStr += Quote ? "\"" : "";
2346 class WinX86_32TargetCodeGenInfo : public X86_32TargetCodeGenInfo {
2348 WinX86_32TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2349 bool DarwinVectorABI, bool RetSmallStructInRegABI, bool Win32StructABI,
2350 unsigned NumRegisterParameters)
2351 : X86_32TargetCodeGenInfo(CGT, DarwinVectorABI, RetSmallStructInRegABI,
2352 Win32StructABI, NumRegisterParameters, false) {}
2354 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2355 CodeGen::CodeGenModule &CGM) const override;
2357 void getDependentLibraryOption(llvm::StringRef Lib,
2358 llvm::SmallString<24> &Opt) const override {
2359 Opt = "/DEFAULTLIB:";
2360 Opt += qualifyWindowsLibrary(Lib);
2363 void getDetectMismatchOption(llvm::StringRef Name,
2364 llvm::StringRef Value,
2365 llvm::SmallString<32> &Opt) const override {
2366 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2370 static void addStackProbeTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2371 CodeGen::CodeGenModule &CGM) {
2372 if (llvm::Function *Fn = dyn_cast_or_null<llvm::Function>(GV)) {
2374 if (CGM.getCodeGenOpts().StackProbeSize != 4096)
2375 Fn->addFnAttr("stack-probe-size",
2376 llvm::utostr(CGM.getCodeGenOpts().StackProbeSize));
2377 if (CGM.getCodeGenOpts().NoStackArgProbe)
2378 Fn->addFnAttr("no-stack-arg-probe");
2382 void WinX86_32TargetCodeGenInfo::setTargetAttributes(
2383 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2384 X86_32TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2385 if (GV->isDeclaration())
2387 addStackProbeTargetAttributes(D, GV, CGM);
2390 class WinX86_64TargetCodeGenInfo : public TargetCodeGenInfo {
2392 WinX86_64TargetCodeGenInfo(CodeGen::CodeGenTypes &CGT,
2393 X86AVXABILevel AVXLevel)
2394 : TargetCodeGenInfo(new WinX86_64ABIInfo(CGT)) {}
2396 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
2397 CodeGen::CodeGenModule &CGM) const override;
2399 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
2403 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
2404 llvm::Value *Address) const override {
2405 llvm::Value *Eight8 = llvm::ConstantInt::get(CGF.Int8Ty, 8);
2407 // 0-15 are the 16 integer registers.
2409 AssignToArrayRange(CGF.Builder, Address, Eight8, 0, 16);
2413 void getDependentLibraryOption(llvm::StringRef Lib,
2414 llvm::SmallString<24> &Opt) const override {
2415 Opt = "/DEFAULTLIB:";
2416 Opt += qualifyWindowsLibrary(Lib);
2419 void getDetectMismatchOption(llvm::StringRef Name,
2420 llvm::StringRef Value,
2421 llvm::SmallString<32> &Opt) const override {
2422 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
2426 void WinX86_64TargetCodeGenInfo::setTargetAttributes(
2427 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
2428 TargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
2429 if (GV->isDeclaration())
2431 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
2432 if (FD->hasAttr<X86ForceAlignArgPointerAttr>()) {
2433 llvm::Function *Fn = cast<llvm::Function>(GV);
2434 Fn->addFnAttr("stackrealign");
2436 if (FD->hasAttr<AnyX86InterruptAttr>()) {
2437 llvm::Function *Fn = cast<llvm::Function>(GV);
2438 Fn->setCallingConv(llvm::CallingConv::X86_INTR);
2442 addStackProbeTargetAttributes(D, GV, CGM);
2446 void X86_64ABIInfo::postMerge(unsigned AggregateSize, Class &Lo,
2448 // AMD64-ABI 3.2.3p2: Rule 5. Then a post merger cleanup is done:
2450 // (a) If one of the classes is Memory, the whole argument is passed in
2453 // (b) If X87UP is not preceded by X87, the whole argument is passed in
2456 // (c) If the size of the aggregate exceeds two eightbytes and the first
2457 // eightbyte isn't SSE or any other eightbyte isn't SSEUP, the whole
2458 // argument is passed in memory. NOTE: This is necessary to keep the
2459 // ABI working for processors that don't support the __m256 type.
2461 // (d) If SSEUP is not preceded by SSE or SSEUP, it is converted to SSE.
2463 // Some of these are enforced by the merging logic. Others can arise
2464 // only with unions; for example:
2465 // union { _Complex double; unsigned; }
2467 // Note that clauses (b) and (c) were added in 0.98.
2471 if (Hi == X87Up && Lo != X87 && honorsRevision0_98())
2473 if (AggregateSize > 128 && (Lo != SSE || Hi != SSEUp))
2475 if (Hi == SSEUp && Lo != SSE)
2479 X86_64ABIInfo::Class X86_64ABIInfo::merge(Class Accum, Class Field) {
2480 // AMD64-ABI 3.2.3p2: Rule 4. Each field of an object is
2481 // classified recursively so that always two fields are
2482 // considered. The resulting class is calculated according to
2483 // the classes of the fields in the eightbyte:
2485 // (a) If both classes are equal, this is the resulting class.
2487 // (b) If one of the classes is NO_CLASS, the resulting class is
2490 // (c) If one of the classes is MEMORY, the result is the MEMORY
2493 // (d) If one of the classes is INTEGER, the result is the
2496 // (e) If one of the classes is X87, X87UP, COMPLEX_X87 class,
2497 // MEMORY is used as class.
2499 // (f) Otherwise class SSE is used.
2501 // Accum should never be memory (we should have returned) or
2502 // ComplexX87 (because this cannot be passed in a structure).
2503 assert((Accum != Memory && Accum != ComplexX87) &&
2504 "Invalid accumulated classification during merge.");
2505 if (Accum == Field || Field == NoClass)
2507 if (Field == Memory)
2509 if (Accum == NoClass)
2511 if (Accum == Integer || Field == Integer)
2513 if (Field == X87 || Field == X87Up || Field == ComplexX87 ||
2514 Accum == X87 || Accum == X87Up)
2519 void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
2520 Class &Lo, Class &Hi, bool isNamedArg) const {
2521 // FIXME: This code can be simplified by introducing a simple value class for
2522 // Class pairs with appropriate constructor methods for the various
2525 // FIXME: Some of the split computations are wrong; unaligned vectors
2526 // shouldn't be passed in registers for example, so there is no chance they
2527 // can straddle an eightbyte. Verify & simplify.
2531 Class &Current = OffsetBase < 64 ? Lo : Hi;
2534 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
2535 BuiltinType::Kind k = BT->getKind();
2537 if (k == BuiltinType::Void) {
2539 } else if (k == BuiltinType::Int128 || k == BuiltinType::UInt128) {
2542 } else if (k >= BuiltinType::Bool && k <= BuiltinType::LongLong) {
2544 } else if (k == BuiltinType::Float || k == BuiltinType::Double) {
2546 } else if (k == BuiltinType::LongDouble) {
2547 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2548 if (LDF == &llvm::APFloat::IEEEquad()) {
2551 } else if (LDF == &llvm::APFloat::x87DoubleExtended()) {
2554 } else if (LDF == &llvm::APFloat::IEEEdouble()) {
2557 llvm_unreachable("unexpected long double representation!");
2559 // FIXME: _Decimal32 and _Decimal64 are SSE.
2560 // FIXME: _float128 and _Decimal128 are (SSE, SSEUp).
2564 if (const EnumType *ET = Ty->getAs<EnumType>()) {
2565 // Classify the underlying integer type.
2566 classify(ET->getDecl()->getIntegerType(), OffsetBase, Lo, Hi, isNamedArg);
2570 if (Ty->hasPointerRepresentation()) {
2575 if (Ty->isMemberPointerType()) {
2576 if (Ty->isMemberFunctionPointerType()) {
2577 if (Has64BitPointers) {
2578 // If Has64BitPointers, this is an {i64, i64}, so classify both
2582 // Otherwise, with 32-bit pointers, this is an {i32, i32}. If that
2583 // straddles an eightbyte boundary, Hi should be classified as well.
2584 uint64_t EB_FuncPtr = (OffsetBase) / 64;
2585 uint64_t EB_ThisAdj = (OffsetBase + 64 - 1) / 64;
2586 if (EB_FuncPtr != EB_ThisAdj) {
2598 if (const VectorType *VT = Ty->getAs<VectorType>()) {
2599 uint64_t Size = getContext().getTypeSize(VT);
2600 if (Size == 1 || Size == 8 || Size == 16 || Size == 32) {
2601 // gcc passes the following as integer:
2602 // 4 bytes - <4 x char>, <2 x short>, <1 x int>, <1 x float>
2603 // 2 bytes - <2 x char>, <1 x short>
2604 // 1 byte - <1 x char>
2607 // If this type crosses an eightbyte boundary, it should be
2609 uint64_t EB_Lo = (OffsetBase) / 64;
2610 uint64_t EB_Hi = (OffsetBase + Size - 1) / 64;
2613 } else if (Size == 64) {
2614 QualType ElementType = VT->getElementType();
2616 // gcc passes <1 x double> in memory. :(
2617 if (ElementType->isSpecificBuiltinType(BuiltinType::Double))
2620 // gcc passes <1 x long long> as SSE but clang used to unconditionally
2621 // pass them as integer. For platforms where clang is the de facto
2622 // platform compiler, we must continue to use integer.
2623 if (!classifyIntegerMMXAsSSE() &&
2624 (ElementType->isSpecificBuiltinType(BuiltinType::LongLong) ||
2625 ElementType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
2626 ElementType->isSpecificBuiltinType(BuiltinType::Long) ||
2627 ElementType->isSpecificBuiltinType(BuiltinType::ULong)))
2632 // If this type crosses an eightbyte boundary, it should be
2634 if (OffsetBase && OffsetBase != 64)
2636 } else if (Size == 128 ||
2637 (isNamedArg && Size <= getNativeVectorSizeForAVXABI(AVXLevel))) {
2638 // Arguments of 256-bits are split into four eightbyte chunks. The
2639 // least significant one belongs to class SSE and all the others to class
2640 // SSEUP. The original Lo and Hi design considers that types can't be
2641 // greater than 128-bits, so a 64-bit split in Hi and Lo makes sense.
2642 // This design isn't correct for 256-bits, but since there're no cases
2643 // where the upper parts would need to be inspected, avoid adding
2644 // complexity and just consider Hi to match the 64-256 part.
2646 // Note that per 3.5.7 of AMD64-ABI, 256-bit args are only passed in
2647 // registers if they are "named", i.e. not part of the "..." of a
2648 // variadic function.
2650 // Similarly, per 3.2.3. of the AVX512 draft, 512-bits ("named") args are
2651 // split into eight eightbyte chunks, one SSE and seven SSEUP.
2658 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
2659 QualType ET = getContext().getCanonicalType(CT->getElementType());
2661 uint64_t Size = getContext().getTypeSize(Ty);
2662 if (ET->isIntegralOrEnumerationType()) {
2665 else if (Size <= 128)
2667 } else if (ET == getContext().FloatTy) {
2669 } else if (ET == getContext().DoubleTy) {
2671 } else if (ET == getContext().LongDoubleTy) {
2672 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
2673 if (LDF == &llvm::APFloat::IEEEquad())
2675 else if (LDF == &llvm::APFloat::x87DoubleExtended())
2676 Current = ComplexX87;
2677 else if (LDF == &llvm::APFloat::IEEEdouble())
2680 llvm_unreachable("unexpected long double representation!");
2683 // If this complex type crosses an eightbyte boundary then it
2685 uint64_t EB_Real = (OffsetBase) / 64;
2686 uint64_t EB_Imag = (OffsetBase + getContext().getTypeSize(ET)) / 64;
2687 if (Hi == NoClass && EB_Real != EB_Imag)
2693 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
2694 // Arrays are treated like structures.
2696 uint64_t Size = getContext().getTypeSize(Ty);
2698 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2699 // than eight eightbytes, ..., it has class MEMORY.
2703 // AMD64-ABI 3.2.3p2: Rule 1. If ..., or it contains unaligned
2704 // fields, it has class MEMORY.
2706 // Only need to check alignment of array base.
2707 if (OffsetBase % getContext().getTypeAlign(AT->getElementType()))
2710 // Otherwise implement simplified merge. We could be smarter about
2711 // this, but it isn't worth it and would be harder to verify.
2713 uint64_t EltSize = getContext().getTypeSize(AT->getElementType());
2714 uint64_t ArraySize = AT->getSize().getZExtValue();
2716 // The only case a 256-bit wide vector could be used is when the array
2717 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2718 // to work for sizes wider than 128, early check and fallback to memory.
2721 (Size != EltSize || Size > getNativeVectorSizeForAVXABI(AVXLevel)))
2724 for (uint64_t i=0, Offset=OffsetBase; i<ArraySize; ++i, Offset += EltSize) {
2725 Class FieldLo, FieldHi;
2726 classify(AT->getElementType(), Offset, FieldLo, FieldHi, isNamedArg);
2727 Lo = merge(Lo, FieldLo);
2728 Hi = merge(Hi, FieldHi);
2729 if (Lo == Memory || Hi == Memory)
2733 postMerge(Size, Lo, Hi);
2734 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp array classification.");
2738 if (const RecordType *RT = Ty->getAs<RecordType>()) {
2739 uint64_t Size = getContext().getTypeSize(Ty);
2741 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger
2742 // than eight eightbytes, ..., it has class MEMORY.
2746 // AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
2747 // copy constructor or a non-trivial destructor, it is passed by invisible
2749 if (getRecordArgABI(RT, getCXXABI()))
2752 const RecordDecl *RD = RT->getDecl();
2754 // Assume variable sized types are passed in memory.
2755 if (RD->hasFlexibleArrayMember())
2758 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2760 // Reset Lo class, this will be recomputed.
2763 // If this is a C++ record, classify the bases first.
2764 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
2765 for (const auto &I : CXXRD->bases()) {
2766 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
2767 "Unexpected base class!");
2768 const CXXRecordDecl *Base =
2769 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2771 // Classify this field.
2773 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate exceeds a
2774 // single eightbyte, each is classified separately. Each eightbyte gets
2775 // initialized to class NO_CLASS.
2776 Class FieldLo, FieldHi;
2778 OffsetBase + getContext().toBits(Layout.getBaseClassOffset(Base));
2779 classify(I.getType(), Offset, FieldLo, FieldHi, isNamedArg);
2780 Lo = merge(Lo, FieldLo);
2781 Hi = merge(Hi, FieldHi);
2782 if (Lo == Memory || Hi == Memory) {
2783 postMerge(Size, Lo, Hi);
2789 // Classify the fields one at a time, merging the results.
2791 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
2792 i != e; ++i, ++idx) {
2793 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2794 bool BitField = i->isBitField();
2796 // Ignore padding bit-fields.
2797 if (BitField && i->isUnnamedBitfield())
2800 // AMD64-ABI 3.2.3p2: Rule 1. If the size of an object is larger than
2801 // four eightbytes, or it contains unaligned fields, it has class MEMORY.
2803 // The only case a 256-bit wide vector could be used is when the struct
2804 // contains a single 256-bit element. Since Lo and Hi logic isn't extended
2805 // to work for sizes wider than 128, early check and fallback to memory.
2807 if (Size > 128 && (Size != getContext().getTypeSize(i->getType()) ||
2808 Size > getNativeVectorSizeForAVXABI(AVXLevel))) {
2810 postMerge(Size, Lo, Hi);
2813 // Note, skip this test for bit-fields, see below.
2814 if (!BitField && Offset % getContext().getTypeAlign(i->getType())) {
2816 postMerge(Size, Lo, Hi);
2820 // Classify this field.
2822 // AMD64-ABI 3.2.3p2: Rule 3. If the size of the aggregate
2823 // exceeds a single eightbyte, each is classified
2824 // separately. Each eightbyte gets initialized to class
2826 Class FieldLo, FieldHi;
2828 // Bit-fields require special handling, they do not force the
2829 // structure to be passed in memory even if unaligned, and
2830 // therefore they can straddle an eightbyte.
2832 assert(!i->isUnnamedBitfield());
2833 uint64_t Offset = OffsetBase + Layout.getFieldOffset(idx);
2834 uint64_t Size = i->getBitWidthValue(getContext());
2836 uint64_t EB_Lo = Offset / 64;
2837 uint64_t EB_Hi = (Offset + Size - 1) / 64;
2840 assert(EB_Hi == EB_Lo && "Invalid classification, type > 16 bytes.");
2845 FieldHi = EB_Hi ? Integer : NoClass;
2848 classify(i->getType(), Offset, FieldLo, FieldHi, isNamedArg);
2849 Lo = merge(Lo, FieldLo);
2850 Hi = merge(Hi, FieldHi);
2851 if (Lo == Memory || Hi == Memory)
2855 postMerge(Size, Lo, Hi);
2859 ABIArgInfo X86_64ABIInfo::getIndirectReturnResult(QualType Ty) const {
2860 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2862 if (!isAggregateTypeForABI(Ty)) {
2863 // Treat an enum type as its underlying type.
2864 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2865 Ty = EnumTy->getDecl()->getIntegerType();
2867 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2868 : ABIArgInfo::getDirect());
2871 return getNaturalAlignIndirect(Ty);
2874 bool X86_64ABIInfo::IsIllegalVectorType(QualType Ty) const {
2875 if (const VectorType *VecTy = Ty->getAs<VectorType>()) {
2876 uint64_t Size = getContext().getTypeSize(VecTy);
2877 unsigned LargestVector = getNativeVectorSizeForAVXABI(AVXLevel);
2878 if (Size <= 64 || Size > LargestVector)
2885 ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
2886 unsigned freeIntRegs) const {
2887 // If this is a scalar LLVM value then assume LLVM will pass it in the right
2890 // This assumption is optimistic, as there could be free registers available
2891 // when we need to pass this argument in memory, and LLVM could try to pass
2892 // the argument in the free register. This does not seem to happen currently,
2893 // but this code would be much safer if we could mark the argument with
2894 // 'onstack'. See PR12193.
2895 if (!isAggregateTypeForABI(Ty) && !IsIllegalVectorType(Ty)) {
2896 // Treat an enum type as its underlying type.
2897 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
2898 Ty = EnumTy->getDecl()->getIntegerType();
2900 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
2901 : ABIArgInfo::getDirect());
2904 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
2905 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
2907 // Compute the byval alignment. We specify the alignment of the byval in all
2908 // cases so that the mid-level optimizer knows the alignment of the byval.
2909 unsigned Align = std::max(getContext().getTypeAlign(Ty) / 8, 8U);
2911 // Attempt to avoid passing indirect results using byval when possible. This
2912 // is important for good codegen.
2914 // We do this by coercing the value into a scalar type which the backend can
2915 // handle naturally (i.e., without using byval).
2917 // For simplicity, we currently only do this when we have exhausted all of the
2918 // free integer registers. Doing this when there are free integer registers
2919 // would require more care, as we would have to ensure that the coerced value
2920 // did not claim the unused register. That would require either reording the
2921 // arguments to the function (so that any subsequent inreg values came first),
2922 // or only doing this optimization when there were no following arguments that
2925 // We currently expect it to be rare (particularly in well written code) for
2926 // arguments to be passed on the stack when there are still free integer
2927 // registers available (this would typically imply large structs being passed
2928 // by value), so this seems like a fair tradeoff for now.
2930 // We can revisit this if the backend grows support for 'onstack' parameter
2931 // attributes. See PR12193.
2932 if (freeIntRegs == 0) {
2933 uint64_t Size = getContext().getTypeSize(Ty);
2935 // If this type fits in an eightbyte, coerce it into the matching integral
2936 // type, which will end up on the stack (with alignment 8).
2937 if (Align == 8 && Size <= 64)
2938 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
2942 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(Align));
2945 /// The ABI specifies that a value should be passed in a full vector XMM/YMM
2946 /// register. Pick an LLVM IR type that will be passed as a vector register.
2947 llvm::Type *X86_64ABIInfo::GetByteVectorType(QualType Ty) const {
2948 // Wrapper structs/arrays that only contain vectors are passed just like
2949 // vectors; strip them off if present.
2950 if (const Type *InnerTy = isSingleElementStruct(Ty, getContext()))
2951 Ty = QualType(InnerTy, 0);
2953 llvm::Type *IRType = CGT.ConvertType(Ty);
2954 if (isa<llvm::VectorType>(IRType) ||
2955 IRType->getTypeID() == llvm::Type::FP128TyID)
2958 // We couldn't find the preferred IR vector type for 'Ty'.
2959 uint64_t Size = getContext().getTypeSize(Ty);
2960 assert((Size == 128 || Size == 256 || Size == 512) && "Invalid type found!");
2962 // Return a LLVM IR vector type based on the size of 'Ty'.
2963 return llvm::VectorType::get(llvm::Type::getDoubleTy(getVMContext()),
2967 /// BitsContainNoUserData - Return true if the specified [start,end) bit range
2968 /// is known to either be off the end of the specified type or being in
2969 /// alignment padding. The user type specified is known to be at most 128 bits
2970 /// in size, and have passed through X86_64ABIInfo::classify with a successful
2971 /// classification that put one of the two halves in the INTEGER class.
2973 /// It is conservatively correct to return false.
2974 static bool BitsContainNoUserData(QualType Ty, unsigned StartBit,
2975 unsigned EndBit, ASTContext &Context) {
2976 // If the bytes being queried are off the end of the type, there is no user
2977 // data hiding here. This handles analysis of builtins, vectors and other
2978 // types that don't contain interesting padding.
2979 unsigned TySize = (unsigned)Context.getTypeSize(Ty);
2980 if (TySize <= StartBit)
2983 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
2984 unsigned EltSize = (unsigned)Context.getTypeSize(AT->getElementType());
2985 unsigned NumElts = (unsigned)AT->getSize().getZExtValue();
2987 // Check each element to see if the element overlaps with the queried range.
2988 for (unsigned i = 0; i != NumElts; ++i) {
2989 // If the element is after the span we care about, then we're done..
2990 unsigned EltOffset = i*EltSize;
2991 if (EltOffset >= EndBit) break;
2993 unsigned EltStart = EltOffset < StartBit ? StartBit-EltOffset :0;
2994 if (!BitsContainNoUserData(AT->getElementType(), EltStart,
2995 EndBit-EltOffset, Context))
2998 // If it overlaps no elements, then it is safe to process as padding.
3002 if (const RecordType *RT = Ty->getAs<RecordType>()) {
3003 const RecordDecl *RD = RT->getDecl();
3004 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
3006 // If this is a C++ record, check the bases first.
3007 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
3008 for (const auto &I : CXXRD->bases()) {
3009 assert(!I.isVirtual() && !I.getType()->isDependentType() &&
3010 "Unexpected base class!");
3011 const CXXRecordDecl *Base =
3012 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
3014 // If the base is after the span we care about, ignore it.
3015 unsigned BaseOffset = Context.toBits(Layout.getBaseClassOffset(Base));
3016 if (BaseOffset >= EndBit) continue;
3018 unsigned BaseStart = BaseOffset < StartBit ? StartBit-BaseOffset :0;
3019 if (!BitsContainNoUserData(I.getType(), BaseStart,
3020 EndBit-BaseOffset, Context))
3025 // Verify that no field has data that overlaps the region of interest. Yes
3026 // this could be sped up a lot by being smarter about queried fields,
3027 // however we're only looking at structs up to 16 bytes, so we don't care
3030 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
3031 i != e; ++i, ++idx) {
3032 unsigned FieldOffset = (unsigned)Layout.getFieldOffset(idx);
3034 // If we found a field after the region we care about, then we're done.
3035 if (FieldOffset >= EndBit) break;
3037 unsigned FieldStart = FieldOffset < StartBit ? StartBit-FieldOffset :0;
3038 if (!BitsContainNoUserData(i->getType(), FieldStart, EndBit-FieldOffset,
3043 // If nothing in this record overlapped the area of interest, then we're
3051 /// ContainsFloatAtOffset - Return true if the specified LLVM IR type has a
3052 /// float member at the specified offset. For example, {int,{float}} has a
3053 /// float at offset 4. It is conservatively correct for this routine to return
3055 static bool ContainsFloatAtOffset(llvm::Type *IRType, unsigned IROffset,
3056 const llvm::DataLayout &TD) {
3057 // Base case if we find a float.
3058 if (IROffset == 0 && IRType->isFloatTy())
3061 // If this is a struct, recurse into the field at the specified offset.
3062 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3063 const llvm::StructLayout *SL = TD.getStructLayout(STy);
3064 unsigned Elt = SL->getElementContainingOffset(IROffset);
3065 IROffset -= SL->getElementOffset(Elt);
3066 return ContainsFloatAtOffset(STy->getElementType(Elt), IROffset, TD);
3069 // If this is an array, recurse into the field at the specified offset.
3070 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3071 llvm::Type *EltTy = ATy->getElementType();
3072 unsigned EltSize = TD.getTypeAllocSize(EltTy);
3073 IROffset -= IROffset/EltSize*EltSize;
3074 return ContainsFloatAtOffset(EltTy, IROffset, TD);
3081 /// GetSSETypeAtOffset - Return a type that will be passed by the backend in the
3082 /// low 8 bytes of an XMM register, corresponding to the SSE class.
3083 llvm::Type *X86_64ABIInfo::
3084 GetSSETypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3085 QualType SourceTy, unsigned SourceOffset) const {
3086 // The only three choices we have are either double, <2 x float>, or float. We
3087 // pass as float if the last 4 bytes is just padding. This happens for
3088 // structs that contain 3 floats.
3089 if (BitsContainNoUserData(SourceTy, SourceOffset*8+32,
3090 SourceOffset*8+64, getContext()))
3091 return llvm::Type::getFloatTy(getVMContext());
3093 // We want to pass as <2 x float> if the LLVM IR type contains a float at
3094 // offset+0 and offset+4. Walk the LLVM IR type to find out if this is the
3096 if (ContainsFloatAtOffset(IRType, IROffset, getDataLayout()) &&
3097 ContainsFloatAtOffset(IRType, IROffset+4, getDataLayout()))
3098 return llvm::VectorType::get(llvm::Type::getFloatTy(getVMContext()), 2);
3100 return llvm::Type::getDoubleTy(getVMContext());
3104 /// GetINTEGERTypeAtOffset - The ABI specifies that a value should be passed in
3105 /// an 8-byte GPR. This means that we either have a scalar or we are talking
3106 /// about the high or low part of an up-to-16-byte struct. This routine picks
3107 /// the best LLVM IR type to represent this, which may be i64 or may be anything
3108 /// else that the backend will pass in a GPR that works better (e.g. i8, %foo*,
3111 /// PrefType is an LLVM IR type that corresponds to (part of) the IR type for
3112 /// the source type. IROffset is an offset in bytes into the LLVM IR type that
3113 /// the 8-byte value references. PrefType may be null.
3115 /// SourceTy is the source-level type for the entire argument. SourceOffset is
3116 /// an offset into this that we're processing (which is always either 0 or 8).
3118 llvm::Type *X86_64ABIInfo::
3119 GetINTEGERTypeAtOffset(llvm::Type *IRType, unsigned IROffset,
3120 QualType SourceTy, unsigned SourceOffset) const {
3121 // If we're dealing with an un-offset LLVM IR type, then it means that we're
3122 // returning an 8-byte unit starting with it. See if we can safely use it.
3123 if (IROffset == 0) {
3124 // Pointers and int64's always fill the 8-byte unit.
3125 if ((isa<llvm::PointerType>(IRType) && Has64BitPointers) ||
3126 IRType->isIntegerTy(64))
3129 // If we have a 1/2/4-byte integer, we can use it only if the rest of the
3130 // goodness in the source type is just tail padding. This is allowed to
3131 // kick in for struct {double,int} on the int, but not on
3132 // struct{double,int,int} because we wouldn't return the second int. We
3133 // have to do this analysis on the source type because we can't depend on
3134 // unions being lowered a specific way etc.
3135 if (IRType->isIntegerTy(8) || IRType->isIntegerTy(16) ||
3136 IRType->isIntegerTy(32) ||
3137 (isa<llvm::PointerType>(IRType) && !Has64BitPointers)) {
3138 unsigned BitWidth = isa<llvm::PointerType>(IRType) ? 32 :
3139 cast<llvm::IntegerType>(IRType)->getBitWidth();
3141 if (BitsContainNoUserData(SourceTy, SourceOffset*8+BitWidth,
3142 SourceOffset*8+64, getContext()))
3147 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(IRType)) {
3148 // If this is a struct, recurse into the field at the specified offset.
3149 const llvm::StructLayout *SL = getDataLayout().getStructLayout(STy);
3150 if (IROffset < SL->getSizeInBytes()) {
3151 unsigned FieldIdx = SL->getElementContainingOffset(IROffset);
3152 IROffset -= SL->getElementOffset(FieldIdx);
3154 return GetINTEGERTypeAtOffset(STy->getElementType(FieldIdx), IROffset,
3155 SourceTy, SourceOffset);
3159 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(IRType)) {
3160 llvm::Type *EltTy = ATy->getElementType();
3161 unsigned EltSize = getDataLayout().getTypeAllocSize(EltTy);
3162 unsigned EltOffset = IROffset/EltSize*EltSize;
3163 return GetINTEGERTypeAtOffset(EltTy, IROffset-EltOffset, SourceTy,
3167 // Okay, we don't have any better idea of what to pass, so we pass this in an
3168 // integer register that isn't too big to fit the rest of the struct.
3169 unsigned TySizeInBytes =
3170 (unsigned)getContext().getTypeSizeInChars(SourceTy).getQuantity();
3172 assert(TySizeInBytes != SourceOffset && "Empty field?");
3174 // It is always safe to classify this as an integer type up to i64 that
3175 // isn't larger than the structure.
3176 return llvm::IntegerType::get(getVMContext(),
3177 std::min(TySizeInBytes-SourceOffset, 8U)*8);
3181 /// GetX86_64ByValArgumentPair - Given a high and low type that can ideally
3182 /// be used as elements of a two register pair to pass or return, return a
3183 /// first class aggregate to represent them. For example, if the low part of
3184 /// a by-value argument should be passed as i32* and the high part as float,
3185 /// return {i32*, float}.
3187 GetX86_64ByValArgumentPair(llvm::Type *Lo, llvm::Type *Hi,
3188 const llvm::DataLayout &TD) {
3189 // In order to correctly satisfy the ABI, we need to the high part to start
3190 // at offset 8. If the high and low parts we inferred are both 4-byte types
3191 // (e.g. i32 and i32) then the resultant struct type ({i32,i32}) won't have
3192 // the second element at offset 8. Check for this:
3193 unsigned LoSize = (unsigned)TD.getTypeAllocSize(Lo);
3194 unsigned HiAlign = TD.getABITypeAlignment(Hi);
3195 unsigned HiStart = llvm::alignTo(LoSize, HiAlign);
3196 assert(HiStart != 0 && HiStart <= 8 && "Invalid x86-64 argument pair!");
3198 // To handle this, we have to increase the size of the low part so that the
3199 // second element will start at an 8 byte offset. We can't increase the size
3200 // of the second element because it might make us access off the end of the
3203 // There are usually two sorts of types the ABI generation code can produce
3204 // for the low part of a pair that aren't 8 bytes in size: float or
3205 // i8/i16/i32. This can also include pointers when they are 32-bit (X32 and
3207 // Promote these to a larger type.
3208 if (Lo->isFloatTy())
3209 Lo = llvm::Type::getDoubleTy(Lo->getContext());
3211 assert((Lo->isIntegerTy() || Lo->isPointerTy())
3212 && "Invalid/unknown lo type");
3213 Lo = llvm::Type::getInt64Ty(Lo->getContext());
3217 llvm::StructType *Result = llvm::StructType::get(Lo, Hi);
3219 // Verify that the second element is at an 8-byte offset.
3220 assert(TD.getStructLayout(Result)->getElementOffset(1) == 8 &&
3221 "Invalid x86-64 argument pair!");
3225 ABIArgInfo X86_64ABIInfo::
3226 classifyReturnType(QualType RetTy) const {
3227 // AMD64-ABI 3.2.3p4: Rule 1. Classify the return type with the
3228 // classification algorithm.
3229 X86_64ABIInfo::Class Lo, Hi;
3230 classify(RetTy, 0, Lo, Hi, /*isNamedArg*/ true);
3232 // Check some invariants.
3233 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3234 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3236 llvm::Type *ResType = nullptr;
3240 return ABIArgInfo::getIgnore();
3241 // If the low part is just padding, it takes no register, leave ResType
3243 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3244 "Unknown missing lo part");
3249 llvm_unreachable("Invalid classification for lo word.");
3251 // AMD64-ABI 3.2.3p4: Rule 2. Types of class memory are returned via
3254 return getIndirectReturnResult(RetTy);
3256 // AMD64-ABI 3.2.3p4: Rule 3. If the class is INTEGER, the next
3257 // available register of the sequence %rax, %rdx is used.
3259 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3261 // If we have a sign or zero extended integer, make sure to return Extend
3262 // so that the parameter gets the right LLVM IR attributes.
3263 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3264 // Treat an enum type as its underlying type.
3265 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
3266 RetTy = EnumTy->getDecl()->getIntegerType();
3268 if (RetTy->isIntegralOrEnumerationType() &&
3269 RetTy->isPromotableIntegerType())
3270 return ABIArgInfo::getExtend(RetTy);
3274 // AMD64-ABI 3.2.3p4: Rule 4. If the class is SSE, the next
3275 // available SSE register of the sequence %xmm0, %xmm1 is used.
3277 ResType = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 0, RetTy, 0);
3280 // AMD64-ABI 3.2.3p4: Rule 6. If the class is X87, the value is
3281 // returned on the X87 stack in %st0 as 80-bit x87 number.
3283 ResType = llvm::Type::getX86_FP80Ty(getVMContext());
3286 // AMD64-ABI 3.2.3p4: Rule 8. If the class is COMPLEX_X87, the real
3287 // part of the value is returned in %st0 and the imaginary part in
3290 assert(Hi == ComplexX87 && "Unexpected ComplexX87 classification.");
3291 ResType = llvm::StructType::get(llvm::Type::getX86_FP80Ty(getVMContext()),
3292 llvm::Type::getX86_FP80Ty(getVMContext()));
3296 llvm::Type *HighPart = nullptr;
3298 // Memory was handled previously and X87 should
3299 // never occur as a hi class.
3302 llvm_unreachable("Invalid classification for hi word.");
3304 case ComplexX87: // Previously handled.
3309 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3310 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3311 return ABIArgInfo::getDirect(HighPart, 8);
3314 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3315 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3316 return ABIArgInfo::getDirect(HighPart, 8);
3319 // AMD64-ABI 3.2.3p4: Rule 5. If the class is SSEUP, the eightbyte
3320 // is passed in the next available eightbyte chunk if the last used
3323 // SSEUP should always be preceded by SSE, just widen.
3325 assert(Lo == SSE && "Unexpected SSEUp classification.");
3326 ResType = GetByteVectorType(RetTy);
3329 // AMD64-ABI 3.2.3p4: Rule 7. If the class is X87UP, the value is
3330 // returned together with the previous X87 value in %st0.
3332 // If X87Up is preceded by X87, we don't need to do
3333 // anything. However, in some cases with unions it may not be
3334 // preceded by X87. In such situations we follow gcc and pass the
3335 // extra bits in an SSE reg.
3337 HighPart = GetSSETypeAtOffset(CGT.ConvertType(RetTy), 8, RetTy, 8);
3338 if (Lo == NoClass) // Return HighPart at offset 8 in memory.
3339 return ABIArgInfo::getDirect(HighPart, 8);
3344 // If a high part was specified, merge it together with the low part. It is
3345 // known to pass in the high eightbyte of the result. We do this by forming a
3346 // first class struct aggregate with the high and low part: {low, high}
3348 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3350 return ABIArgInfo::getDirect(ResType);
3353 ABIArgInfo X86_64ABIInfo::classifyArgumentType(
3354 QualType Ty, unsigned freeIntRegs, unsigned &neededInt, unsigned &neededSSE,
3358 Ty = useFirstFieldIfTransparentUnion(Ty);
3360 X86_64ABIInfo::Class Lo, Hi;
3361 classify(Ty, 0, Lo, Hi, isNamedArg);
3363 // Check some invariants.
3364 // FIXME: Enforce these by construction.
3365 assert((Hi != Memory || Lo == Memory) && "Invalid memory classification.");
3366 assert((Hi != SSEUp || Lo == SSE) && "Invalid SSEUp classification.");
3370 llvm::Type *ResType = nullptr;
3374 return ABIArgInfo::getIgnore();
3375 // If the low part is just padding, it takes no register, leave ResType
3377 assert((Hi == SSE || Hi == Integer || Hi == X87Up) &&
3378 "Unknown missing lo part");
3381 // AMD64-ABI 3.2.3p3: Rule 1. If the class is MEMORY, pass the argument
3385 // AMD64-ABI 3.2.3p3: Rule 5. If the class is X87, X87UP or
3386 // COMPLEX_X87, it is passed in memory.
3389 if (getRecordArgABI(Ty, getCXXABI()) == CGCXXABI::RAA_Indirect)
3391 return getIndirectResult(Ty, freeIntRegs);
3395 llvm_unreachable("Invalid classification for lo word.");
3397 // AMD64-ABI 3.2.3p3: Rule 2. If the class is INTEGER, the next
3398 // available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8
3403 // Pick an 8-byte type based on the preferred type.
3404 ResType = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 0, Ty, 0);
3406 // If we have a sign or zero extended integer, make sure to return Extend
3407 // so that the parameter gets the right LLVM IR attributes.
3408 if (Hi == NoClass && isa<llvm::IntegerType>(ResType)) {
3409 // Treat an enum type as its underlying type.
3410 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3411 Ty = EnumTy->getDecl()->getIntegerType();
3413 if (Ty->isIntegralOrEnumerationType() &&
3414 Ty->isPromotableIntegerType())
3415 return ABIArgInfo::getExtend(Ty);
3420 // AMD64-ABI 3.2.3p3: Rule 3. If the class is SSE, the next
3421 // available SSE register is used, the registers are taken in the
3422 // order from %xmm0 to %xmm7.
3424 llvm::Type *IRType = CGT.ConvertType(Ty);
3425 ResType = GetSSETypeAtOffset(IRType, 0, Ty, 0);
3431 llvm::Type *HighPart = nullptr;
3433 // Memory was handled previously, ComplexX87 and X87 should
3434 // never occur as hi classes, and X87Up must be preceded by X87,
3435 // which is passed in memory.
3439 llvm_unreachable("Invalid classification for hi word.");
3441 case NoClass: break;
3445 // Pick an 8-byte type based on the preferred type.
3446 HighPart = GetINTEGERTypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3448 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3449 return ABIArgInfo::getDirect(HighPart, 8);
3452 // X87Up generally doesn't occur here (long double is passed in
3453 // memory), except in situations involving unions.
3456 HighPart = GetSSETypeAtOffset(CGT.ConvertType(Ty), 8, Ty, 8);
3458 if (Lo == NoClass) // Pass HighPart at offset 8 in memory.
3459 return ABIArgInfo::getDirect(HighPart, 8);
3464 // AMD64-ABI 3.2.3p3: Rule 4. If the class is SSEUP, the
3465 // eightbyte is passed in the upper half of the last used SSE
3466 // register. This only happens when 128-bit vectors are passed.
3468 assert(Lo == SSE && "Unexpected SSEUp classification");
3469 ResType = GetByteVectorType(Ty);
3473 // If a high part was specified, merge it together with the low part. It is
3474 // known to pass in the high eightbyte of the result. We do this by forming a
3475 // first class struct aggregate with the high and low part: {low, high}
3477 ResType = GetX86_64ByValArgumentPair(ResType, HighPart, getDataLayout());
3479 return ABIArgInfo::getDirect(ResType);
3483 X86_64ABIInfo::classifyRegCallStructTypeImpl(QualType Ty, unsigned &NeededInt,
3484 unsigned &NeededSSE) const {
3485 auto RT = Ty->getAs<RecordType>();
3486 assert(RT && "classifyRegCallStructType only valid with struct types");
3488 if (RT->getDecl()->hasFlexibleArrayMember())
3489 return getIndirectReturnResult(Ty);
3492 if (auto CXXRD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3493 if (CXXRD->isDynamicClass()) {
3494 NeededInt = NeededSSE = 0;
3495 return getIndirectReturnResult(Ty);
3498 for (const auto &I : CXXRD->bases())
3499 if (classifyRegCallStructTypeImpl(I.getType(), NeededInt, NeededSSE)
3501 NeededInt = NeededSSE = 0;
3502 return getIndirectReturnResult(Ty);
3507 for (const auto *FD : RT->getDecl()->fields()) {
3508 if (FD->getType()->isRecordType() && !FD->getType()->isUnionType()) {
3509 if (classifyRegCallStructTypeImpl(FD->getType(), NeededInt, NeededSSE)
3511 NeededInt = NeededSSE = 0;
3512 return getIndirectReturnResult(Ty);
3515 unsigned LocalNeededInt, LocalNeededSSE;
3516 if (classifyArgumentType(FD->getType(), UINT_MAX, LocalNeededInt,
3517 LocalNeededSSE, true)
3519 NeededInt = NeededSSE = 0;
3520 return getIndirectReturnResult(Ty);
3522 NeededInt += LocalNeededInt;
3523 NeededSSE += LocalNeededSSE;
3527 return ABIArgInfo::getDirect();
3530 ABIArgInfo X86_64ABIInfo::classifyRegCallStructType(QualType Ty,
3531 unsigned &NeededInt,
3532 unsigned &NeededSSE) const {
3537 return classifyRegCallStructTypeImpl(Ty, NeededInt, NeededSSE);
3540 void X86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3542 const unsigned CallingConv = FI.getCallingConvention();
3543 // It is possible to force Win64 calling convention on any x86_64 target by
3544 // using __attribute__((ms_abi)). In such case to correctly emit Win64
3545 // compatible code delegate this call to WinX86_64ABIInfo::computeInfo.
3546 if (CallingConv == llvm::CallingConv::Win64) {
3547 WinX86_64ABIInfo Win64ABIInfo(CGT);
3548 Win64ABIInfo.computeInfo(FI);
3552 bool IsRegCall = CallingConv == llvm::CallingConv::X86_RegCall;
3554 // Keep track of the number of assigned registers.
3555 unsigned FreeIntRegs = IsRegCall ? 11 : 6;
3556 unsigned FreeSSERegs = IsRegCall ? 16 : 8;
3557 unsigned NeededInt, NeededSSE;
3559 if (!::classifyReturnType(getCXXABI(), FI, *this)) {
3560 if (IsRegCall && FI.getReturnType()->getTypePtr()->isRecordType() &&
3561 !FI.getReturnType()->getTypePtr()->isUnionType()) {
3562 FI.getReturnInfo() =
3563 classifyRegCallStructType(FI.getReturnType(), NeededInt, NeededSSE);
3564 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3565 FreeIntRegs -= NeededInt;
3566 FreeSSERegs -= NeededSSE;
3568 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3570 } else if (IsRegCall && FI.getReturnType()->getAs<ComplexType>()) {
3571 // Complex Long Double Type is passed in Memory when Regcall
3572 // calling convention is used.
3573 const ComplexType *CT = FI.getReturnType()->getAs<ComplexType>();
3574 if (getContext().getCanonicalType(CT->getElementType()) ==
3575 getContext().LongDoubleTy)
3576 FI.getReturnInfo() = getIndirectReturnResult(FI.getReturnType());
3578 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
3581 // If the return value is indirect, then the hidden argument is consuming one
3582 // integer register.
3583 if (FI.getReturnInfo().isIndirect())
3586 // The chain argument effectively gives us another free register.
3587 if (FI.isChainCall())
3590 unsigned NumRequiredArgs = FI.getNumRequiredArgs();
3591 // AMD64-ABI 3.2.3p3: Once arguments are classified, the registers
3592 // get assigned (in left-to-right order) for passing as follows...
3594 for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
3595 it != ie; ++it, ++ArgNo) {
3596 bool IsNamedArg = ArgNo < NumRequiredArgs;
3598 if (IsRegCall && it->type->isStructureOrClassType())
3599 it->info = classifyRegCallStructType(it->type, NeededInt, NeededSSE);
3601 it->info = classifyArgumentType(it->type, FreeIntRegs, NeededInt,
3602 NeededSSE, IsNamedArg);
3604 // AMD64-ABI 3.2.3p3: If there are no registers available for any
3605 // eightbyte of an argument, the whole argument is passed on the
3606 // stack. If registers have already been assigned for some
3607 // eightbytes of such an argument, the assignments get reverted.
3608 if (FreeIntRegs >= NeededInt && FreeSSERegs >= NeededSSE) {
3609 FreeIntRegs -= NeededInt;
3610 FreeSSERegs -= NeededSSE;
3612 it->info = getIndirectResult(it->type, FreeIntRegs);
3617 static Address EmitX86_64VAArgFromMemory(CodeGenFunction &CGF,
3618 Address VAListAddr, QualType Ty) {
3619 Address overflow_arg_area_p = CGF.Builder.CreateStructGEP(
3620 VAListAddr, 2, CharUnits::fromQuantity(8), "overflow_arg_area_p");
3621 llvm::Value *overflow_arg_area =
3622 CGF.Builder.CreateLoad(overflow_arg_area_p, "overflow_arg_area");
3624 // AMD64-ABI 3.5.7p5: Step 7. Align l->overflow_arg_area upwards to a 16
3625 // byte boundary if alignment needed by type exceeds 8 byte boundary.
3626 // It isn't stated explicitly in the standard, but in practice we use
3627 // alignment greater than 16 where necessary.
3628 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
3629 if (Align > CharUnits::fromQuantity(8)) {
3630 overflow_arg_area = emitRoundPointerUpToAlignment(CGF, overflow_arg_area,
3634 // AMD64-ABI 3.5.7p5: Step 8. Fetch type from l->overflow_arg_area.
3635 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3637 CGF.Builder.CreateBitCast(overflow_arg_area,
3638 llvm::PointerType::getUnqual(LTy));
3640 // AMD64-ABI 3.5.7p5: Step 9. Set l->overflow_arg_area to:
3641 // l->overflow_arg_area + sizeof(type).
3642 // AMD64-ABI 3.5.7p5: Step 10. Align l->overflow_arg_area upwards to
3643 // an 8 byte boundary.
3645 uint64_t SizeInBytes = (CGF.getContext().getTypeSize(Ty) + 7) / 8;
3646 llvm::Value *Offset =
3647 llvm::ConstantInt::get(CGF.Int32Ty, (SizeInBytes + 7) & ~7);
3648 overflow_arg_area = CGF.Builder.CreateGEP(overflow_arg_area, Offset,
3649 "overflow_arg_area.next");
3650 CGF.Builder.CreateStore(overflow_arg_area, overflow_arg_area_p);
3652 // AMD64-ABI 3.5.7p5: Step 11. Return the fetched type.
3653 return Address(Res, Align);
3656 Address X86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
3657 QualType Ty) const {
3658 // Assume that va_list type is correct; should be pointer to LLVM type:
3662 // i8* overflow_arg_area;
3663 // i8* reg_save_area;
3665 unsigned neededInt, neededSSE;
3667 Ty = getContext().getCanonicalType(Ty);
3668 ABIArgInfo AI = classifyArgumentType(Ty, 0, neededInt, neededSSE,
3669 /*isNamedArg*/false);
3671 // AMD64-ABI 3.5.7p5: Step 1. Determine whether type may be passed
3672 // in the registers. If not go to step 7.
3673 if (!neededInt && !neededSSE)
3674 return EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3676 // AMD64-ABI 3.5.7p5: Step 2. Compute num_gp to hold the number of
3677 // general purpose registers needed to pass type and num_fp to hold
3678 // the number of floating point registers needed.
3680 // AMD64-ABI 3.5.7p5: Step 3. Verify whether arguments fit into
3681 // registers. In the case: l->gp_offset > 48 - num_gp * 8 or
3682 // l->fp_offset > 304 - num_fp * 16 go to step 7.
3684 // NOTE: 304 is a typo, there are (6 * 8 + 8 * 16) = 176 bytes of
3685 // register save space).
3687 llvm::Value *InRegs = nullptr;
3688 Address gp_offset_p = Address::invalid(), fp_offset_p = Address::invalid();
3689 llvm::Value *gp_offset = nullptr, *fp_offset = nullptr;
3692 CGF.Builder.CreateStructGEP(VAListAddr, 0, CharUnits::Zero(),
3694 gp_offset = CGF.Builder.CreateLoad(gp_offset_p, "gp_offset");
3695 InRegs = llvm::ConstantInt::get(CGF.Int32Ty, 48 - neededInt * 8);
3696 InRegs = CGF.Builder.CreateICmpULE(gp_offset, InRegs, "fits_in_gp");
3701 CGF.Builder.CreateStructGEP(VAListAddr, 1, CharUnits::fromQuantity(4),
3703 fp_offset = CGF.Builder.CreateLoad(fp_offset_p, "fp_offset");
3704 llvm::Value *FitsInFP =
3705 llvm::ConstantInt::get(CGF.Int32Ty, 176 - neededSSE * 16);
3706 FitsInFP = CGF.Builder.CreateICmpULE(fp_offset, FitsInFP, "fits_in_fp");
3707 InRegs = InRegs ? CGF.Builder.CreateAnd(InRegs, FitsInFP) : FitsInFP;
3710 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
3711 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
3712 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
3713 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
3715 // Emit code to load the value if it was passed in registers.
3717 CGF.EmitBlock(InRegBlock);
3719 // AMD64-ABI 3.5.7p5: Step 4. Fetch type from l->reg_save_area with
3720 // an offset of l->gp_offset and/or l->fp_offset. This may require
3721 // copying to a temporary location in case the parameter is passed
3722 // in different register classes or requires an alignment greater
3723 // than 8 for general purpose registers and 16 for XMM registers.
3725 // FIXME: This really results in shameful code when we end up needing to
3726 // collect arguments from different places; often what should result in a
3727 // simple assembling of a structure from scattered addresses has many more
3728 // loads than necessary. Can we clean this up?
3729 llvm::Type *LTy = CGF.ConvertTypeForMem(Ty);
3730 llvm::Value *RegSaveArea = CGF.Builder.CreateLoad(
3731 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(16)),
3734 Address RegAddr = Address::invalid();
3735 if (neededInt && neededSSE) {
3737 assert(AI.isDirect() && "Unexpected ABI info for mixed regs");
3738 llvm::StructType *ST = cast<llvm::StructType>(AI.getCoerceToType());
3739 Address Tmp = CGF.CreateMemTemp(Ty);
3740 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3741 assert(ST->getNumElements() == 2 && "Unexpected ABI info for mixed regs");
3742 llvm::Type *TyLo = ST->getElementType(0);
3743 llvm::Type *TyHi = ST->getElementType(1);
3744 assert((TyLo->isFPOrFPVectorTy() ^ TyHi->isFPOrFPVectorTy()) &&
3745 "Unexpected ABI info for mixed regs");
3746 llvm::Type *PTyLo = llvm::PointerType::getUnqual(TyLo);
3747 llvm::Type *PTyHi = llvm::PointerType::getUnqual(TyHi);
3748 llvm::Value *GPAddr = CGF.Builder.CreateGEP(RegSaveArea, gp_offset);
3749 llvm::Value *FPAddr = CGF.Builder.CreateGEP(RegSaveArea, fp_offset);
3750 llvm::Value *RegLoAddr = TyLo->isFPOrFPVectorTy() ? FPAddr : GPAddr;
3751 llvm::Value *RegHiAddr = TyLo->isFPOrFPVectorTy() ? GPAddr : FPAddr;
3753 // Copy the first element.
3754 // FIXME: Our choice of alignment here and below is probably pessimistic.
3755 llvm::Value *V = CGF.Builder.CreateAlignedLoad(
3756 TyLo, CGF.Builder.CreateBitCast(RegLoAddr, PTyLo),
3757 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyLo)));
3758 CGF.Builder.CreateStore(V,
3759 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3761 // Copy the second element.
3762 V = CGF.Builder.CreateAlignedLoad(
3763 TyHi, CGF.Builder.CreateBitCast(RegHiAddr, PTyHi),
3764 CharUnits::fromQuantity(getDataLayout().getABITypeAlignment(TyHi)));
3765 CharUnits Offset = CharUnits::fromQuantity(
3766 getDataLayout().getStructLayout(ST)->getElementOffset(1));
3767 CGF.Builder.CreateStore(V, CGF.Builder.CreateStructGEP(Tmp, 1, Offset));
3769 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3770 } else if (neededInt) {
3771 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, gp_offset),
3772 CharUnits::fromQuantity(8));
3773 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3775 // Copy to a temporary if necessary to ensure the appropriate alignment.
3776 std::pair<CharUnits, CharUnits> SizeAlign =
3777 getContext().getTypeInfoInChars(Ty);
3778 uint64_t TySize = SizeAlign.first.getQuantity();
3779 CharUnits TyAlign = SizeAlign.second;
3781 // Copy into a temporary if the type is more aligned than the
3782 // register save area.
3783 if (TyAlign.getQuantity() > 8) {
3784 Address Tmp = CGF.CreateMemTemp(Ty);
3785 CGF.Builder.CreateMemCpy(Tmp, RegAddr, TySize, false);
3789 } else if (neededSSE == 1) {
3790 RegAddr = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3791 CharUnits::fromQuantity(16));
3792 RegAddr = CGF.Builder.CreateElementBitCast(RegAddr, LTy);
3794 assert(neededSSE == 2 && "Invalid number of needed registers!");
3795 // SSE registers are spaced 16 bytes apart in the register save
3796 // area, we need to collect the two eightbytes together.
3797 // The ABI isn't explicit about this, but it seems reasonable
3798 // to assume that the slots are 16-byte aligned, since the stack is
3799 // naturally 16-byte aligned and the prologue is expected to store
3800 // all the SSE registers to the RSA.
3801 Address RegAddrLo = Address(CGF.Builder.CreateGEP(RegSaveArea, fp_offset),
3802 CharUnits::fromQuantity(16));
3804 CGF.Builder.CreateConstInBoundsByteGEP(RegAddrLo,
3805 CharUnits::fromQuantity(16));
3806 llvm::Type *ST = AI.canHaveCoerceToType()
3807 ? AI.getCoerceToType()
3808 : llvm::StructType::get(CGF.DoubleTy, CGF.DoubleTy);
3810 Address Tmp = CGF.CreateMemTemp(Ty);
3811 Tmp = CGF.Builder.CreateElementBitCast(Tmp, ST);
3812 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3813 RegAddrLo, ST->getStructElementType(0)));
3814 CGF.Builder.CreateStore(V,
3815 CGF.Builder.CreateStructGEP(Tmp, 0, CharUnits::Zero()));
3816 V = CGF.Builder.CreateLoad(CGF.Builder.CreateElementBitCast(
3817 RegAddrHi, ST->getStructElementType(1)));
3818 CGF.Builder.CreateStore(V,
3819 CGF.Builder.CreateStructGEP(Tmp, 1, CharUnits::fromQuantity(8)));
3821 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, LTy);
3824 // AMD64-ABI 3.5.7p5: Step 5. Set:
3825 // l->gp_offset = l->gp_offset + num_gp * 8
3826 // l->fp_offset = l->fp_offset + num_fp * 16.
3828 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededInt * 8);
3829 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(gp_offset, Offset),
3833 llvm::Value *Offset = llvm::ConstantInt::get(CGF.Int32Ty, neededSSE * 16);
3834 CGF.Builder.CreateStore(CGF.Builder.CreateAdd(fp_offset, Offset),
3837 CGF.EmitBranch(ContBlock);
3839 // Emit code to load the value if it was passed in memory.
3841 CGF.EmitBlock(InMemBlock);
3842 Address MemAddr = EmitX86_64VAArgFromMemory(CGF, VAListAddr, Ty);
3844 // Return the appropriate result.
3846 CGF.EmitBlock(ContBlock);
3847 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock, MemAddr, InMemBlock,
3852 Address X86_64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
3853 QualType Ty) const {
3854 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
3855 CGF.getContext().getTypeInfoInChars(Ty),
3856 CharUnits::fromQuantity(8),
3857 /*allowHigherAlign*/ false);
3861 WinX86_64ABIInfo::reclassifyHvaArgType(QualType Ty, unsigned &FreeSSERegs,
3862 const ABIArgInfo ¤t) const {
3863 // Assumes vectorCall calling convention.
3864 const Type *Base = nullptr;
3865 uint64_t NumElts = 0;
3867 if (!Ty->isBuiltinType() && !Ty->isVectorType() &&
3868 isHomogeneousAggregate(Ty, Base, NumElts) && FreeSSERegs >= NumElts) {
3869 FreeSSERegs -= NumElts;
3870 return getDirectX86Hva();
3875 ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, unsigned &FreeSSERegs,
3876 bool IsReturnType, bool IsVectorCall,
3877 bool IsRegCall) const {
3879 if (Ty->isVoidType())
3880 return ABIArgInfo::getIgnore();
3882 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
3883 Ty = EnumTy->getDecl()->getIntegerType();
3885 TypeInfo Info = getContext().getTypeInfo(Ty);
3886 uint64_t Width = Info.Width;
3887 CharUnits Align = getContext().toCharUnitsFromBits(Info.Align);
3889 const RecordType *RT = Ty->getAs<RecordType>();
3891 if (!IsReturnType) {
3892 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI()))
3893 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
3896 if (RT->getDecl()->hasFlexibleArrayMember())
3897 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3901 const Type *Base = nullptr;
3902 uint64_t NumElts = 0;
3903 // vectorcall adds the concept of a homogenous vector aggregate, similar to
3905 if ((IsVectorCall || IsRegCall) &&
3906 isHomogeneousAggregate(Ty, Base, NumElts)) {
3908 if (FreeSSERegs >= NumElts) {
3909 FreeSSERegs -= NumElts;
3910 if (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())
3911 return ABIArgInfo::getDirect();
3912 return ABIArgInfo::getExpand();
3914 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3915 } else if (IsVectorCall) {
3916 if (FreeSSERegs >= NumElts &&
3917 (IsReturnType || Ty->isBuiltinType() || Ty->isVectorType())) {
3918 FreeSSERegs -= NumElts;
3919 return ABIArgInfo::getDirect();
3920 } else if (IsReturnType) {
3921 return ABIArgInfo::getExpand();
3922 } else if (!Ty->isBuiltinType() && !Ty->isVectorType()) {
3923 // HVAs are delayed and reclassified in the 2nd step.
3924 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3929 if (Ty->isMemberPointerType()) {
3930 // If the member pointer is represented by an LLVM int or ptr, pass it
3932 llvm::Type *LLTy = CGT.ConvertType(Ty);
3933 if (LLTy->isPointerTy() || LLTy->isIntegerTy())
3934 return ABIArgInfo::getDirect();
3937 if (RT || Ty->isAnyComplexType() || Ty->isMemberPointerType()) {
3938 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
3939 // not 1, 2, 4, or 8 bytes, must be passed by reference."
3940 if (Width > 64 || !llvm::isPowerOf2_64(Width))
3941 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
3943 // Otherwise, coerce it to a small integer.
3944 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Width));
3947 // Bool type is always extended to the ABI, other builtin types are not
3949 const BuiltinType *BT = Ty->getAs<BuiltinType>();
3950 if (BT && BT->getKind() == BuiltinType::Bool)
3951 return ABIArgInfo::getExtend(Ty);
3953 // Mingw64 GCC uses the old 80 bit extended precision floating point unit. It
3954 // passes them indirectly through memory.
3955 if (IsMingw64 && BT && BT->getKind() == BuiltinType::LongDouble) {
3956 const llvm::fltSemantics *LDF = &getTarget().getLongDoubleFormat();
3957 if (LDF == &llvm::APFloat::x87DoubleExtended())
3958 return ABIArgInfo::getIndirect(Align, /*ByVal=*/false);
3961 return ABIArgInfo::getDirect();
3964 void WinX86_64ABIInfo::computeVectorCallArgs(CGFunctionInfo &FI,
3965 unsigned FreeSSERegs,
3967 bool IsRegCall) const {
3969 for (auto &I : FI.arguments()) {
3970 // Vectorcall in x64 only permits the first 6 arguments to be passed
3971 // as XMM/YMM registers.
3972 if (Count < VectorcallMaxParamNumAsReg)
3973 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
3975 // Since these cannot be passed in registers, pretend no registers
3977 unsigned ZeroSSERegsAvail = 0;
3978 I.info = classify(I.type, /*FreeSSERegs=*/ZeroSSERegsAvail, false,
3979 IsVectorCall, IsRegCall);
3984 for (auto &I : FI.arguments()) {
3985 I.info = reclassifyHvaArgType(I.type, FreeSSERegs, I.info);
3989 void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
3991 FI.getCallingConvention() == llvm::CallingConv::X86_VectorCall;
3992 bool IsRegCall = FI.getCallingConvention() == llvm::CallingConv::X86_RegCall;
3994 unsigned FreeSSERegs = 0;
3996 // We can use up to 4 SSE return registers with vectorcall.
3998 } else if (IsRegCall) {
3999 // RegCall gives us 16 SSE registers.
4003 if (!getCXXABI().classifyReturnType(FI))
4004 FI.getReturnInfo() = classify(FI.getReturnType(), FreeSSERegs, true,
4005 IsVectorCall, IsRegCall);
4008 // We can use up to 6 SSE register parameters with vectorcall.
4010 } else if (IsRegCall) {
4011 // RegCall gives us 16 SSE registers, we can reuse the return registers.
4016 computeVectorCallArgs(FI, FreeSSERegs, IsVectorCall, IsRegCall);
4018 for (auto &I : FI.arguments())
4019 I.info = classify(I.type, FreeSSERegs, false, IsVectorCall, IsRegCall);
4024 Address WinX86_64ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4025 QualType Ty) const {
4027 bool IsIndirect = false;
4029 // MS x64 ABI requirement: "Any argument that doesn't fit in 8 bytes, or is
4030 // not 1, 2, 4, or 8 bytes, must be passed by reference."
4031 if (isAggregateTypeForABI(Ty) || Ty->isMemberPointerType()) {
4032 uint64_t Width = getContext().getTypeSize(Ty);
4033 IsIndirect = Width > 64 || !llvm::isPowerOf2_64(Width);
4036 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
4037 CGF.getContext().getTypeInfoInChars(Ty),
4038 CharUnits::fromQuantity(8),
4039 /*allowHigherAlign*/ false);
4044 /// PPC32_SVR4_ABIInfo - The 32-bit PowerPC ELF (SVR4) ABI information.
4045 class PPC32_SVR4_ABIInfo : public DefaultABIInfo {
4046 bool IsSoftFloatABI;
4048 CharUnits getParamTypeAlignment(QualType Ty) const;
4051 PPC32_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, bool SoftFloatABI)
4052 : DefaultABIInfo(CGT), IsSoftFloatABI(SoftFloatABI) {}
4054 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4055 QualType Ty) const override;
4058 class PPC32TargetCodeGenInfo : public TargetCodeGenInfo {
4060 PPC32TargetCodeGenInfo(CodeGenTypes &CGT, bool SoftFloatABI)
4061 : TargetCodeGenInfo(new PPC32_SVR4_ABIInfo(CGT, SoftFloatABI)) {}
4063 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4064 // This is recovered from gcc output.
4065 return 1; // r1 is the dedicated stack pointer
4068 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4069 llvm::Value *Address) const override;
4073 CharUnits PPC32_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4074 // Complex types are passed just like their elements
4075 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4076 Ty = CTy->getElementType();
4078 if (Ty->isVectorType())
4079 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16
4082 // For single-element float/vector structs, we consider the whole type
4083 // to have the same alignment requirements as its single element.
4084 const Type *AlignTy = nullptr;
4085 if (const Type *EltType = isSingleElementStruct(Ty, getContext())) {
4086 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4087 if ((EltType->isVectorType() && getContext().getTypeSize(EltType) == 128) ||
4088 (BT && BT->isFloatingPoint()))
4093 return CharUnits::fromQuantity(AlignTy->isVectorType() ? 16 : 4);
4094 return CharUnits::fromQuantity(4);
4097 // TODO: this implementation is now likely redundant with
4098 // DefaultABIInfo::EmitVAArg.
4099 Address PPC32_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAList,
4100 QualType Ty) const {
4101 if (getTarget().getTriple().isOSDarwin()) {
4102 auto TI = getContext().getTypeInfoInChars(Ty);
4103 TI.second = getParamTypeAlignment(Ty);
4105 CharUnits SlotSize = CharUnits::fromQuantity(4);
4106 return emitVoidPtrVAArg(CGF, VAList, Ty,
4107 classifyArgumentType(Ty).isIndirect(), TI, SlotSize,
4108 /*AllowHigherAlign=*/true);
4111 const unsigned OverflowLimit = 8;
4112 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4113 // TODO: Implement this. For now ignore.
4115 return Address::invalid(); // FIXME?
4118 // struct __va_list_tag {
4119 // unsigned char gpr;
4120 // unsigned char fpr;
4121 // unsigned short reserved;
4122 // void *overflow_arg_area;
4123 // void *reg_save_area;
4126 bool isI64 = Ty->isIntegerType() && getContext().getTypeSize(Ty) == 64;
4128 Ty->isIntegerType() || Ty->isPointerType() || Ty->isAggregateType();
4129 bool isF64 = Ty->isFloatingType() && getContext().getTypeSize(Ty) == 64;
4131 // All aggregates are passed indirectly? That doesn't seem consistent
4132 // with the argument-lowering code.
4133 bool isIndirect = Ty->isAggregateType();
4135 CGBuilderTy &Builder = CGF.Builder;
4137 // The calling convention either uses 1-2 GPRs or 1 FPR.
4138 Address NumRegsAddr = Address::invalid();
4139 if (isInt || IsSoftFloatABI) {
4140 NumRegsAddr = Builder.CreateStructGEP(VAList, 0, CharUnits::Zero(), "gpr");
4142 NumRegsAddr = Builder.CreateStructGEP(VAList, 1, CharUnits::One(), "fpr");
4145 llvm::Value *NumRegs = Builder.CreateLoad(NumRegsAddr, "numUsedRegs");
4147 // "Align" the register count when TY is i64.
4148 if (isI64 || (isF64 && IsSoftFloatABI)) {
4149 NumRegs = Builder.CreateAdd(NumRegs, Builder.getInt8(1));
4150 NumRegs = Builder.CreateAnd(NumRegs, Builder.getInt8((uint8_t) ~1U));
4154 Builder.CreateICmpULT(NumRegs, Builder.getInt8(OverflowLimit), "cond");
4156 llvm::BasicBlock *UsingRegs = CGF.createBasicBlock("using_regs");
4157 llvm::BasicBlock *UsingOverflow = CGF.createBasicBlock("using_overflow");
4158 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
4160 Builder.CreateCondBr(CC, UsingRegs, UsingOverflow);
4162 llvm::Type *DirectTy = CGF.ConvertType(Ty);
4163 if (isIndirect) DirectTy = DirectTy->getPointerTo(0);
4165 // Case 1: consume registers.
4166 Address RegAddr = Address::invalid();
4168 CGF.EmitBlock(UsingRegs);
4170 Address RegSaveAreaPtr =
4171 Builder.CreateStructGEP(VAList, 4, CharUnits::fromQuantity(8));
4172 RegAddr = Address(Builder.CreateLoad(RegSaveAreaPtr),
4173 CharUnits::fromQuantity(8));
4174 assert(RegAddr.getElementType() == CGF.Int8Ty);
4176 // Floating-point registers start after the general-purpose registers.
4177 if (!(isInt || IsSoftFloatABI)) {
4178 RegAddr = Builder.CreateConstInBoundsByteGEP(RegAddr,
4179 CharUnits::fromQuantity(32));
4182 // Get the address of the saved value by scaling the number of
4183 // registers we've used by the number of
4184 CharUnits RegSize = CharUnits::fromQuantity((isInt || IsSoftFloatABI) ? 4 : 8);
4185 llvm::Value *RegOffset =
4186 Builder.CreateMul(NumRegs, Builder.getInt8(RegSize.getQuantity()));
4187 RegAddr = Address(Builder.CreateInBoundsGEP(CGF.Int8Ty,
4188 RegAddr.getPointer(), RegOffset),
4189 RegAddr.getAlignment().alignmentOfArrayElement(RegSize));
4190 RegAddr = Builder.CreateElementBitCast(RegAddr, DirectTy);
4192 // Increase the used-register count.
4194 Builder.CreateAdd(NumRegs,
4195 Builder.getInt8((isI64 || (isF64 && IsSoftFloatABI)) ? 2 : 1));
4196 Builder.CreateStore(NumRegs, NumRegsAddr);
4198 CGF.EmitBranch(Cont);
4201 // Case 2: consume space in the overflow area.
4202 Address MemAddr = Address::invalid();
4204 CGF.EmitBlock(UsingOverflow);
4206 Builder.CreateStore(Builder.getInt8(OverflowLimit), NumRegsAddr);
4208 // Everything in the overflow area is rounded up to a size of at least 4.
4209 CharUnits OverflowAreaAlign = CharUnits::fromQuantity(4);
4213 auto TypeInfo = CGF.getContext().getTypeInfoInChars(Ty);
4214 Size = TypeInfo.first.alignTo(OverflowAreaAlign);
4216 Size = CGF.getPointerSize();
4219 Address OverflowAreaAddr =
4220 Builder.CreateStructGEP(VAList, 3, CharUnits::fromQuantity(4));
4221 Address OverflowArea(Builder.CreateLoad(OverflowAreaAddr, "argp.cur"),
4223 // Round up address of argument to alignment
4224 CharUnits Align = CGF.getContext().getTypeAlignInChars(Ty);
4225 if (Align > OverflowAreaAlign) {
4226 llvm::Value *Ptr = OverflowArea.getPointer();
4227 OverflowArea = Address(emitRoundPointerUpToAlignment(CGF, Ptr, Align),
4231 MemAddr = Builder.CreateElementBitCast(OverflowArea, DirectTy);
4233 // Increase the overflow area.
4234 OverflowArea = Builder.CreateConstInBoundsByteGEP(OverflowArea, Size);
4235 Builder.CreateStore(OverflowArea.getPointer(), OverflowAreaAddr);
4236 CGF.EmitBranch(Cont);
4239 CGF.EmitBlock(Cont);
4241 // Merge the cases with a phi.
4242 Address Result = emitMergePHI(CGF, RegAddr, UsingRegs, MemAddr, UsingOverflow,
4245 // Load the pointer if the argument was passed indirectly.
4247 Result = Address(Builder.CreateLoad(Result, "aggr"),
4248 getContext().getTypeAlignInChars(Ty));
4255 PPC32TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4256 llvm::Value *Address) const {
4257 // This is calculated from the LLVM and GCC tables and verified
4258 // against gcc output. AFAIK all ABIs use the same encoding.
4260 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4262 llvm::IntegerType *i8 = CGF.Int8Ty;
4263 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4264 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4265 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4267 // 0-31: r0-31, the 4-byte general-purpose registers
4268 AssignToArrayRange(Builder, Address, Four8, 0, 31);
4270 // 32-63: fp0-31, the 8-byte floating-point registers
4271 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4273 // 64-76 are various 4-byte special-purpose registers:
4280 AssignToArrayRange(Builder, Address, Four8, 64, 76);
4282 // 77-108: v0-31, the 16-byte vector registers
4283 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4290 AssignToArrayRange(Builder, Address, Four8, 109, 113);
4298 /// PPC64_SVR4_ABIInfo - The 64-bit PowerPC ELF (SVR4) ABI information.
4299 class PPC64_SVR4_ABIInfo : public SwiftABIInfo {
4307 static const unsigned GPRBits = 64;
4310 bool IsSoftFloatABI;
4312 // A vector of float or double will be promoted to <4 x f32> or <4 x f64> and
4313 // will be passed in a QPX register.
4314 bool IsQPXVectorTy(const Type *Ty) const {
4318 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4319 unsigned NumElements = VT->getNumElements();
4320 if (NumElements == 1)
4323 if (VT->getElementType()->isSpecificBuiltinType(BuiltinType::Double)) {
4324 if (getContext().getTypeSize(Ty) <= 256)
4326 } else if (VT->getElementType()->
4327 isSpecificBuiltinType(BuiltinType::Float)) {
4328 if (getContext().getTypeSize(Ty) <= 128)
4336 bool IsQPXVectorTy(QualType Ty) const {
4337 return IsQPXVectorTy(Ty.getTypePtr());
4341 PPC64_SVR4_ABIInfo(CodeGen::CodeGenTypes &CGT, ABIKind Kind, bool HasQPX,
4343 : SwiftABIInfo(CGT), Kind(Kind), HasQPX(HasQPX),
4344 IsSoftFloatABI(SoftFloatABI) {}
4346 bool isPromotableTypeForABI(QualType Ty) const;
4347 CharUnits getParamTypeAlignment(QualType Ty) const;
4349 ABIArgInfo classifyReturnType(QualType RetTy) const;
4350 ABIArgInfo classifyArgumentType(QualType Ty) const;
4352 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4353 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4354 uint64_t Members) const override;
4356 // TODO: We can add more logic to computeInfo to improve performance.
4357 // Example: For aggregate arguments that fit in a register, we could
4358 // use getDirectInReg (as is done below for structs containing a single
4359 // floating-point value) to avoid pushing them to memory on function
4360 // entry. This would require changing the logic in PPCISelLowering
4361 // when lowering the parameters in the caller and args in the callee.
4362 void computeInfo(CGFunctionInfo &FI) const override {
4363 if (!getCXXABI().classifyReturnType(FI))
4364 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4365 for (auto &I : FI.arguments()) {
4366 // We rely on the default argument classification for the most part.
4367 // One exception: An aggregate containing a single floating-point
4368 // or vector item must be passed in a register if one is available.
4369 const Type *T = isSingleElementStruct(I.type, getContext());
4371 const BuiltinType *BT = T->getAs<BuiltinType>();
4372 if (IsQPXVectorTy(T) ||
4373 (T->isVectorType() && getContext().getTypeSize(T) == 128) ||
4374 (BT && BT->isFloatingPoint())) {
4376 I.info = ABIArgInfo::getDirectInReg(CGT.ConvertType(QT));
4380 I.info = classifyArgumentType(I.type);
4384 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4385 QualType Ty) const override;
4387 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4388 bool asReturnValue) const override {
4389 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4392 bool isSwiftErrorInRegister() const override {
4397 class PPC64_SVR4_TargetCodeGenInfo : public TargetCodeGenInfo {
4400 PPC64_SVR4_TargetCodeGenInfo(CodeGenTypes &CGT,
4401 PPC64_SVR4_ABIInfo::ABIKind Kind, bool HasQPX,
4403 : TargetCodeGenInfo(new PPC64_SVR4_ABIInfo(CGT, Kind, HasQPX,
4406 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4407 // This is recovered from gcc output.
4408 return 1; // r1 is the dedicated stack pointer
4411 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4412 llvm::Value *Address) const override;
4415 class PPC64TargetCodeGenInfo : public DefaultTargetCodeGenInfo {
4417 PPC64TargetCodeGenInfo(CodeGenTypes &CGT) : DefaultTargetCodeGenInfo(CGT) {}
4419 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4420 // This is recovered from gcc output.
4421 return 1; // r1 is the dedicated stack pointer
4424 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4425 llvm::Value *Address) const override;
4430 // Return true if the ABI requires Ty to be passed sign- or zero-
4431 // extended to 64 bits.
4433 PPC64_SVR4_ABIInfo::isPromotableTypeForABI(QualType Ty) const {
4434 // Treat an enum type as its underlying type.
4435 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
4436 Ty = EnumTy->getDecl()->getIntegerType();
4438 // Promotable integer types are required to be promoted by the ABI.
4439 if (Ty->isPromotableIntegerType())
4442 // In addition to the usual promotable integer types, we also need to
4443 // extend all 32-bit types, since the ABI requires promotion to 64 bits.
4444 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
4445 switch (BT->getKind()) {
4446 case BuiltinType::Int:
4447 case BuiltinType::UInt:
4456 /// isAlignedParamType - Determine whether a type requires 16-byte or
4457 /// higher alignment in the parameter area. Always returns at least 8.
4458 CharUnits PPC64_SVR4_ABIInfo::getParamTypeAlignment(QualType Ty) const {
4459 // Complex types are passed just like their elements.
4460 if (const ComplexType *CTy = Ty->getAs<ComplexType>())
4461 Ty = CTy->getElementType();
4463 // Only vector types of size 16 bytes need alignment (larger types are
4464 // passed via reference, smaller types are not aligned).
4465 if (IsQPXVectorTy(Ty)) {
4466 if (getContext().getTypeSize(Ty) > 128)
4467 return CharUnits::fromQuantity(32);
4469 return CharUnits::fromQuantity(16);
4470 } else if (Ty->isVectorType()) {
4471 return CharUnits::fromQuantity(getContext().getTypeSize(Ty) == 128 ? 16 : 8);
4474 // For single-element float/vector structs, we consider the whole type
4475 // to have the same alignment requirements as its single element.
4476 const Type *AlignAsType = nullptr;
4477 const Type *EltType = isSingleElementStruct(Ty, getContext());
4479 const BuiltinType *BT = EltType->getAs<BuiltinType>();
4480 if (IsQPXVectorTy(EltType) || (EltType->isVectorType() &&
4481 getContext().getTypeSize(EltType) == 128) ||
4482 (BT && BT->isFloatingPoint()))
4483 AlignAsType = EltType;
4486 // Likewise for ELFv2 homogeneous aggregates.
4487 const Type *Base = nullptr;
4488 uint64_t Members = 0;
4489 if (!AlignAsType && Kind == ELFv2 &&
4490 isAggregateTypeForABI(Ty) && isHomogeneousAggregate(Ty, Base, Members))
4493 // With special case aggregates, only vector base types need alignment.
4494 if (AlignAsType && IsQPXVectorTy(AlignAsType)) {
4495 if (getContext().getTypeSize(AlignAsType) > 128)
4496 return CharUnits::fromQuantity(32);
4498 return CharUnits::fromQuantity(16);
4499 } else if (AlignAsType) {
4500 return CharUnits::fromQuantity(AlignAsType->isVectorType() ? 16 : 8);
4503 // Otherwise, we only need alignment for any aggregate type that
4504 // has an alignment requirement of >= 16 bytes.
4505 if (isAggregateTypeForABI(Ty) && getContext().getTypeAlign(Ty) >= 128) {
4506 if (HasQPX && getContext().getTypeAlign(Ty) >= 256)
4507 return CharUnits::fromQuantity(32);
4508 return CharUnits::fromQuantity(16);
4511 return CharUnits::fromQuantity(8);
4514 /// isHomogeneousAggregate - Return true if a type is an ELFv2 homogeneous
4515 /// aggregate. Base is set to the base element type, and Members is set
4516 /// to the number of base elements.
4517 bool ABIInfo::isHomogeneousAggregate(QualType Ty, const Type *&Base,
4518 uint64_t &Members) const {
4519 if (const ConstantArrayType *AT = getContext().getAsConstantArrayType(Ty)) {
4520 uint64_t NElements = AT->getSize().getZExtValue();
4523 if (!isHomogeneousAggregate(AT->getElementType(), Base, Members))
4525 Members *= NElements;
4526 } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
4527 const RecordDecl *RD = RT->getDecl();
4528 if (RD->hasFlexibleArrayMember())
4533 // If this is a C++ record, check the bases first.
4534 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
4535 for (const auto &I : CXXRD->bases()) {
4536 // Ignore empty records.
4537 if (isEmptyRecord(getContext(), I.getType(), true))
4540 uint64_t FldMembers;
4541 if (!isHomogeneousAggregate(I.getType(), Base, FldMembers))
4544 Members += FldMembers;
4548 for (const auto *FD : RD->fields()) {
4549 // Ignore (non-zero arrays of) empty records.
4550 QualType FT = FD->getType();
4551 while (const ConstantArrayType *AT =
4552 getContext().getAsConstantArrayType(FT)) {
4553 if (AT->getSize().getZExtValue() == 0)
4555 FT = AT->getElementType();
4557 if (isEmptyRecord(getContext(), FT, true))
4560 // For compatibility with GCC, ignore empty bitfields in C++ mode.
4561 if (getContext().getLangOpts().CPlusPlus &&
4562 FD->isZeroLengthBitField(getContext()))
4565 uint64_t FldMembers;
4566 if (!isHomogeneousAggregate(FD->getType(), Base, FldMembers))
4569 Members = (RD->isUnion() ?
4570 std::max(Members, FldMembers) : Members + FldMembers);
4576 // Ensure there is no padding.
4577 if (getContext().getTypeSize(Base) * Members !=
4578 getContext().getTypeSize(Ty))
4582 if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
4584 Ty = CT->getElementType();
4587 // Most ABIs only support float, double, and some vector type widths.
4588 if (!isHomogeneousAggregateBaseType(Ty))
4591 // The base type must be the same for all members. Types that
4592 // agree in both total size and mode (float vs. vector) are
4593 // treated as being equivalent here.
4594 const Type *TyPtr = Ty.getTypePtr();
4597 // If it's a non-power-of-2 vector, its size is already a power-of-2,
4598 // so make sure to widen it explicitly.
4599 if (const VectorType *VT = Base->getAs<VectorType>()) {
4600 QualType EltTy = VT->getElementType();
4601 unsigned NumElements =
4602 getContext().getTypeSize(VT) / getContext().getTypeSize(EltTy);
4604 .getVectorType(EltTy, NumElements, VT->getVectorKind())
4609 if (Base->isVectorType() != TyPtr->isVectorType() ||
4610 getContext().getTypeSize(Base) != getContext().getTypeSize(TyPtr))
4613 return Members > 0 && isHomogeneousAggregateSmallEnough(Base, Members);
4616 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
4617 // Homogeneous aggregates for ELFv2 must have base types of float,
4618 // double, long double, or 128-bit vectors.
4619 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
4620 if (BT->getKind() == BuiltinType::Float ||
4621 BT->getKind() == BuiltinType::Double ||
4622 BT->getKind() == BuiltinType::LongDouble ||
4623 (getContext().getTargetInfo().hasFloat128Type() &&
4624 (BT->getKind() == BuiltinType::Float128))) {
4630 if (const VectorType *VT = Ty->getAs<VectorType>()) {
4631 if (getContext().getTypeSize(VT) == 128 || IsQPXVectorTy(Ty))
4637 bool PPC64_SVR4_ABIInfo::isHomogeneousAggregateSmallEnough(
4638 const Type *Base, uint64_t Members) const {
4639 // Vector and fp128 types require one register, other floating point types
4640 // require one or two registers depending on their size.
4642 ((getContext().getTargetInfo().hasFloat128Type() &&
4643 Base->isFloat128Type()) ||
4644 Base->isVectorType()) ? 1
4645 : (getContext().getTypeSize(Base) + 63) / 64;
4647 // Homogeneous Aggregates may occupy at most 8 registers.
4648 return Members * NumRegs <= 8;
4652 PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
4653 Ty = useFirstFieldIfTransparentUnion(Ty);
4655 if (Ty->isAnyComplexType())
4656 return ABIArgInfo::getDirect();
4658 // Non-Altivec vector types are passed in GPRs (smaller than 16 bytes)
4659 // or via reference (larger than 16 bytes).
4660 if (Ty->isVectorType() && !IsQPXVectorTy(Ty)) {
4661 uint64_t Size = getContext().getTypeSize(Ty);
4663 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
4664 else if (Size < 128) {
4665 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4666 return ABIArgInfo::getDirect(CoerceTy);
4670 if (isAggregateTypeForABI(Ty)) {
4671 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
4672 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
4674 uint64_t ABIAlign = getParamTypeAlignment(Ty).getQuantity();
4675 uint64_t TyAlign = getContext().getTypeAlignInChars(Ty).getQuantity();
4677 // ELFv2 homogeneous aggregates are passed as array types.
4678 const Type *Base = nullptr;
4679 uint64_t Members = 0;
4680 if (Kind == ELFv2 &&
4681 isHomogeneousAggregate(Ty, Base, Members)) {
4682 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4683 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4684 return ABIArgInfo::getDirect(CoerceTy);
4687 // If an aggregate may end up fully in registers, we do not
4688 // use the ByVal method, but pass the aggregate as array.
4689 // This is usually beneficial since we avoid forcing the
4690 // back-end to store the argument to memory.
4691 uint64_t Bits = getContext().getTypeSize(Ty);
4692 if (Bits > 0 && Bits <= 8 * GPRBits) {
4693 llvm::Type *CoerceTy;
4695 // Types up to 8 bytes are passed as integer type (which will be
4696 // properly aligned in the argument save area doubleword).
4697 if (Bits <= GPRBits)
4699 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4700 // Larger types are passed as arrays, with the base type selected
4701 // according to the required alignment in the save area.
4703 uint64_t RegBits = ABIAlign * 8;
4704 uint64_t NumRegs = llvm::alignTo(Bits, RegBits) / RegBits;
4705 llvm::Type *RegTy = llvm::IntegerType::get(getVMContext(), RegBits);
4706 CoerceTy = llvm::ArrayType::get(RegTy, NumRegs);
4709 return ABIArgInfo::getDirect(CoerceTy);
4712 // All other aggregates are passed ByVal.
4713 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
4715 /*Realign=*/TyAlign > ABIAlign);
4718 return (isPromotableTypeForABI(Ty) ? ABIArgInfo::getExtend(Ty)
4719 : ABIArgInfo::getDirect());
4723 PPC64_SVR4_ABIInfo::classifyReturnType(QualType RetTy) const {
4724 if (RetTy->isVoidType())
4725 return ABIArgInfo::getIgnore();
4727 if (RetTy->isAnyComplexType())
4728 return ABIArgInfo::getDirect();
4730 // Non-Altivec vector types are returned in GPRs (smaller than 16 bytes)
4731 // or via reference (larger than 16 bytes).
4732 if (RetTy->isVectorType() && !IsQPXVectorTy(RetTy)) {
4733 uint64_t Size = getContext().getTypeSize(RetTy);
4735 return getNaturalAlignIndirect(RetTy);
4736 else if (Size < 128) {
4737 llvm::Type *CoerceTy = llvm::IntegerType::get(getVMContext(), Size);
4738 return ABIArgInfo::getDirect(CoerceTy);
4742 if (isAggregateTypeForABI(RetTy)) {
4743 // ELFv2 homogeneous aggregates are returned as array types.
4744 const Type *Base = nullptr;
4745 uint64_t Members = 0;
4746 if (Kind == ELFv2 &&
4747 isHomogeneousAggregate(RetTy, Base, Members)) {
4748 llvm::Type *BaseTy = CGT.ConvertType(QualType(Base, 0));
4749 llvm::Type *CoerceTy = llvm::ArrayType::get(BaseTy, Members);
4750 return ABIArgInfo::getDirect(CoerceTy);
4753 // ELFv2 small aggregates are returned in up to two registers.
4754 uint64_t Bits = getContext().getTypeSize(RetTy);
4755 if (Kind == ELFv2 && Bits <= 2 * GPRBits) {
4757 return ABIArgInfo::getIgnore();
4759 llvm::Type *CoerceTy;
4760 if (Bits > GPRBits) {
4761 CoerceTy = llvm::IntegerType::get(getVMContext(), GPRBits);
4762 CoerceTy = llvm::StructType::get(CoerceTy, CoerceTy);
4765 llvm::IntegerType::get(getVMContext(), llvm::alignTo(Bits, 8));
4766 return ABIArgInfo::getDirect(CoerceTy);
4769 // All other aggregates are returned indirectly.
4770 return getNaturalAlignIndirect(RetTy);
4773 return (isPromotableTypeForABI(RetTy) ? ABIArgInfo::getExtend(RetTy)
4774 : ABIArgInfo::getDirect());
4777 // Based on ARMABIInfo::EmitVAArg, adjusted for 64-bit machine.
4778 Address PPC64_SVR4_ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4779 QualType Ty) const {
4780 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
4781 TypeInfo.second = getParamTypeAlignment(Ty);
4783 CharUnits SlotSize = CharUnits::fromQuantity(8);
4785 // If we have a complex type and the base type is smaller than 8 bytes,
4786 // the ABI calls for the real and imaginary parts to be right-adjusted
4787 // in separate doublewords. However, Clang expects us to produce a
4788 // pointer to a structure with the two parts packed tightly. So generate
4789 // loads of the real and imaginary parts relative to the va_list pointer,
4790 // and store them to a temporary structure.
4791 if (const ComplexType *CTy = Ty->getAs<ComplexType>()) {
4792 CharUnits EltSize = TypeInfo.first / 2;
4793 if (EltSize < SlotSize) {
4794 Address Addr = emitVoidPtrDirectVAArg(CGF, VAListAddr, CGF.Int8Ty,
4795 SlotSize * 2, SlotSize,
4796 SlotSize, /*AllowHigher*/ true);
4798 Address RealAddr = Addr;
4799 Address ImagAddr = RealAddr;
4800 if (CGF.CGM.getDataLayout().isBigEndian()) {
4801 RealAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr,
4802 SlotSize - EltSize);
4803 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(ImagAddr,
4804 2 * SlotSize - EltSize);
4806 ImagAddr = CGF.Builder.CreateConstInBoundsByteGEP(RealAddr, SlotSize);
4809 llvm::Type *EltTy = CGF.ConvertTypeForMem(CTy->getElementType());
4810 RealAddr = CGF.Builder.CreateElementBitCast(RealAddr, EltTy);
4811 ImagAddr = CGF.Builder.CreateElementBitCast(ImagAddr, EltTy);
4812 llvm::Value *Real = CGF.Builder.CreateLoad(RealAddr, ".vareal");
4813 llvm::Value *Imag = CGF.Builder.CreateLoad(ImagAddr, ".vaimag");
4815 Address Temp = CGF.CreateMemTemp(Ty, "vacplx");
4816 CGF.EmitStoreOfComplex({Real, Imag}, CGF.MakeAddrLValue(Temp, Ty),
4822 // Otherwise, just use the general rule.
4823 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*Indirect*/ false,
4824 TypeInfo, SlotSize, /*AllowHigher*/ true);
4828 PPC64_initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4829 llvm::Value *Address) {
4830 // This is calculated from the LLVM and GCC tables and verified
4831 // against gcc output. AFAIK all ABIs use the same encoding.
4833 CodeGen::CGBuilderTy &Builder = CGF.Builder;
4835 llvm::IntegerType *i8 = CGF.Int8Ty;
4836 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
4837 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
4838 llvm::Value *Sixteen8 = llvm::ConstantInt::get(i8, 16);
4840 // 0-31: r0-31, the 8-byte general-purpose registers
4841 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
4843 // 32-63: fp0-31, the 8-byte floating-point registers
4844 AssignToArrayRange(Builder, Address, Eight8, 32, 63);
4846 // 64-67 are various 8-byte special-purpose registers:
4851 AssignToArrayRange(Builder, Address, Eight8, 64, 67);
4853 // 68-76 are various 4-byte special-purpose registers:
4856 AssignToArrayRange(Builder, Address, Four8, 68, 76);
4858 // 77-108: v0-31, the 16-byte vector registers
4859 AssignToArrayRange(Builder, Address, Sixteen8, 77, 108);
4869 AssignToArrayRange(Builder, Address, Eight8, 109, 116);
4875 PPC64_SVR4_TargetCodeGenInfo::initDwarfEHRegSizeTable(
4876 CodeGen::CodeGenFunction &CGF,
4877 llvm::Value *Address) const {
4879 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4883 PPC64TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
4884 llvm::Value *Address) const {
4886 return PPC64_initDwarfEHRegSizeTable(CGF, Address);
4889 //===----------------------------------------------------------------------===//
4890 // AArch64 ABI Implementation
4891 //===----------------------------------------------------------------------===//
4895 class AArch64ABIInfo : public SwiftABIInfo {
4907 AArch64ABIInfo(CodeGenTypes &CGT, ABIKind Kind)
4908 : SwiftABIInfo(CGT), Kind(Kind) {}
4911 ABIKind getABIKind() const { return Kind; }
4912 bool isDarwinPCS() const { return Kind == DarwinPCS; }
4914 ABIArgInfo classifyReturnType(QualType RetTy) const;
4915 ABIArgInfo classifyArgumentType(QualType RetTy) const;
4916 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
4917 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
4918 uint64_t Members) const override;
4920 bool isIllegalVectorType(QualType Ty) const;
4922 void computeInfo(CGFunctionInfo &FI) const override {
4923 if (!::classifyReturnType(getCXXABI(), FI, *this))
4924 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
4926 for (auto &it : FI.arguments())
4927 it.info = classifyArgumentType(it.type);
4930 Address EmitDarwinVAArg(Address VAListAddr, QualType Ty,
4931 CodeGenFunction &CGF) const;
4933 Address EmitAAPCSVAArg(Address VAListAddr, QualType Ty,
4934 CodeGenFunction &CGF) const;
4936 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
4937 QualType Ty) const override {
4938 return Kind == Win64 ? EmitMSVAArg(CGF, VAListAddr, Ty)
4939 : isDarwinPCS() ? EmitDarwinVAArg(VAListAddr, Ty, CGF)
4940 : EmitAAPCSVAArg(VAListAddr, Ty, CGF);
4943 Address EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
4944 QualType Ty) const override;
4946 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
4947 bool asReturnValue) const override {
4948 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
4950 bool isSwiftErrorInRegister() const override {
4954 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
4955 unsigned elts) const override;
4958 class AArch64TargetCodeGenInfo : public TargetCodeGenInfo {
4960 AArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind Kind)
4961 : TargetCodeGenInfo(new AArch64ABIInfo(CGT, Kind)) {}
4963 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
4964 return "mov\tfp, fp\t\t// marker for objc_retainAutoreleaseReturnValue";
4967 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
4971 bool doesReturnSlotInterfereWithArgs() const override { return false; }
4974 class WindowsAArch64TargetCodeGenInfo : public AArch64TargetCodeGenInfo {
4976 WindowsAArch64TargetCodeGenInfo(CodeGenTypes &CGT, AArch64ABIInfo::ABIKind K)
4977 : AArch64TargetCodeGenInfo(CGT, K) {}
4979 void getDependentLibraryOption(llvm::StringRef Lib,
4980 llvm::SmallString<24> &Opt) const override {
4981 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
4984 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
4985 llvm::SmallString<32> &Opt) const override {
4986 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
4991 ABIArgInfo AArch64ABIInfo::classifyArgumentType(QualType Ty) const {
4992 Ty = useFirstFieldIfTransparentUnion(Ty);
4994 // Handle illegal vector types here.
4995 if (isIllegalVectorType(Ty)) {
4996 uint64_t Size = getContext().getTypeSize(Ty);
4997 // Android promotes <2 x i8> to i16, not i32
4998 if (isAndroid() && (Size <= 16)) {
4999 llvm::Type *ResType = llvm::Type::getInt16Ty(getVMContext());
5000 return ABIArgInfo::getDirect(ResType);
5003 llvm::Type *ResType = llvm::Type::getInt32Ty(getVMContext());
5004 return ABIArgInfo::getDirect(ResType);
5007 llvm::Type *ResType =
5008 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 2);
5009 return ABIArgInfo::getDirect(ResType);
5012 llvm::Type *ResType =
5013 llvm::VectorType::get(llvm::Type::getInt32Ty(getVMContext()), 4);
5014 return ABIArgInfo::getDirect(ResType);
5016 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5019 if (!isAggregateTypeForABI(Ty)) {
5020 // Treat an enum type as its underlying type.
5021 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
5022 Ty = EnumTy->getDecl()->getIntegerType();
5024 return (Ty->isPromotableIntegerType() && isDarwinPCS()
5025 ? ABIArgInfo::getExtend(Ty)
5026 : ABIArgInfo::getDirect());
5029 // Structures with either a non-trivial destructor or a non-trivial
5030 // copy constructor are always indirect.
5031 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5032 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
5033 CGCXXABI::RAA_DirectInMemory);
5036 // Empty records are always ignored on Darwin, but actually passed in C++ mode
5037 // elsewhere for GNU compatibility.
5038 uint64_t Size = getContext().getTypeSize(Ty);
5039 bool IsEmpty = isEmptyRecord(getContext(), Ty, true);
5040 if (IsEmpty || Size == 0) {
5041 if (!getContext().getLangOpts().CPlusPlus || isDarwinPCS())
5042 return ABIArgInfo::getIgnore();
5044 // GNU C mode. The only argument that gets ignored is an empty one with size
5046 if (IsEmpty && Size == 0)
5047 return ABIArgInfo::getIgnore();
5048 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5051 // Homogeneous Floating-point Aggregates (HFAs) need to be expanded.
5052 const Type *Base = nullptr;
5053 uint64_t Members = 0;
5054 if (isHomogeneousAggregate(Ty, Base, Members)) {
5055 return ABIArgInfo::getDirect(
5056 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members));
5059 // Aggregates <= 16 bytes are passed directly in registers or on the stack.
5061 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5062 // same size and alignment.
5063 if (getTarget().isRenderScriptTarget()) {
5064 return coerceToIntArray(Ty, getContext(), getVMContext());
5066 unsigned Alignment = getContext().getTypeAlign(Ty);
5067 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5069 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5070 // For aggregates with 16-byte alignment, we use i128.
5071 if (Alignment < 128 && Size == 128) {
5072 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5073 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5075 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5078 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5081 ABIArgInfo AArch64ABIInfo::classifyReturnType(QualType RetTy) const {
5082 if (RetTy->isVoidType())
5083 return ABIArgInfo::getIgnore();
5085 // Large vector types should be returned via memory.
5086 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128)
5087 return getNaturalAlignIndirect(RetTy);
5089 if (!isAggregateTypeForABI(RetTy)) {
5090 // Treat an enum type as its underlying type.
5091 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5092 RetTy = EnumTy->getDecl()->getIntegerType();
5094 return (RetTy->isPromotableIntegerType() && isDarwinPCS()
5095 ? ABIArgInfo::getExtend(RetTy)
5096 : ABIArgInfo::getDirect());
5099 uint64_t Size = getContext().getTypeSize(RetTy);
5100 if (isEmptyRecord(getContext(), RetTy, true) || Size == 0)
5101 return ABIArgInfo::getIgnore();
5103 const Type *Base = nullptr;
5104 uint64_t Members = 0;
5105 if (isHomogeneousAggregate(RetTy, Base, Members))
5106 // Homogeneous Floating-point Aggregates (HFAs) are returned directly.
5107 return ABIArgInfo::getDirect();
5109 // Aggregates <= 16 bytes are returned directly in registers or on the stack.
5111 // On RenderScript, coerce Aggregates <= 16 bytes to an integer array of
5112 // same size and alignment.
5113 if (getTarget().isRenderScriptTarget()) {
5114 return coerceToIntArray(RetTy, getContext(), getVMContext());
5116 unsigned Alignment = getContext().getTypeAlign(RetTy);
5117 Size = llvm::alignTo(Size, 64); // round up to multiple of 8 bytes
5119 // We use a pair of i64 for 16-byte aggregate with 8-byte alignment.
5120 // For aggregates with 16-byte alignment, we use i128.
5121 if (Alignment < 128 && Size == 128) {
5122 llvm::Type *BaseTy = llvm::Type::getInt64Ty(getVMContext());
5123 return ABIArgInfo::getDirect(llvm::ArrayType::get(BaseTy, Size / 64));
5125 return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(), Size));
5128 return getNaturalAlignIndirect(RetTy);
5131 /// isIllegalVectorType - check whether the vector type is legal for AArch64.
5132 bool AArch64ABIInfo::isIllegalVectorType(QualType Ty) const {
5133 if (const VectorType *VT = Ty->getAs<VectorType>()) {
5134 // Check whether VT is legal.
5135 unsigned NumElements = VT->getNumElements();
5136 uint64_t Size = getContext().getTypeSize(VT);
5137 // NumElements should be power of 2.
5138 if (!llvm::isPowerOf2_32(NumElements))
5140 return Size != 64 && (Size != 128 || NumElements == 1);
5145 bool AArch64ABIInfo::isLegalVectorTypeForSwift(CharUnits totalSize,
5147 unsigned elts) const {
5148 if (!llvm::isPowerOf2_32(elts))
5150 if (totalSize.getQuantity() != 8 &&
5151 (totalSize.getQuantity() != 16 || elts == 1))
5156 bool AArch64ABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
5157 // Homogeneous aggregates for AAPCS64 must have base types of a floating
5158 // point type or a short-vector type. This is the same as the 32-bit ABI,
5159 // but with the difference that any floating-point type is allowed,
5160 // including __fp16.
5161 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
5162 if (BT->isFloatingPoint())
5164 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
5165 unsigned VecSize = getContext().getTypeSize(VT);
5166 if (VecSize == 64 || VecSize == 128)
5172 bool AArch64ABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
5173 uint64_t Members) const {
5174 return Members <= 4;
5177 Address AArch64ABIInfo::EmitAAPCSVAArg(Address VAListAddr,
5179 CodeGenFunction &CGF) const {
5180 ABIArgInfo AI = classifyArgumentType(Ty);
5181 bool IsIndirect = AI.isIndirect();
5183 llvm::Type *BaseTy = CGF.ConvertType(Ty);
5185 BaseTy = llvm::PointerType::getUnqual(BaseTy);
5186 else if (AI.getCoerceToType())
5187 BaseTy = AI.getCoerceToType();
5189 unsigned NumRegs = 1;
5190 if (llvm::ArrayType *ArrTy = dyn_cast<llvm::ArrayType>(BaseTy)) {
5191 BaseTy = ArrTy->getElementType();
5192 NumRegs = ArrTy->getNumElements();
5194 bool IsFPR = BaseTy->isFloatingPointTy() || BaseTy->isVectorTy();
5196 // The AArch64 va_list type and handling is specified in the Procedure Call
5197 // Standard, section B.4:
5207 llvm::BasicBlock *MaybeRegBlock = CGF.createBasicBlock("vaarg.maybe_reg");
5208 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
5209 llvm::BasicBlock *OnStackBlock = CGF.createBasicBlock("vaarg.on_stack");
5210 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
5212 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5213 CharUnits TyAlign = TyInfo.second;
5215 Address reg_offs_p = Address::invalid();
5216 llvm::Value *reg_offs = nullptr;
5218 CharUnits reg_top_offset;
5219 int RegSize = IsIndirect ? 8 : TyInfo.first.getQuantity();
5221 // 3 is the field number of __gr_offs
5223 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
5225 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "gr_offs");
5226 reg_top_index = 1; // field number for __gr_top
5227 reg_top_offset = CharUnits::fromQuantity(8);
5228 RegSize = llvm::alignTo(RegSize, 8);
5230 // 4 is the field number of __vr_offs.
5232 CGF.Builder.CreateStructGEP(VAListAddr, 4, CharUnits::fromQuantity(28),
5234 reg_offs = CGF.Builder.CreateLoad(reg_offs_p, "vr_offs");
5235 reg_top_index = 2; // field number for __vr_top
5236 reg_top_offset = CharUnits::fromQuantity(16);
5237 RegSize = 16 * NumRegs;
5240 //=======================================
5241 // Find out where argument was passed
5242 //=======================================
5244 // If reg_offs >= 0 we're already using the stack for this type of
5245 // argument. We don't want to keep updating reg_offs (in case it overflows,
5246 // though anyone passing 2GB of arguments, each at most 16 bytes, deserves
5247 // whatever they get).
5248 llvm::Value *UsingStack = nullptr;
5249 UsingStack = CGF.Builder.CreateICmpSGE(
5250 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, 0));
5252 CGF.Builder.CreateCondBr(UsingStack, OnStackBlock, MaybeRegBlock);
5254 // Otherwise, at least some kind of argument could go in these registers, the
5255 // question is whether this particular type is too big.
5256 CGF.EmitBlock(MaybeRegBlock);
5258 // Integer arguments may need to correct register alignment (for example a
5259 // "struct { __int128 a; };" gets passed in x_2N, x_{2N+1}). In this case we
5260 // align __gr_offs to calculate the potential address.
5261 if (!IsFPR && !IsIndirect && TyAlign.getQuantity() > 8) {
5262 int Align = TyAlign.getQuantity();
5264 reg_offs = CGF.Builder.CreateAdd(
5265 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, Align - 1),
5267 reg_offs = CGF.Builder.CreateAnd(
5268 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, -Align),
5272 // Update the gr_offs/vr_offs pointer for next call to va_arg on this va_list.
5273 // The fact that this is done unconditionally reflects the fact that
5274 // allocating an argument to the stack also uses up all the remaining
5275 // registers of the appropriate kind.
5276 llvm::Value *NewOffset = nullptr;
5277 NewOffset = CGF.Builder.CreateAdd(
5278 reg_offs, llvm::ConstantInt::get(CGF.Int32Ty, RegSize), "new_reg_offs");
5279 CGF.Builder.CreateStore(NewOffset, reg_offs_p);
5281 // Now we're in a position to decide whether this argument really was in
5282 // registers or not.
5283 llvm::Value *InRegs = nullptr;
5284 InRegs = CGF.Builder.CreateICmpSLE(
5285 NewOffset, llvm::ConstantInt::get(CGF.Int32Ty, 0), "inreg");
5287 CGF.Builder.CreateCondBr(InRegs, InRegBlock, OnStackBlock);
5289 //=======================================
5290 // Argument was in registers
5291 //=======================================
5293 // Now we emit the code for if the argument was originally passed in
5294 // registers. First start the appropriate block:
5295 CGF.EmitBlock(InRegBlock);
5297 llvm::Value *reg_top = nullptr;
5298 Address reg_top_p = CGF.Builder.CreateStructGEP(VAListAddr, reg_top_index,
5299 reg_top_offset, "reg_top_p");
5300 reg_top = CGF.Builder.CreateLoad(reg_top_p, "reg_top");
5301 Address BaseAddr(CGF.Builder.CreateInBoundsGEP(reg_top, reg_offs),
5302 CharUnits::fromQuantity(IsFPR ? 16 : 8));
5303 Address RegAddr = Address::invalid();
5304 llvm::Type *MemTy = CGF.ConvertTypeForMem(Ty);
5307 // If it's been passed indirectly (actually a struct), whatever we find from
5308 // stored registers or on the stack will actually be a struct **.
5309 MemTy = llvm::PointerType::getUnqual(MemTy);
5312 const Type *Base = nullptr;
5313 uint64_t NumMembers = 0;
5314 bool IsHFA = isHomogeneousAggregate(Ty, Base, NumMembers);
5315 if (IsHFA && NumMembers > 1) {
5316 // Homogeneous aggregates passed in registers will have their elements split
5317 // and stored 16-bytes apart regardless of size (they're notionally in qN,
5318 // qN+1, ...). We reload and store into a temporary local variable
5320 assert(!IsIndirect && "Homogeneous aggregates should be passed directly");
5321 auto BaseTyInfo = getContext().getTypeInfoInChars(QualType(Base, 0));
5322 llvm::Type *BaseTy = CGF.ConvertType(QualType(Base, 0));
5323 llvm::Type *HFATy = llvm::ArrayType::get(BaseTy, NumMembers);
5324 Address Tmp = CGF.CreateTempAlloca(HFATy,
5325 std::max(TyAlign, BaseTyInfo.second));
5327 // On big-endian platforms, the value will be right-aligned in its slot.
5329 if (CGF.CGM.getDataLayout().isBigEndian() &&
5330 BaseTyInfo.first.getQuantity() < 16)
5331 Offset = 16 - BaseTyInfo.first.getQuantity();
5333 for (unsigned i = 0; i < NumMembers; ++i) {
5334 CharUnits BaseOffset = CharUnits::fromQuantity(16 * i + Offset);
5336 CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, BaseOffset);
5337 LoadAddr = CGF.Builder.CreateElementBitCast(LoadAddr, BaseTy);
5340 CGF.Builder.CreateConstArrayGEP(Tmp, i, BaseTyInfo.first);
5342 llvm::Value *Elem = CGF.Builder.CreateLoad(LoadAddr);
5343 CGF.Builder.CreateStore(Elem, StoreAddr);
5346 RegAddr = CGF.Builder.CreateElementBitCast(Tmp, MemTy);
5348 // Otherwise the object is contiguous in memory.
5350 // It might be right-aligned in its slot.
5351 CharUnits SlotSize = BaseAddr.getAlignment();
5352 if (CGF.CGM.getDataLayout().isBigEndian() && !IsIndirect &&
5353 (IsHFA || !isAggregateTypeForABI(Ty)) &&
5354 TyInfo.first < SlotSize) {
5355 CharUnits Offset = SlotSize - TyInfo.first;
5356 BaseAddr = CGF.Builder.CreateConstInBoundsByteGEP(BaseAddr, Offset);
5359 RegAddr = CGF.Builder.CreateElementBitCast(BaseAddr, MemTy);
5362 CGF.EmitBranch(ContBlock);
5364 //=======================================
5365 // Argument was on the stack
5366 //=======================================
5367 CGF.EmitBlock(OnStackBlock);
5369 Address stack_p = CGF.Builder.CreateStructGEP(VAListAddr, 0,
5370 CharUnits::Zero(), "stack_p");
5371 llvm::Value *OnStackPtr = CGF.Builder.CreateLoad(stack_p, "stack");
5373 // Again, stack arguments may need realignment. In this case both integer and
5374 // floating-point ones might be affected.
5375 if (!IsIndirect && TyAlign.getQuantity() > 8) {
5376 int Align = TyAlign.getQuantity();
5378 OnStackPtr = CGF.Builder.CreatePtrToInt(OnStackPtr, CGF.Int64Ty);
5380 OnStackPtr = CGF.Builder.CreateAdd(
5381 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, Align - 1),
5383 OnStackPtr = CGF.Builder.CreateAnd(
5384 OnStackPtr, llvm::ConstantInt::get(CGF.Int64Ty, -Align),
5387 OnStackPtr = CGF.Builder.CreateIntToPtr(OnStackPtr, CGF.Int8PtrTy);
5389 Address OnStackAddr(OnStackPtr,
5390 std::max(CharUnits::fromQuantity(8), TyAlign));
5392 // All stack slots are multiples of 8 bytes.
5393 CharUnits StackSlotSize = CharUnits::fromQuantity(8);
5394 CharUnits StackSize;
5396 StackSize = StackSlotSize;
5398 StackSize = TyInfo.first.alignTo(StackSlotSize);
5400 llvm::Value *StackSizeC = CGF.Builder.getSize(StackSize);
5401 llvm::Value *NewStack =
5402 CGF.Builder.CreateInBoundsGEP(OnStackPtr, StackSizeC, "new_stack");
5404 // Write the new value of __stack for the next call to va_arg
5405 CGF.Builder.CreateStore(NewStack, stack_p);
5407 if (CGF.CGM.getDataLayout().isBigEndian() && !isAggregateTypeForABI(Ty) &&
5408 TyInfo.first < StackSlotSize) {
5409 CharUnits Offset = StackSlotSize - TyInfo.first;
5410 OnStackAddr = CGF.Builder.CreateConstInBoundsByteGEP(OnStackAddr, Offset);
5413 OnStackAddr = CGF.Builder.CreateElementBitCast(OnStackAddr, MemTy);
5415 CGF.EmitBranch(ContBlock);
5417 //=======================================
5419 //=======================================
5420 CGF.EmitBlock(ContBlock);
5422 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
5423 OnStackAddr, OnStackBlock, "vaargs.addr");
5426 return Address(CGF.Builder.CreateLoad(ResAddr, "vaarg.addr"),
5432 Address AArch64ABIInfo::EmitDarwinVAArg(Address VAListAddr, QualType Ty,
5433 CodeGenFunction &CGF) const {
5434 // The backend's lowering doesn't support va_arg for aggregates or
5435 // illegal vector types. Lower VAArg here for these cases and use
5436 // the LLVM va_arg instruction for everything else.
5437 if (!isAggregateTypeForABI(Ty) && !isIllegalVectorType(Ty))
5438 return EmitVAArgInstr(CGF, VAListAddr, Ty, ABIArgInfo::getDirect());
5440 CharUnits SlotSize = CharUnits::fromQuantity(8);
5442 // Empty records are ignored for parameter passing purposes.
5443 if (isEmptyRecord(getContext(), Ty, true)) {
5444 Address Addr(CGF.Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
5445 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
5449 // The size of the actual thing passed, which might end up just
5450 // being a pointer for indirect types.
5451 auto TyInfo = getContext().getTypeInfoInChars(Ty);
5453 // Arguments bigger than 16 bytes which aren't homogeneous
5454 // aggregates should be passed indirectly.
5455 bool IsIndirect = false;
5456 if (TyInfo.first.getQuantity() > 16) {
5457 const Type *Base = nullptr;
5458 uint64_t Members = 0;
5459 IsIndirect = !isHomogeneousAggregate(Ty, Base, Members);
5462 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect,
5463 TyInfo, SlotSize, /*AllowHigherAlign*/ true);
5466 Address AArch64ABIInfo::EmitMSVAArg(CodeGenFunction &CGF, Address VAListAddr,
5467 QualType Ty) const {
5468 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
5469 CGF.getContext().getTypeInfoInChars(Ty),
5470 CharUnits::fromQuantity(8),
5471 /*allowHigherAlign*/ false);
5474 //===----------------------------------------------------------------------===//
5475 // ARM ABI Implementation
5476 //===----------------------------------------------------------------------===//
5480 class ARMABIInfo : public SwiftABIInfo {
5493 ARMABIInfo(CodeGenTypes &CGT, ABIKind _Kind)
5494 : SwiftABIInfo(CGT), Kind(_Kind) {
5498 bool isEABI() const {
5499 switch (getTarget().getTriple().getEnvironment()) {
5500 case llvm::Triple::Android:
5501 case llvm::Triple::EABI:
5502 case llvm::Triple::EABIHF:
5503 case llvm::Triple::GNUEABI:
5504 case llvm::Triple::GNUEABIHF:
5505 case llvm::Triple::MuslEABI:
5506 case llvm::Triple::MuslEABIHF:
5513 bool isEABIHF() const {
5514 switch (getTarget().getTriple().getEnvironment()) {
5515 case llvm::Triple::EABIHF:
5516 case llvm::Triple::GNUEABIHF:
5517 case llvm::Triple::MuslEABIHF:
5524 ABIKind getABIKind() const { return Kind; }
5527 ABIArgInfo classifyReturnType(QualType RetTy, bool isVariadic) const;
5528 ABIArgInfo classifyArgumentType(QualType RetTy, bool isVariadic) const;
5529 bool isIllegalVectorType(QualType Ty) const;
5531 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
5532 bool isHomogeneousAggregateSmallEnough(const Type *Ty,
5533 uint64_t Members) const override;
5535 void computeInfo(CGFunctionInfo &FI) const override;
5537 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
5538 QualType Ty) const override;
5540 llvm::CallingConv::ID getLLVMDefaultCC() const;
5541 llvm::CallingConv::ID getABIDefaultCC() const;
5544 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
5545 bool asReturnValue) const override {
5546 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
5548 bool isSwiftErrorInRegister() const override {
5551 bool isLegalVectorTypeForSwift(CharUnits totalSize, llvm::Type *eltTy,
5552 unsigned elts) const override;
5555 class ARMTargetCodeGenInfo : public TargetCodeGenInfo {
5557 ARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5558 :TargetCodeGenInfo(new ARMABIInfo(CGT, K)) {}
5560 const ARMABIInfo &getABIInfo() const {
5561 return static_cast<const ARMABIInfo&>(TargetCodeGenInfo::getABIInfo());
5564 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
5568 StringRef getARCRetainAutoreleasedReturnValueMarker() const override {
5569 return "mov\tr7, r7\t\t// marker for objc_retainAutoreleaseReturnValue";
5572 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
5573 llvm::Value *Address) const override {
5574 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
5576 // 0-15 are the 16 integer registers.
5577 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 15);
5581 unsigned getSizeOfUnwindException() const override {
5582 if (getABIInfo().isEABI()) return 88;
5583 return TargetCodeGenInfo::getSizeOfUnwindException();
5586 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5587 CodeGen::CodeGenModule &CGM) const override {
5588 if (GV->isDeclaration())
5590 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
5594 const ARMInterruptAttr *Attr = FD->getAttr<ARMInterruptAttr>();
5599 switch (Attr->getInterrupt()) {
5600 case ARMInterruptAttr::Generic: Kind = ""; break;
5601 case ARMInterruptAttr::IRQ: Kind = "IRQ"; break;
5602 case ARMInterruptAttr::FIQ: Kind = "FIQ"; break;
5603 case ARMInterruptAttr::SWI: Kind = "SWI"; break;
5604 case ARMInterruptAttr::ABORT: Kind = "ABORT"; break;
5605 case ARMInterruptAttr::UNDEF: Kind = "UNDEF"; break;
5608 llvm::Function *Fn = cast<llvm::Function>(GV);
5610 Fn->addFnAttr("interrupt", Kind);
5612 ARMABIInfo::ABIKind ABI = cast<ARMABIInfo>(getABIInfo()).getABIKind();
5613 if (ABI == ARMABIInfo::APCS)
5616 // AAPCS guarantees that sp will be 8-byte aligned on any public interface,
5617 // however this is not necessarily true on taking any interrupt. Instruct
5618 // the backend to perform a realignment as part of the function prologue.
5619 llvm::AttrBuilder B;
5620 B.addStackAlignmentAttr(8);
5621 Fn->addAttributes(llvm::AttributeList::FunctionIndex, B);
5625 class WindowsARMTargetCodeGenInfo : public ARMTargetCodeGenInfo {
5627 WindowsARMTargetCodeGenInfo(CodeGenTypes &CGT, ARMABIInfo::ABIKind K)
5628 : ARMTargetCodeGenInfo(CGT, K) {}
5630 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
5631 CodeGen::CodeGenModule &CGM) const override;
5633 void getDependentLibraryOption(llvm::StringRef Lib,
5634 llvm::SmallString<24> &Opt) const override {
5635 Opt = "/DEFAULTLIB:" + qualifyWindowsLibrary(Lib);
5638 void getDetectMismatchOption(llvm::StringRef Name, llvm::StringRef Value,
5639 llvm::SmallString<32> &Opt) const override {
5640 Opt = "/FAILIFMISMATCH:\"" + Name.str() + "=" + Value.str() + "\"";
5644 void WindowsARMTargetCodeGenInfo::setTargetAttributes(
5645 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &CGM) const {
5646 ARMTargetCodeGenInfo::setTargetAttributes(D, GV, CGM);
5647 if (GV->isDeclaration())
5649 addStackProbeTargetAttributes(D, GV, CGM);
5653 void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
5654 if (!::classifyReturnType(getCXXABI(), FI, *this))
5655 FI.getReturnInfo() =
5656 classifyReturnType(FI.getReturnType(), FI.isVariadic());
5658 for (auto &I : FI.arguments())
5659 I.info = classifyArgumentType(I.type, FI.isVariadic());
5661 // Always honor user-specified calling convention.
5662 if (FI.getCallingConvention() != llvm::CallingConv::C)
5665 llvm::CallingConv::ID cc = getRuntimeCC();
5666 if (cc != llvm::CallingConv::C)
5667 FI.setEffectiveCallingConvention(cc);
5670 /// Return the default calling convention that LLVM will use.
5671 llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
5672 // The default calling convention that LLVM will infer.
5673 if (isEABIHF() || getTarget().getTriple().isWatchABI())
5674 return llvm::CallingConv::ARM_AAPCS_VFP;
5676 return llvm::CallingConv::ARM_AAPCS;
5678 return llvm::CallingConv::ARM_APCS;
5681 /// Return the calling convention that our ABI would like us to use
5682 /// as the C calling convention.
5683 llvm::CallingConv::ID ARMABIInfo::getABIDefaultCC() const {
5684 switch (getABIKind()) {
5685 case APCS: return llvm::CallingConv::ARM_APCS;
5686 case AAPCS: return llvm::CallingConv::ARM_AAPCS;
5687 case AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5688 case AAPCS16_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
5690 llvm_unreachable("bad ABI kind");
5693 void ARMABIInfo::setCCs() {
5694 assert(getRuntimeCC() == llvm::CallingConv::C);
5696 // Don't muddy up the IR with a ton of explicit annotations if
5697 // they'd just match what LLVM will infer from the triple.
5698 llvm::CallingConv::ID abiCC = getABIDefaultCC();
5699 if (abiCC != getLLVMDefaultCC())
5703 ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty,
5704 bool isVariadic) const {
5705 // 6.1.2.1 The following argument types are VFP CPRCs:
5706 // A single-precision floating-point type (including promoted
5707 // half-precision types); A double-precision floating-point type;
5708 // A 64-bit or 128-bit containerized vector type; Homogeneous Aggregate
5709 // with a Base Type of a single- or double-precision floating-point type,
5710 // 64-bit containerized vectors or 128-bit containerized vectors with one
5711 // to four Elements.
5712 bool IsEffectivelyAAPCS_VFP = getABIKind() == AAPCS_VFP && !isVariadic;
5714 Ty = useFirstFieldIfTransparentUnion(Ty);
5716 // Handle illegal vector types here.
5717 if (isIllegalVectorType(Ty)) {
5718 uint64_t Size = getContext().getTypeSize(Ty);
5720 llvm::Type *ResType =
5721 llvm::Type::getInt32Ty(getVMContext());
5722 return ABIArgInfo::getDirect(ResType);
5725 llvm::Type *ResType = llvm::VectorType::get(
5726 llvm::Type::getInt32Ty(getVMContext()), 2);
5727 return ABIArgInfo::getDirect(ResType);
5730 llvm::Type *ResType = llvm::VectorType::get(
5731 llvm::Type::getInt32Ty(getVMContext()), 4);
5732 return ABIArgInfo::getDirect(ResType);
5734 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
5737 // _Float16 and __fp16 get passed as if it were an int or float, but with
5738 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5739 // half type natively, and does not need to interwork with AAPCS code.
5740 if ((Ty->isFloat16Type() || Ty->isHalfType()) &&
5741 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5742 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5743 llvm::Type::getFloatTy(getVMContext()) :
5744 llvm::Type::getInt32Ty(getVMContext());
5745 return ABIArgInfo::getDirect(ResType);
5748 if (!isAggregateTypeForABI(Ty)) {
5749 // Treat an enum type as its underlying type.
5750 if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
5751 Ty = EnumTy->getDecl()->getIntegerType();
5754 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
5755 : ABIArgInfo::getDirect());
5758 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
5759 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
5762 // Ignore empty records.
5763 if (isEmptyRecord(getContext(), Ty, true))
5764 return ABIArgInfo::getIgnore();
5766 if (IsEffectivelyAAPCS_VFP) {
5767 // Homogeneous Aggregates need to be expanded when we can fit the aggregate
5768 // into VFP registers.
5769 const Type *Base = nullptr;
5770 uint64_t Members = 0;
5771 if (isHomogeneousAggregate(Ty, Base, Members)) {
5772 assert(Base && "Base class should be set for homogeneous aggregate");
5773 // Base can be a floating-point or a vector.
5774 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
5776 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
5777 // WatchOS does have homogeneous aggregates. Note that we intentionally use
5778 // this convention even for a variadic function: the backend will use GPRs
5780 const Type *Base = nullptr;
5781 uint64_t Members = 0;
5782 if (isHomogeneousAggregate(Ty, Base, Members)) {
5783 assert(Base && Members <= 4 && "unexpected homogeneous aggregate");
5785 llvm::ArrayType::get(CGT.ConvertType(QualType(Base, 0)), Members);
5786 return ABIArgInfo::getDirect(Ty, 0, nullptr, false);
5790 if (getABIKind() == ARMABIInfo::AAPCS16_VFP &&
5791 getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(16)) {
5792 // WatchOS is adopting the 64-bit AAPCS rule on composite types: if they're
5793 // bigger than 128-bits, they get placed in space allocated by the caller,
5794 // and a pointer is passed.
5795 return ABIArgInfo::getIndirect(
5796 CharUnits::fromQuantity(getContext().getTypeAlign(Ty) / 8), false);
5799 // Support byval for ARM.
5800 // The ABI alignment for APCS is 4-byte and for AAPCS at least 4-byte and at
5801 // most 8-byte. We realign the indirect argument if type alignment is bigger
5802 // than ABI alignment.
5803 uint64_t ABIAlign = 4;
5804 uint64_t TyAlign = getContext().getTypeAlign(Ty) / 8;
5805 if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
5806 getABIKind() == ARMABIInfo::AAPCS)
5807 ABIAlign = std::min(std::max(TyAlign, (uint64_t)4), (uint64_t)8);
5809 if (getContext().getTypeSizeInChars(Ty) > CharUnits::fromQuantity(64)) {
5810 assert(getABIKind() != ARMABIInfo::AAPCS16_VFP && "unexpected byval");
5811 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(ABIAlign),
5813 /*Realign=*/TyAlign > ABIAlign);
5816 // On RenderScript, coerce Aggregates <= 64 bytes to an integer array of
5817 // same size and alignment.
5818 if (getTarget().isRenderScriptTarget()) {
5819 return coerceToIntArray(Ty, getContext(), getVMContext());
5822 // Otherwise, pass by coercing to a structure of the appropriate size.
5825 // FIXME: Try to match the types of the arguments more accurately where
5827 if (getContext().getTypeAlign(Ty) <= 32) {
5828 ElemTy = llvm::Type::getInt32Ty(getVMContext());
5829 SizeRegs = (getContext().getTypeSize(Ty) + 31) / 32;
5831 ElemTy = llvm::Type::getInt64Ty(getVMContext());
5832 SizeRegs = (getContext().getTypeSize(Ty) + 63) / 64;
5835 return ABIArgInfo::getDirect(llvm::ArrayType::get(ElemTy, SizeRegs));
5838 static bool isIntegerLikeType(QualType Ty, ASTContext &Context,
5839 llvm::LLVMContext &VMContext) {
5840 // APCS, C Language Calling Conventions, Non-Simple Return Values: A structure
5841 // is called integer-like if its size is less than or equal to one word, and
5842 // the offset of each of its addressable sub-fields is zero.
5844 uint64_t Size = Context.getTypeSize(Ty);
5846 // Check that the type fits in a word.
5850 // FIXME: Handle vector types!
5851 if (Ty->isVectorType())
5854 // Float types are never treated as "integer like".
5855 if (Ty->isRealFloatingType())
5858 // If this is a builtin or pointer type then it is ok.
5859 if (Ty->getAs<BuiltinType>() || Ty->isPointerType())
5862 // Small complex integer types are "integer like".
5863 if (const ComplexType *CT = Ty->getAs<ComplexType>())
5864 return isIntegerLikeType(CT->getElementType(), Context, VMContext);
5866 // Single element and zero sized arrays should be allowed, by the definition
5867 // above, but they are not.
5869 // Otherwise, it must be a record type.
5870 const RecordType *RT = Ty->getAs<RecordType>();
5871 if (!RT) return false;
5873 // Ignore records with flexible arrays.
5874 const RecordDecl *RD = RT->getDecl();
5875 if (RD->hasFlexibleArrayMember())
5878 // Check that all sub-fields are at offset 0, and are themselves "integer
5880 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
5882 bool HadField = false;
5884 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
5885 i != e; ++i, ++idx) {
5886 const FieldDecl *FD = *i;
5888 // Bit-fields are not addressable, we only need to verify they are "integer
5889 // like". We still have to disallow a subsequent non-bitfield, for example:
5890 // struct { int : 0; int x }
5891 // is non-integer like according to gcc.
5892 if (FD->isBitField()) {
5896 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5902 // Check if this field is at offset 0.
5903 if (Layout.getFieldOffset(idx) != 0)
5906 if (!isIntegerLikeType(FD->getType(), Context, VMContext))
5909 // Only allow at most one field in a structure. This doesn't match the
5910 // wording above, but follows gcc in situations with a field following an
5912 if (!RD->isUnion()) {
5923 ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy,
5924 bool isVariadic) const {
5925 bool IsEffectivelyAAPCS_VFP =
5926 (getABIKind() == AAPCS_VFP || getABIKind() == AAPCS16_VFP) && !isVariadic;
5928 if (RetTy->isVoidType())
5929 return ABIArgInfo::getIgnore();
5931 // Large vector types should be returned via memory.
5932 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 128) {
5933 return getNaturalAlignIndirect(RetTy);
5936 // _Float16 and __fp16 get returned as if it were an int or float, but with
5937 // the top 16 bits unspecified. This is not done for OpenCL as it handles the
5938 // half type natively, and does not need to interwork with AAPCS code.
5939 if ((RetTy->isFloat16Type() || RetTy->isHalfType()) &&
5940 !getContext().getLangOpts().NativeHalfArgsAndReturns) {
5941 llvm::Type *ResType = IsEffectivelyAAPCS_VFP ?
5942 llvm::Type::getFloatTy(getVMContext()) :
5943 llvm::Type::getInt32Ty(getVMContext());
5944 return ABIArgInfo::getDirect(ResType);
5947 if (!isAggregateTypeForABI(RetTy)) {
5948 // Treat an enum type as its underlying type.
5949 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
5950 RetTy = EnumTy->getDecl()->getIntegerType();
5952 return RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
5953 : ABIArgInfo::getDirect();
5956 // Are we following APCS?
5957 if (getABIKind() == APCS) {
5958 if (isEmptyRecord(getContext(), RetTy, false))
5959 return ABIArgInfo::getIgnore();
5961 // Complex types are all returned as packed integers.
5963 // FIXME: Consider using 2 x vector types if the back end handles them
5965 if (RetTy->isAnyComplexType())
5966 return ABIArgInfo::getDirect(llvm::IntegerType::get(
5967 getVMContext(), getContext().getTypeSize(RetTy)));
5969 // Integer like structures are returned in r0.
5970 if (isIntegerLikeType(RetTy, getContext(), getVMContext())) {
5971 // Return in the smallest viable integer type.
5972 uint64_t Size = getContext().getTypeSize(RetTy);
5974 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
5976 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
5977 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
5980 // Otherwise return in memory.
5981 return getNaturalAlignIndirect(RetTy);
5984 // Otherwise this is an AAPCS variant.
5986 if (isEmptyRecord(getContext(), RetTy, true))
5987 return ABIArgInfo::getIgnore();
5989 // Check for homogeneous aggregates with AAPCS-VFP.
5990 if (IsEffectivelyAAPCS_VFP) {
5991 const Type *Base = nullptr;
5992 uint64_t Members = 0;
5993 if (isHomogeneousAggregate(RetTy, Base, Members)) {
5994 assert(Base && "Base class should be set for homogeneous aggregate");
5995 // Homogeneous Aggregates are returned directly.
5996 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
6000 // Aggregates <= 4 bytes are returned in r0; other aggregates
6001 // are returned indirectly.
6002 uint64_t Size = getContext().getTypeSize(RetTy);
6004 // On RenderScript, coerce Aggregates <= 4 bytes to an integer array of
6005 // same size and alignment.
6006 if (getTarget().isRenderScriptTarget()) {
6007 return coerceToIntArray(RetTy, getContext(), getVMContext());
6009 if (getDataLayout().isBigEndian())
6010 // Return in 32 bit integer integer type (as if loaded by LDR, AAPCS 5.4)
6011 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6013 // Return in the smallest viable integer type.
6015 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
6017 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
6018 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
6019 } else if (Size <= 128 && getABIKind() == AAPCS16_VFP) {
6020 llvm::Type *Int32Ty = llvm::Type::getInt32Ty(getVMContext());
6021 llvm::Type *CoerceTy =
6022 llvm::ArrayType::get(Int32Ty, llvm::alignTo(Size, 32) / 32);
6023 return ABIArgInfo::getDirect(CoerceTy);
6026 return getNaturalAlignIndirect(RetTy);
6029 /// isIllegalVector - check whether Ty is an illegal vector type.
6030 bool ARMABIInfo::isIllegalVectorType(QualType Ty) const {
6031 if (const VectorType *VT = Ty->getAs<VectorType> ()) {
6033 // Android shipped using Clang 3.1, which supported a slightly different
6034 // vector ABI. The primary differences were that 3-element vector types
6035 // were legal, and so were sub 32-bit vectors (i.e. <2 x i8>). This path
6036 // accepts that legacy behavior for Android only.
6037 // Check whether VT is legal.
6038 unsigned NumElements = VT->getNumElements();
6039 // NumElements should be power of 2 or equal to 3.
6040 if (!llvm::isPowerOf2_32(NumElements) && NumElements != 3)
6043 // Check whether VT is legal.
6044 unsigned NumElements = VT->getNumElements();
6045 uint64_t Size = getContext().getTypeSize(VT);
6046 // NumElements should be power of 2.
6047 if (!llvm::isPowerOf2_32(NumElements))
6049 // Size should be greater than 32 bits.
6056 bool ARMABIInfo::isLegalVectorTypeForSwift(CharUnits vectorSize,
6058 unsigned numElts) const {
6059 if (!llvm::isPowerOf2_32(numElts))
6061 unsigned size = getDataLayout().getTypeStoreSizeInBits(eltTy);
6064 if (vectorSize.getQuantity() != 8 &&
6065 (vectorSize.getQuantity() != 16 || numElts == 1))
6070 bool ARMABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
6071 // Homogeneous aggregates for AAPCS-VFP must have base types of float,
6072 // double, or 64-bit or 128-bit vectors.
6073 if (const BuiltinType *BT = Ty->getAs<BuiltinType>()) {
6074 if (BT->getKind() == BuiltinType::Float ||
6075 BT->getKind() == BuiltinType::Double ||
6076 BT->getKind() == BuiltinType::LongDouble)
6078 } else if (const VectorType *VT = Ty->getAs<VectorType>()) {
6079 unsigned VecSize = getContext().getTypeSize(VT);
6080 if (VecSize == 64 || VecSize == 128)
6086 bool ARMABIInfo::isHomogeneousAggregateSmallEnough(const Type *Base,
6087 uint64_t Members) const {
6088 return Members <= 4;
6091 Address ARMABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6092 QualType Ty) const {
6093 CharUnits SlotSize = CharUnits::fromQuantity(4);
6095 // Empty records are ignored for parameter passing purposes.
6096 if (isEmptyRecord(getContext(), Ty, true)) {
6097 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
6098 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
6102 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6103 CharUnits TyAlignForABI = TyInfo.second;
6105 // Use indirect if size of the illegal vector is bigger than 16 bytes.
6106 bool IsIndirect = false;
6107 const Type *Base = nullptr;
6108 uint64_t Members = 0;
6109 if (TyInfo.first > CharUnits::fromQuantity(16) && isIllegalVectorType(Ty)) {
6112 // ARMv7k passes structs bigger than 16 bytes indirectly, in space
6113 // allocated by the caller.
6114 } else if (TyInfo.first > CharUnits::fromQuantity(16) &&
6115 getABIKind() == ARMABIInfo::AAPCS16_VFP &&
6116 !isHomogeneousAggregate(Ty, Base, Members)) {
6119 // Otherwise, bound the type's ABI alignment.
6120 // The ABI alignment for 64-bit or 128-bit vectors is 8 for AAPCS and 4 for
6121 // APCS. For AAPCS, the ABI alignment is at least 4-byte and at most 8-byte.
6122 // Our callers should be prepared to handle an under-aligned address.
6123 } else if (getABIKind() == ARMABIInfo::AAPCS_VFP ||
6124 getABIKind() == ARMABIInfo::AAPCS) {
6125 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6126 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(8));
6127 } else if (getABIKind() == ARMABIInfo::AAPCS16_VFP) {
6128 // ARMv7k allows type alignment up to 16 bytes.
6129 TyAlignForABI = std::max(TyAlignForABI, CharUnits::fromQuantity(4));
6130 TyAlignForABI = std::min(TyAlignForABI, CharUnits::fromQuantity(16));
6132 TyAlignForABI = CharUnits::fromQuantity(4);
6134 TyInfo.second = TyAlignForABI;
6136 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, TyInfo,
6137 SlotSize, /*AllowHigherAlign*/ true);
6140 //===----------------------------------------------------------------------===//
6141 // NVPTX ABI Implementation
6142 //===----------------------------------------------------------------------===//
6146 class NVPTXABIInfo : public ABIInfo {
6148 NVPTXABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
6150 ABIArgInfo classifyReturnType(QualType RetTy) const;
6151 ABIArgInfo classifyArgumentType(QualType Ty) const;
6153 void computeInfo(CGFunctionInfo &FI) const override;
6154 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6155 QualType Ty) const override;
6158 class NVPTXTargetCodeGenInfo : public TargetCodeGenInfo {
6160 NVPTXTargetCodeGenInfo(CodeGenTypes &CGT)
6161 : TargetCodeGenInfo(new NVPTXABIInfo(CGT)) {}
6163 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6164 CodeGen::CodeGenModule &M) const override;
6165 bool shouldEmitStaticExternCAliases() const override;
6168 // Adds a NamedMDNode with F, Name, and Operand as operands, and adds the
6169 // resulting MDNode to the nvvm.annotations MDNode.
6170 static void addNVVMMetadata(llvm::Function *F, StringRef Name, int Operand);
6173 ABIArgInfo NVPTXABIInfo::classifyReturnType(QualType RetTy) const {
6174 if (RetTy->isVoidType())
6175 return ABIArgInfo::getIgnore();
6177 // note: this is different from default ABI
6178 if (!RetTy->isScalarType())
6179 return ABIArgInfo::getDirect();
6181 // Treat an enum type as its underlying type.
6182 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6183 RetTy = EnumTy->getDecl()->getIntegerType();
6185 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6186 : ABIArgInfo::getDirect());
6189 ABIArgInfo NVPTXABIInfo::classifyArgumentType(QualType Ty) const {
6190 // Treat an enum type as its underlying type.
6191 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6192 Ty = EnumTy->getDecl()->getIntegerType();
6194 // Return aggregates type as indirect by value
6195 if (isAggregateTypeForABI(Ty))
6196 return getNaturalAlignIndirect(Ty, /* byval */ true);
6198 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
6199 : ABIArgInfo::getDirect());
6202 void NVPTXABIInfo::computeInfo(CGFunctionInfo &FI) const {
6203 if (!getCXXABI().classifyReturnType(FI))
6204 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6205 for (auto &I : FI.arguments())
6206 I.info = classifyArgumentType(I.type);
6208 // Always honor user-specified calling convention.
6209 if (FI.getCallingConvention() != llvm::CallingConv::C)
6212 FI.setEffectiveCallingConvention(getRuntimeCC());
6215 Address NVPTXABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6216 QualType Ty) const {
6217 llvm_unreachable("NVPTX does not support varargs");
6220 void NVPTXTargetCodeGenInfo::setTargetAttributes(
6221 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6222 if (GV->isDeclaration())
6224 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6227 llvm::Function *F = cast<llvm::Function>(GV);
6229 // Perform special handling in OpenCL mode
6230 if (M.getLangOpts().OpenCL) {
6231 // Use OpenCL function attributes to check for kernel functions
6232 // By default, all functions are device functions
6233 if (FD->hasAttr<OpenCLKernelAttr>()) {
6234 // OpenCL __kernel functions get kernel metadata
6235 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6236 addNVVMMetadata(F, "kernel", 1);
6237 // And kernel functions are not subject to inlining
6238 F->addFnAttr(llvm::Attribute::NoInline);
6242 // Perform special handling in CUDA mode.
6243 if (M.getLangOpts().CUDA) {
6244 // CUDA __global__ functions get a kernel metadata entry. Since
6245 // __global__ functions cannot be called from the device, we do not
6246 // need to set the noinline attribute.
6247 if (FD->hasAttr<CUDAGlobalAttr>()) {
6248 // Create !{<func-ref>, metadata !"kernel", i32 1} node
6249 addNVVMMetadata(F, "kernel", 1);
6251 if (CUDALaunchBoundsAttr *Attr = FD->getAttr<CUDALaunchBoundsAttr>()) {
6252 // Create !{<func-ref>, metadata !"maxntidx", i32 <val>} node
6253 llvm::APSInt MaxThreads(32);
6254 MaxThreads = Attr->getMaxThreads()->EvaluateKnownConstInt(M.getContext());
6256 addNVVMMetadata(F, "maxntidx", MaxThreads.getExtValue());
6258 // min blocks is an optional argument for CUDALaunchBoundsAttr. If it was
6259 // not specified in __launch_bounds__ or if the user specified a 0 value,
6260 // we don't have to add a PTX directive.
6261 if (Attr->getMinBlocks()) {
6262 llvm::APSInt MinBlocks(32);
6263 MinBlocks = Attr->getMinBlocks()->EvaluateKnownConstInt(M.getContext());
6265 // Create !{<func-ref>, metadata !"minctasm", i32 <val>} node
6266 addNVVMMetadata(F, "minctasm", MinBlocks.getExtValue());
6272 void NVPTXTargetCodeGenInfo::addNVVMMetadata(llvm::Function *F, StringRef Name,
6274 llvm::Module *M = F->getParent();
6275 llvm::LLVMContext &Ctx = M->getContext();
6277 // Get "nvvm.annotations" metadata node
6278 llvm::NamedMDNode *MD = M->getOrInsertNamedMetadata("nvvm.annotations");
6280 llvm::Metadata *MDVals[] = {
6281 llvm::ConstantAsMetadata::get(F), llvm::MDString::get(Ctx, Name),
6282 llvm::ConstantAsMetadata::get(
6283 llvm::ConstantInt::get(llvm::Type::getInt32Ty(Ctx), Operand))};
6284 // Append metadata to nvvm.annotations
6285 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
6288 bool NVPTXTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
6293 //===----------------------------------------------------------------------===//
6294 // SystemZ ABI Implementation
6295 //===----------------------------------------------------------------------===//
6299 class SystemZABIInfo : public SwiftABIInfo {
6303 SystemZABIInfo(CodeGenTypes &CGT, bool HV)
6304 : SwiftABIInfo(CGT), HasVector(HV) {}
6306 bool isPromotableIntegerType(QualType Ty) const;
6307 bool isCompoundType(QualType Ty) const;
6308 bool isVectorArgumentType(QualType Ty) const;
6309 bool isFPArgumentType(QualType Ty) const;
6310 QualType GetSingleElementType(QualType Ty) const;
6312 ABIArgInfo classifyReturnType(QualType RetTy) const;
6313 ABIArgInfo classifyArgumentType(QualType ArgTy) const;
6315 void computeInfo(CGFunctionInfo &FI) const override {
6316 if (!getCXXABI().classifyReturnType(FI))
6317 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
6318 for (auto &I : FI.arguments())
6319 I.info = classifyArgumentType(I.type);
6322 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6323 QualType Ty) const override;
6325 bool shouldPassIndirectlyForSwift(ArrayRef<llvm::Type*> scalars,
6326 bool asReturnValue) const override {
6327 return occupiesMoreThan(CGT, scalars, /*total*/ 4);
6329 bool isSwiftErrorInRegister() const override {
6334 class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
6336 SystemZTargetCodeGenInfo(CodeGenTypes &CGT, bool HasVector)
6337 : TargetCodeGenInfo(new SystemZABIInfo(CGT, HasVector)) {}
6342 bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
6343 // Treat an enum type as its underlying type.
6344 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6345 Ty = EnumTy->getDecl()->getIntegerType();
6347 // Promotable integer types are required to be promoted by the ABI.
6348 if (Ty->isPromotableIntegerType())
6351 // 32-bit values must also be promoted.
6352 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6353 switch (BT->getKind()) {
6354 case BuiltinType::Int:
6355 case BuiltinType::UInt:
6363 bool SystemZABIInfo::isCompoundType(QualType Ty) const {
6364 return (Ty->isAnyComplexType() ||
6365 Ty->isVectorType() ||
6366 isAggregateTypeForABI(Ty));
6369 bool SystemZABIInfo::isVectorArgumentType(QualType Ty) const {
6370 return (HasVector &&
6371 Ty->isVectorType() &&
6372 getContext().getTypeSize(Ty) <= 128);
6375 bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
6376 if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
6377 switch (BT->getKind()) {
6378 case BuiltinType::Float:
6379 case BuiltinType::Double:
6388 QualType SystemZABIInfo::GetSingleElementType(QualType Ty) const {
6389 if (const RecordType *RT = Ty->getAsStructureType()) {
6390 const RecordDecl *RD = RT->getDecl();
6393 // If this is a C++ record, check the bases first.
6394 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
6395 for (const auto &I : CXXRD->bases()) {
6396 QualType Base = I.getType();
6398 // Empty bases don't affect things either way.
6399 if (isEmptyRecord(getContext(), Base, true))
6402 if (!Found.isNull())
6404 Found = GetSingleElementType(Base);
6407 // Check the fields.
6408 for (const auto *FD : RD->fields()) {
6409 // For compatibility with GCC, ignore empty bitfields in C++ mode.
6410 // Unlike isSingleElementStruct(), empty structure and array fields
6411 // do count. So do anonymous bitfields that aren't zero-sized.
6412 if (getContext().getLangOpts().CPlusPlus &&
6413 FD->isZeroLengthBitField(getContext()))
6416 // Unlike isSingleElementStruct(), arrays do not count.
6417 // Nested structures still do though.
6418 if (!Found.isNull())
6420 Found = GetSingleElementType(FD->getType());
6423 // Unlike isSingleElementStruct(), trailing padding is allowed.
6424 // An 8-byte aligned struct s { float f; } is passed as a double.
6425 if (!Found.isNull())
6432 Address SystemZABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6433 QualType Ty) const {
6434 // Assume that va_list type is correct; should be pointer to LLVM type:
6438 // i8 *__overflow_arg_area;
6439 // i8 *__reg_save_area;
6442 // Every non-vector argument occupies 8 bytes and is passed by preference
6443 // in either GPRs or FPRs. Vector arguments occupy 8 or 16 bytes and are
6444 // always passed on the stack.
6445 Ty = getContext().getCanonicalType(Ty);
6446 auto TyInfo = getContext().getTypeInfoInChars(Ty);
6447 llvm::Type *ArgTy = CGF.ConvertTypeForMem(Ty);
6448 llvm::Type *DirectTy = ArgTy;
6449 ABIArgInfo AI = classifyArgumentType(Ty);
6450 bool IsIndirect = AI.isIndirect();
6451 bool InFPRs = false;
6452 bool IsVector = false;
6453 CharUnits UnpaddedSize;
6454 CharUnits DirectAlign;
6456 DirectTy = llvm::PointerType::getUnqual(DirectTy);
6457 UnpaddedSize = DirectAlign = CharUnits::fromQuantity(8);
6459 if (AI.getCoerceToType())
6460 ArgTy = AI.getCoerceToType();
6461 InFPRs = ArgTy->isFloatTy() || ArgTy->isDoubleTy();
6462 IsVector = ArgTy->isVectorTy();
6463 UnpaddedSize = TyInfo.first;
6464 DirectAlign = TyInfo.second;
6466 CharUnits PaddedSize = CharUnits::fromQuantity(8);
6467 if (IsVector && UnpaddedSize > PaddedSize)
6468 PaddedSize = CharUnits::fromQuantity(16);
6469 assert((UnpaddedSize <= PaddedSize) && "Invalid argument size.");
6471 CharUnits Padding = (PaddedSize - UnpaddedSize);
6473 llvm::Type *IndexTy = CGF.Int64Ty;
6474 llvm::Value *PaddedSizeV =
6475 llvm::ConstantInt::get(IndexTy, PaddedSize.getQuantity());
6478 // Work out the address of a vector argument on the stack.
6479 // Vector arguments are always passed in the high bits of a
6480 // single (8 byte) or double (16 byte) stack slot.
6481 Address OverflowArgAreaPtr =
6482 CGF.Builder.CreateStructGEP(VAListAddr, 2, CharUnits::fromQuantity(16),
6483 "overflow_arg_area_ptr");
6484 Address OverflowArgArea =
6485 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6488 CGF.Builder.CreateElementBitCast(OverflowArgArea, DirectTy, "mem_addr");
6490 // Update overflow_arg_area_ptr pointer
6491 llvm::Value *NewOverflowArgArea =
6492 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6493 "overflow_arg_area");
6494 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6499 assert(PaddedSize.getQuantity() == 8);
6501 unsigned MaxRegs, RegCountField, RegSaveIndex;
6502 CharUnits RegPadding;
6504 MaxRegs = 4; // Maximum of 4 FPR arguments
6505 RegCountField = 1; // __fpr
6506 RegSaveIndex = 16; // save offset for f0
6507 RegPadding = CharUnits(); // floats are passed in the high bits of an FPR
6509 MaxRegs = 5; // Maximum of 5 GPR arguments
6510 RegCountField = 0; // __gpr
6511 RegSaveIndex = 2; // save offset for r2
6512 RegPadding = Padding; // values are passed in the low bits of a GPR
6515 Address RegCountPtr = CGF.Builder.CreateStructGEP(
6516 VAListAddr, RegCountField, RegCountField * CharUnits::fromQuantity(8),
6518 llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
6519 llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
6520 llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
6523 llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
6524 llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
6525 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
6526 CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
6528 // Emit code to load the value if it was passed in registers.
6529 CGF.EmitBlock(InRegBlock);
6531 // Work out the address of an argument register.
6532 llvm::Value *ScaledRegCount =
6533 CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
6534 llvm::Value *RegBase =
6535 llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize.getQuantity()
6536 + RegPadding.getQuantity());
6537 llvm::Value *RegOffset =
6538 CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
6539 Address RegSaveAreaPtr =
6540 CGF.Builder.CreateStructGEP(VAListAddr, 3, CharUnits::fromQuantity(24),
6541 "reg_save_area_ptr");
6542 llvm::Value *RegSaveArea =
6543 CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
6544 Address RawRegAddr(CGF.Builder.CreateGEP(RegSaveArea, RegOffset,
6548 CGF.Builder.CreateElementBitCast(RawRegAddr, DirectTy, "reg_addr");
6550 // Update the register count
6551 llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
6552 llvm::Value *NewRegCount =
6553 CGF.Builder.CreateAdd(RegCount, One, "reg_count");
6554 CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
6555 CGF.EmitBranch(ContBlock);
6557 // Emit code to load the value if it was passed in memory.
6558 CGF.EmitBlock(InMemBlock);
6560 // Work out the address of a stack argument.
6561 Address OverflowArgAreaPtr = CGF.Builder.CreateStructGEP(
6562 VAListAddr, 2, CharUnits::fromQuantity(16), "overflow_arg_area_ptr");
6563 Address OverflowArgArea =
6564 Address(CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area"),
6566 Address RawMemAddr =
6567 CGF.Builder.CreateConstByteGEP(OverflowArgArea, Padding, "raw_mem_addr");
6569 CGF.Builder.CreateElementBitCast(RawMemAddr, DirectTy, "mem_addr");
6571 // Update overflow_arg_area_ptr pointer
6572 llvm::Value *NewOverflowArgArea =
6573 CGF.Builder.CreateGEP(OverflowArgArea.getPointer(), PaddedSizeV,
6574 "overflow_arg_area");
6575 CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
6576 CGF.EmitBranch(ContBlock);
6578 // Return the appropriate result.
6579 CGF.EmitBlock(ContBlock);
6580 Address ResAddr = emitMergePHI(CGF, RegAddr, InRegBlock,
6581 MemAddr, InMemBlock, "va_arg.addr");
6584 ResAddr = Address(CGF.Builder.CreateLoad(ResAddr, "indirect_arg"),
6590 ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
6591 if (RetTy->isVoidType())
6592 return ABIArgInfo::getIgnore();
6593 if (isVectorArgumentType(RetTy))
6594 return ABIArgInfo::getDirect();
6595 if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
6596 return getNaturalAlignIndirect(RetTy);
6597 return (isPromotableIntegerType(RetTy) ? ABIArgInfo::getExtend(RetTy)
6598 : ABIArgInfo::getDirect());
6601 ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
6602 // Handle the generic C++ ABI.
6603 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
6604 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6606 // Integers and enums are extended to full register width.
6607 if (isPromotableIntegerType(Ty))
6608 return ABIArgInfo::getExtend(Ty);
6610 // Handle vector types and vector-like structure types. Note that
6611 // as opposed to float-like structure types, we do not allow any
6612 // padding for vector-like structures, so verify the sizes match.
6613 uint64_t Size = getContext().getTypeSize(Ty);
6614 QualType SingleElementTy = GetSingleElementType(Ty);
6615 if (isVectorArgumentType(SingleElementTy) &&
6616 getContext().getTypeSize(SingleElementTy) == Size)
6617 return ABIArgInfo::getDirect(CGT.ConvertType(SingleElementTy));
6619 // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
6620 if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
6621 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6623 // Handle small structures.
6624 if (const RecordType *RT = Ty->getAs<RecordType>()) {
6625 // Structures with flexible arrays have variable length, so really
6626 // fail the size test above.
6627 const RecordDecl *RD = RT->getDecl();
6628 if (RD->hasFlexibleArrayMember())
6629 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6631 // The structure is passed as an unextended integer, a float, or a double.
6633 if (isFPArgumentType(SingleElementTy)) {
6634 assert(Size == 32 || Size == 64);
6636 PassTy = llvm::Type::getFloatTy(getVMContext());
6638 PassTy = llvm::Type::getDoubleTy(getVMContext());
6640 PassTy = llvm::IntegerType::get(getVMContext(), Size);
6641 return ABIArgInfo::getDirect(PassTy);
6644 // Non-structure compounds are passed indirectly.
6645 if (isCompoundType(Ty))
6646 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
6648 return ABIArgInfo::getDirect(nullptr);
6651 //===----------------------------------------------------------------------===//
6652 // MSP430 ABI Implementation
6653 //===----------------------------------------------------------------------===//
6657 class MSP430TargetCodeGenInfo : public TargetCodeGenInfo {
6659 MSP430TargetCodeGenInfo(CodeGenTypes &CGT)
6660 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
6661 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6662 CodeGen::CodeGenModule &M) const override;
6667 void MSP430TargetCodeGenInfo::setTargetAttributes(
6668 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
6669 if (GV->isDeclaration())
6671 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D)) {
6672 if (const MSP430InterruptAttr *attr = FD->getAttr<MSP430InterruptAttr>()) {
6673 // Handle 'interrupt' attribute:
6674 llvm::Function *F = cast<llvm::Function>(GV);
6676 // Step 1: Set ISR calling convention.
6677 F->setCallingConv(llvm::CallingConv::MSP430_INTR);
6679 // Step 2: Add attributes goodness.
6680 F->addFnAttr(llvm::Attribute::NoInline);
6682 // Step 3: Emit ISR vector alias.
6683 unsigned Num = attr->getNumber() / 2;
6684 llvm::GlobalAlias::create(llvm::Function::ExternalLinkage,
6685 "__isr_" + Twine(Num), F);
6690 //===----------------------------------------------------------------------===//
6691 // MIPS ABI Implementation. This works for both little-endian and
6692 // big-endian variants.
6693 //===----------------------------------------------------------------------===//
6696 class MipsABIInfo : public ABIInfo {
6698 unsigned MinABIStackAlignInBytes, StackAlignInBytes;
6699 void CoerceToIntArgs(uint64_t TySize,
6700 SmallVectorImpl<llvm::Type *> &ArgList) const;
6701 llvm::Type* HandleAggregates(QualType Ty, uint64_t TySize) const;
6702 llvm::Type* returnAggregateInRegs(QualType RetTy, uint64_t Size) const;
6703 llvm::Type* getPaddingType(uint64_t Align, uint64_t Offset) const;
6705 MipsABIInfo(CodeGenTypes &CGT, bool _IsO32) :
6706 ABIInfo(CGT), IsO32(_IsO32), MinABIStackAlignInBytes(IsO32 ? 4 : 8),
6707 StackAlignInBytes(IsO32 ? 8 : 16) {}
6709 ABIArgInfo classifyReturnType(QualType RetTy) const;
6710 ABIArgInfo classifyArgumentType(QualType RetTy, uint64_t &Offset) const;
6711 void computeInfo(CGFunctionInfo &FI) const override;
6712 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
6713 QualType Ty) const override;
6714 ABIArgInfo extendType(QualType Ty) const;
6717 class MIPSTargetCodeGenInfo : public TargetCodeGenInfo {
6718 unsigned SizeOfUnwindException;
6720 MIPSTargetCodeGenInfo(CodeGenTypes &CGT, bool IsO32)
6721 : TargetCodeGenInfo(new MipsABIInfo(CGT, IsO32)),
6722 SizeOfUnwindException(IsO32 ? 24 : 32) {}
6724 int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const override {
6728 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
6729 CodeGen::CodeGenModule &CGM) const override {
6730 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
6732 llvm::Function *Fn = cast<llvm::Function>(GV);
6734 if (FD->hasAttr<MipsLongCallAttr>())
6735 Fn->addFnAttr("long-call");
6736 else if (FD->hasAttr<MipsShortCallAttr>())
6737 Fn->addFnAttr("short-call");
6739 // Other attributes do not have a meaning for declarations.
6740 if (GV->isDeclaration())
6743 if (FD->hasAttr<Mips16Attr>()) {
6744 Fn->addFnAttr("mips16");
6746 else if (FD->hasAttr<NoMips16Attr>()) {
6747 Fn->addFnAttr("nomips16");
6750 if (FD->hasAttr<MicroMipsAttr>())
6751 Fn->addFnAttr("micromips");
6752 else if (FD->hasAttr<NoMicroMipsAttr>())
6753 Fn->addFnAttr("nomicromips");
6755 const MipsInterruptAttr *Attr = FD->getAttr<MipsInterruptAttr>();
6760 switch (Attr->getInterrupt()) {
6761 case MipsInterruptAttr::eic: Kind = "eic"; break;
6762 case MipsInterruptAttr::sw0: Kind = "sw0"; break;
6763 case MipsInterruptAttr::sw1: Kind = "sw1"; break;
6764 case MipsInterruptAttr::hw0: Kind = "hw0"; break;
6765 case MipsInterruptAttr::hw1: Kind = "hw1"; break;
6766 case MipsInterruptAttr::hw2: Kind = "hw2"; break;
6767 case MipsInterruptAttr::hw3: Kind = "hw3"; break;
6768 case MipsInterruptAttr::hw4: Kind = "hw4"; break;
6769 case MipsInterruptAttr::hw5: Kind = "hw5"; break;
6772 Fn->addFnAttr("interrupt", Kind);
6776 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
6777 llvm::Value *Address) const override;
6779 unsigned getSizeOfUnwindException() const override {
6780 return SizeOfUnwindException;
6785 void MipsABIInfo::CoerceToIntArgs(
6786 uint64_t TySize, SmallVectorImpl<llvm::Type *> &ArgList) const {
6787 llvm::IntegerType *IntTy =
6788 llvm::IntegerType::get(getVMContext(), MinABIStackAlignInBytes * 8);
6790 // Add (TySize / MinABIStackAlignInBytes) args of IntTy.
6791 for (unsigned N = TySize / (MinABIStackAlignInBytes * 8); N; --N)
6792 ArgList.push_back(IntTy);
6794 // If necessary, add one more integer type to ArgList.
6795 unsigned R = TySize % (MinABIStackAlignInBytes * 8);
6798 ArgList.push_back(llvm::IntegerType::get(getVMContext(), R));
6801 // In N32/64, an aligned double precision floating point field is passed in
6803 llvm::Type* MipsABIInfo::HandleAggregates(QualType Ty, uint64_t TySize) const {
6804 SmallVector<llvm::Type*, 8> ArgList, IntArgList;
6807 CoerceToIntArgs(TySize, ArgList);
6808 return llvm::StructType::get(getVMContext(), ArgList);
6811 if (Ty->isComplexType())
6812 return CGT.ConvertType(Ty);
6814 const RecordType *RT = Ty->getAs<RecordType>();
6816 // Unions/vectors are passed in integer registers.
6817 if (!RT || !RT->isStructureOrClassType()) {
6818 CoerceToIntArgs(TySize, ArgList);
6819 return llvm::StructType::get(getVMContext(), ArgList);
6822 const RecordDecl *RD = RT->getDecl();
6823 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6824 assert(!(TySize % 8) && "Size of structure must be multiple of 8.");
6826 uint64_t LastOffset = 0;
6828 llvm::IntegerType *I64 = llvm::IntegerType::get(getVMContext(), 64);
6830 // Iterate over fields in the struct/class and check if there are any aligned
6832 for (RecordDecl::field_iterator i = RD->field_begin(), e = RD->field_end();
6833 i != e; ++i, ++idx) {
6834 const QualType Ty = i->getType();
6835 const BuiltinType *BT = Ty->getAs<BuiltinType>();
6837 if (!BT || BT->getKind() != BuiltinType::Double)
6840 uint64_t Offset = Layout.getFieldOffset(idx);
6841 if (Offset % 64) // Ignore doubles that are not aligned.
6844 // Add ((Offset - LastOffset) / 64) args of type i64.
6845 for (unsigned j = (Offset - LastOffset) / 64; j > 0; --j)
6846 ArgList.push_back(I64);
6849 ArgList.push_back(llvm::Type::getDoubleTy(getVMContext()));
6850 LastOffset = Offset + 64;
6853 CoerceToIntArgs(TySize - LastOffset, IntArgList);
6854 ArgList.append(IntArgList.begin(), IntArgList.end());
6856 return llvm::StructType::get(getVMContext(), ArgList);
6859 llvm::Type *MipsABIInfo::getPaddingType(uint64_t OrigOffset,
6860 uint64_t Offset) const {
6861 if (OrigOffset + MinABIStackAlignInBytes > Offset)
6864 return llvm::IntegerType::get(getVMContext(), (Offset - OrigOffset) * 8);
6868 MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
6869 Ty = useFirstFieldIfTransparentUnion(Ty);
6871 uint64_t OrigOffset = Offset;
6872 uint64_t TySize = getContext().getTypeSize(Ty);
6873 uint64_t Align = getContext().getTypeAlign(Ty) / 8;
6875 Align = std::min(std::max(Align, (uint64_t)MinABIStackAlignInBytes),
6876 (uint64_t)StackAlignInBytes);
6877 unsigned CurrOffset = llvm::alignTo(Offset, Align);
6878 Offset = CurrOffset + llvm::alignTo(TySize, Align * 8) / 8;
6880 if (isAggregateTypeForABI(Ty) || Ty->isVectorType()) {
6881 // Ignore empty aggregates.
6883 return ABIArgInfo::getIgnore();
6885 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
6886 Offset = OrigOffset + MinABIStackAlignInBytes;
6887 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
6890 // If we have reached here, aggregates are passed directly by coercing to
6891 // another structure type. Padding is inserted if the offset of the
6892 // aggregate is unaligned.
6893 ABIArgInfo ArgInfo =
6894 ABIArgInfo::getDirect(HandleAggregates(Ty, TySize), 0,
6895 getPaddingType(OrigOffset, CurrOffset));
6896 ArgInfo.setInReg(true);
6900 // Treat an enum type as its underlying type.
6901 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
6902 Ty = EnumTy->getDecl()->getIntegerType();
6904 // All integral types are promoted to the GPR width.
6905 if (Ty->isIntegralOrEnumerationType())
6906 return extendType(Ty);
6908 return ABIArgInfo::getDirect(
6909 nullptr, 0, IsO32 ? nullptr : getPaddingType(OrigOffset, CurrOffset));
6913 MipsABIInfo::returnAggregateInRegs(QualType RetTy, uint64_t Size) const {
6914 const RecordType *RT = RetTy->getAs<RecordType>();
6915 SmallVector<llvm::Type*, 8> RTList;
6917 if (RT && RT->isStructureOrClassType()) {
6918 const RecordDecl *RD = RT->getDecl();
6919 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
6920 unsigned FieldCnt = Layout.getFieldCount();
6922 // N32/64 returns struct/classes in floating point registers if the
6923 // following conditions are met:
6924 // 1. The size of the struct/class is no larger than 128-bit.
6925 // 2. The struct/class has one or two fields all of which are floating
6927 // 3. The offset of the first field is zero (this follows what gcc does).
6929 // Any other composite results are returned in integer registers.
6931 if (FieldCnt && (FieldCnt <= 2) && !Layout.getFieldOffset(0)) {
6932 RecordDecl::field_iterator b = RD->field_begin(), e = RD->field_end();
6933 for (; b != e; ++b) {
6934 const BuiltinType *BT = b->getType()->getAs<BuiltinType>();
6936 if (!BT || !BT->isFloatingPoint())
6939 RTList.push_back(CGT.ConvertType(b->getType()));
6943 return llvm::StructType::get(getVMContext(), RTList,
6944 RD->hasAttr<PackedAttr>());
6950 CoerceToIntArgs(Size, RTList);
6951 return llvm::StructType::get(getVMContext(), RTList);
6954 ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
6955 uint64_t Size = getContext().getTypeSize(RetTy);
6957 if (RetTy->isVoidType())
6958 return ABIArgInfo::getIgnore();
6960 // O32 doesn't treat zero-sized structs differently from other structs.
6961 // However, N32/N64 ignores zero sized return values.
6962 if (!IsO32 && Size == 0)
6963 return ABIArgInfo::getIgnore();
6965 if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
6967 if (RetTy->isAnyComplexType())
6968 return ABIArgInfo::getDirect();
6970 // O32 returns integer vectors in registers and N32/N64 returns all small
6971 // aggregates in registers.
6973 (RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())) {
6974 ABIArgInfo ArgInfo =
6975 ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
6976 ArgInfo.setInReg(true);
6981 return getNaturalAlignIndirect(RetTy);
6984 // Treat an enum type as its underlying type.
6985 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
6986 RetTy = EnumTy->getDecl()->getIntegerType();
6988 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
6989 : ABIArgInfo::getDirect());
6992 void MipsABIInfo::computeInfo(CGFunctionInfo &FI) const {
6993 ABIArgInfo &RetInfo = FI.getReturnInfo();
6994 if (!getCXXABI().classifyReturnType(FI))
6995 RetInfo = classifyReturnType(FI.getReturnType());
6997 // Check if a pointer to an aggregate is passed as a hidden argument.
6998 uint64_t Offset = RetInfo.isIndirect() ? MinABIStackAlignInBytes : 0;
7000 for (auto &I : FI.arguments())
7001 I.info = classifyArgumentType(I.type, Offset);
7004 Address MipsABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7005 QualType OrigTy) const {
7006 QualType Ty = OrigTy;
7008 // Integer arguments are promoted to 32-bit on O32 and 64-bit on N32/N64.
7009 // Pointers are also promoted in the same way but this only matters for N32.
7010 unsigned SlotSizeInBits = IsO32 ? 32 : 64;
7011 unsigned PtrWidth = getTarget().getPointerWidth(0);
7012 bool DidPromote = false;
7013 if ((Ty->isIntegerType() &&
7014 getContext().getIntWidth(Ty) < SlotSizeInBits) ||
7015 (Ty->isPointerType() && PtrWidth < SlotSizeInBits)) {
7017 Ty = getContext().getIntTypeForBitwidth(SlotSizeInBits,
7018 Ty->isSignedIntegerType());
7021 auto TyInfo = getContext().getTypeInfoInChars(Ty);
7023 // The alignment of things in the argument area is never larger than
7024 // StackAlignInBytes.
7026 std::min(TyInfo.second, CharUnits::fromQuantity(StackAlignInBytes));
7028 // MinABIStackAlignInBytes is the size of argument slots on the stack.
7029 CharUnits ArgSlotSize = CharUnits::fromQuantity(MinABIStackAlignInBytes);
7031 Address Addr = emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7032 TyInfo, ArgSlotSize, /*AllowHigherAlign*/ true);
7035 // If there was a promotion, "unpromote" into a temporary.
7036 // TODO: can we just use a pointer into a subset of the original slot?
7038 Address Temp = CGF.CreateMemTemp(OrigTy, "vaarg.promotion-temp");
7039 llvm::Value *Promoted = CGF.Builder.CreateLoad(Addr);
7041 // Truncate down to the right width.
7042 llvm::Type *IntTy = (OrigTy->isIntegerType() ? Temp.getElementType()
7044 llvm::Value *V = CGF.Builder.CreateTrunc(Promoted, IntTy);
7045 if (OrigTy->isPointerType())
7046 V = CGF.Builder.CreateIntToPtr(V, Temp.getElementType());
7048 CGF.Builder.CreateStore(V, Temp);
7055 ABIArgInfo MipsABIInfo::extendType(QualType Ty) const {
7056 int TySize = getContext().getTypeSize(Ty);
7058 // MIPS64 ABI requires unsigned 32 bit integers to be sign extended.
7059 if (Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
7060 return ABIArgInfo::getSignExtend(Ty);
7062 return ABIArgInfo::getExtend(Ty);
7066 MIPSTargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
7067 llvm::Value *Address) const {
7068 // This information comes from gcc's implementation, which seems to
7069 // as canonical as it gets.
7071 // Everything on MIPS is 4 bytes. Double-precision FP registers
7072 // are aliased to pairs of single-precision FP registers.
7073 llvm::Value *Four8 = llvm::ConstantInt::get(CGF.Int8Ty, 4);
7075 // 0-31 are the general purpose registers, $0 - $31.
7076 // 32-63 are the floating-point registers, $f0 - $f31.
7077 // 64 and 65 are the multiply/divide registers, $hi and $lo.
7078 // 66 is the (notional, I think) register for signal-handler return.
7079 AssignToArrayRange(CGF.Builder, Address, Four8, 0, 65);
7081 // 67-74 are the floating-point status registers, $fcc0 - $fcc7.
7082 // They are one bit wide and ignored here.
7084 // 80-111 are the coprocessor 0 registers, $c0r0 - $c0r31.
7085 // (coprocessor 1 is the FP unit)
7086 // 112-143 are the coprocessor 2 registers, $c2r0 - $c2r31.
7087 // 144-175 are the coprocessor 3 registers, $c3r0 - $c3r31.
7088 // 176-181 are the DSP accumulator registers.
7089 AssignToArrayRange(CGF.Builder, Address, Four8, 80, 181);
7093 //===----------------------------------------------------------------------===//
7094 // AVR ABI Implementation.
7095 //===----------------------------------------------------------------------===//
7098 class AVRTargetCodeGenInfo : public TargetCodeGenInfo {
7100 AVRTargetCodeGenInfo(CodeGenTypes &CGT)
7101 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) { }
7103 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7104 CodeGen::CodeGenModule &CGM) const override {
7105 if (GV->isDeclaration())
7107 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
7109 auto *Fn = cast<llvm::Function>(GV);
7111 if (FD->getAttr<AVRInterruptAttr>())
7112 Fn->addFnAttr("interrupt");
7114 if (FD->getAttr<AVRSignalAttr>())
7115 Fn->addFnAttr("signal");
7120 //===----------------------------------------------------------------------===//
7121 // TCE ABI Implementation (see http://tce.cs.tut.fi). Uses mostly the defaults.
7122 // Currently subclassed only to implement custom OpenCL C function attribute
7124 //===----------------------------------------------------------------------===//
7128 class TCETargetCodeGenInfo : public DefaultTargetCodeGenInfo {
7130 TCETargetCodeGenInfo(CodeGenTypes &CGT)
7131 : DefaultTargetCodeGenInfo(CGT) {}
7133 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7134 CodeGen::CodeGenModule &M) const override;
7137 void TCETargetCodeGenInfo::setTargetAttributes(
7138 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7139 if (GV->isDeclaration())
7141 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7144 llvm::Function *F = cast<llvm::Function>(GV);
7146 if (M.getLangOpts().OpenCL) {
7147 if (FD->hasAttr<OpenCLKernelAttr>()) {
7148 // OpenCL C Kernel functions are not subject to inlining
7149 F->addFnAttr(llvm::Attribute::NoInline);
7150 const ReqdWorkGroupSizeAttr *Attr = FD->getAttr<ReqdWorkGroupSizeAttr>();
7152 // Convert the reqd_work_group_size() attributes to metadata.
7153 llvm::LLVMContext &Context = F->getContext();
7154 llvm::NamedMDNode *OpenCLMetadata =
7155 M.getModule().getOrInsertNamedMetadata(
7156 "opencl.kernel_wg_size_info");
7158 SmallVector<llvm::Metadata *, 5> Operands;
7159 Operands.push_back(llvm::ConstantAsMetadata::get(F));
7162 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7163 M.Int32Ty, llvm::APInt(32, Attr->getXDim()))));
7165 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7166 M.Int32Ty, llvm::APInt(32, Attr->getYDim()))));
7168 llvm::ConstantAsMetadata::get(llvm::Constant::getIntegerValue(
7169 M.Int32Ty, llvm::APInt(32, Attr->getZDim()))));
7171 // Add a boolean constant operand for "required" (true) or "hint"
7172 // (false) for implementing the work_group_size_hint attr later.
7173 // Currently always true as the hint is not yet implemented.
7175 llvm::ConstantAsMetadata::get(llvm::ConstantInt::getTrue(Context)));
7176 OpenCLMetadata->addOperand(llvm::MDNode::get(Context, Operands));
7184 //===----------------------------------------------------------------------===//
7185 // Hexagon ABI Implementation
7186 //===----------------------------------------------------------------------===//
7190 class HexagonABIInfo : public ABIInfo {
7194 HexagonABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7198 ABIArgInfo classifyReturnType(QualType RetTy) const;
7199 ABIArgInfo classifyArgumentType(QualType RetTy) const;
7201 void computeInfo(CGFunctionInfo &FI) const override;
7203 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7204 QualType Ty) const override;
7207 class HexagonTargetCodeGenInfo : public TargetCodeGenInfo {
7209 HexagonTargetCodeGenInfo(CodeGenTypes &CGT)
7210 :TargetCodeGenInfo(new HexagonABIInfo(CGT)) {}
7212 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
7219 void HexagonABIInfo::computeInfo(CGFunctionInfo &FI) const {
7220 if (!getCXXABI().classifyReturnType(FI))
7221 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7222 for (auto &I : FI.arguments())
7223 I.info = classifyArgumentType(I.type);
7226 ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
7227 if (!isAggregateTypeForABI(Ty)) {
7228 // Treat an enum type as its underlying type.
7229 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
7230 Ty = EnumTy->getDecl()->getIntegerType();
7232 return (Ty->isPromotableIntegerType() ? ABIArgInfo::getExtend(Ty)
7233 : ABIArgInfo::getDirect());
7236 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
7237 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7239 // Ignore empty records.
7240 if (isEmptyRecord(getContext(), Ty, true))
7241 return ABIArgInfo::getIgnore();
7243 uint64_t Size = getContext().getTypeSize(Ty);
7245 return getNaturalAlignIndirect(Ty, /*ByVal=*/true);
7246 // Pass in the smallest viable integer type.
7248 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7250 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7252 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7254 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7257 ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
7258 if (RetTy->isVoidType())
7259 return ABIArgInfo::getIgnore();
7261 // Large vector types should be returned via memory.
7262 if (RetTy->isVectorType() && getContext().getTypeSize(RetTy) > 64)
7263 return getNaturalAlignIndirect(RetTy);
7265 if (!isAggregateTypeForABI(RetTy)) {
7266 // Treat an enum type as its underlying type.
7267 if (const EnumType *EnumTy = RetTy->getAs<EnumType>())
7268 RetTy = EnumTy->getDecl()->getIntegerType();
7270 return (RetTy->isPromotableIntegerType() ? ABIArgInfo::getExtend(RetTy)
7271 : ABIArgInfo::getDirect());
7274 if (isEmptyRecord(getContext(), RetTy, true))
7275 return ABIArgInfo::getIgnore();
7277 // Aggregates <= 8 bytes are returned in r0; other aggregates
7278 // are returned indirectly.
7279 uint64_t Size = getContext().getTypeSize(RetTy);
7281 // Return in the smallest viable integer type.
7283 return ABIArgInfo::getDirect(llvm::Type::getInt8Ty(getVMContext()));
7285 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7287 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7288 return ABIArgInfo::getDirect(llvm::Type::getInt64Ty(getVMContext()));
7291 return getNaturalAlignIndirect(RetTy, /*ByVal=*/true);
7294 Address HexagonABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7295 QualType Ty) const {
7296 // FIXME: Someone needs to audit that this handle alignment correctly.
7297 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, /*indirect*/ false,
7298 getContext().getTypeInfoInChars(Ty),
7299 CharUnits::fromQuantity(4),
7300 /*AllowHigherAlign*/ true);
7303 //===----------------------------------------------------------------------===//
7304 // Lanai ABI Implementation
7305 //===----------------------------------------------------------------------===//
7308 class LanaiABIInfo : public DefaultABIInfo {
7310 LanaiABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7312 bool shouldUseInReg(QualType Ty, CCState &State) const;
7314 void computeInfo(CGFunctionInfo &FI) const override {
7315 CCState State(FI.getCallingConvention());
7316 // Lanai uses 4 registers to pass arguments unless the function has the
7317 // regparm attribute set.
7318 if (FI.getHasRegParm()) {
7319 State.FreeRegs = FI.getRegParm();
7324 if (!getCXXABI().classifyReturnType(FI))
7325 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7326 for (auto &I : FI.arguments())
7327 I.info = classifyArgumentType(I.type, State);
7330 ABIArgInfo getIndirectResult(QualType Ty, bool ByVal, CCState &State) const;
7331 ABIArgInfo classifyArgumentType(QualType RetTy, CCState &State) const;
7333 } // end anonymous namespace
7335 bool LanaiABIInfo::shouldUseInReg(QualType Ty, CCState &State) const {
7336 unsigned Size = getContext().getTypeSize(Ty);
7337 unsigned SizeInRegs = llvm::alignTo(Size, 32U) / 32U;
7339 if (SizeInRegs == 0)
7342 if (SizeInRegs > State.FreeRegs) {
7347 State.FreeRegs -= SizeInRegs;
7352 ABIArgInfo LanaiABIInfo::getIndirectResult(QualType Ty, bool ByVal,
7353 CCState &State) const {
7355 if (State.FreeRegs) {
7356 --State.FreeRegs; // Non-byval indirects just use one pointer.
7357 return getNaturalAlignIndirectInReg(Ty);
7359 return getNaturalAlignIndirect(Ty, false);
7362 // Compute the byval alignment.
7363 const unsigned MinABIStackAlignInBytes = 4;
7364 unsigned TypeAlign = getContext().getTypeAlign(Ty) / 8;
7365 return ABIArgInfo::getIndirect(CharUnits::fromQuantity(4), /*ByVal=*/true,
7366 /*Realign=*/TypeAlign >
7367 MinABIStackAlignInBytes);
7370 ABIArgInfo LanaiABIInfo::classifyArgumentType(QualType Ty,
7371 CCState &State) const {
7372 // Check with the C++ ABI first.
7373 const RecordType *RT = Ty->getAs<RecordType>();
7375 CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, getCXXABI());
7376 if (RAA == CGCXXABI::RAA_Indirect) {
7377 return getIndirectResult(Ty, /*ByVal=*/false, State);
7378 } else if (RAA == CGCXXABI::RAA_DirectInMemory) {
7379 return getNaturalAlignIndirect(Ty, /*ByRef=*/true);
7383 if (isAggregateTypeForABI(Ty)) {
7384 // Structures with flexible arrays are always indirect.
7385 if (RT && RT->getDecl()->hasFlexibleArrayMember())
7386 return getIndirectResult(Ty, /*ByVal=*/true, State);
7388 // Ignore empty structs/unions.
7389 if (isEmptyRecord(getContext(), Ty, true))
7390 return ABIArgInfo::getIgnore();
7392 llvm::LLVMContext &LLVMContext = getVMContext();
7393 unsigned SizeInRegs = (getContext().getTypeSize(Ty) + 31) / 32;
7394 if (SizeInRegs <= State.FreeRegs) {
7395 llvm::IntegerType *Int32 = llvm::Type::getInt32Ty(LLVMContext);
7396 SmallVector<llvm::Type *, 3> Elements(SizeInRegs, Int32);
7397 llvm::Type *Result = llvm::StructType::get(LLVMContext, Elements);
7398 State.FreeRegs -= SizeInRegs;
7399 return ABIArgInfo::getDirectInReg(Result);
7403 return getIndirectResult(Ty, true, State);
7406 // Treat an enum type as its underlying type.
7407 if (const auto *EnumTy = Ty->getAs<EnumType>())
7408 Ty = EnumTy->getDecl()->getIntegerType();
7410 bool InReg = shouldUseInReg(Ty, State);
7411 if (Ty->isPromotableIntegerType()) {
7413 return ABIArgInfo::getDirectInReg();
7414 return ABIArgInfo::getExtend(Ty);
7417 return ABIArgInfo::getDirectInReg();
7418 return ABIArgInfo::getDirect();
7422 class LanaiTargetCodeGenInfo : public TargetCodeGenInfo {
7424 LanaiTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
7425 : TargetCodeGenInfo(new LanaiABIInfo(CGT)) {}
7429 //===----------------------------------------------------------------------===//
7430 // AMDGPU ABI Implementation
7431 //===----------------------------------------------------------------------===//
7435 class AMDGPUABIInfo final : public DefaultABIInfo {
7437 static const unsigned MaxNumRegsForArgsRet = 16;
7439 unsigned numRegsForType(QualType Ty) const;
7441 bool isHomogeneousAggregateBaseType(QualType Ty) const override;
7442 bool isHomogeneousAggregateSmallEnough(const Type *Base,
7443 uint64_t Members) const override;
7446 explicit AMDGPUABIInfo(CodeGen::CodeGenTypes &CGT) :
7447 DefaultABIInfo(CGT) {}
7449 ABIArgInfo classifyReturnType(QualType RetTy) const;
7450 ABIArgInfo classifyKernelArgumentType(QualType Ty) const;
7451 ABIArgInfo classifyArgumentType(QualType Ty, unsigned &NumRegsLeft) const;
7453 void computeInfo(CGFunctionInfo &FI) const override;
7456 bool AMDGPUABIInfo::isHomogeneousAggregateBaseType(QualType Ty) const {
7460 bool AMDGPUABIInfo::isHomogeneousAggregateSmallEnough(
7461 const Type *Base, uint64_t Members) const {
7462 uint32_t NumRegs = (getContext().getTypeSize(Base) + 31) / 32;
7464 // Homogeneous Aggregates may occupy at most 16 registers.
7465 return Members * NumRegs <= MaxNumRegsForArgsRet;
7468 /// Estimate number of registers the type will use when passed in registers.
7469 unsigned AMDGPUABIInfo::numRegsForType(QualType Ty) const {
7470 unsigned NumRegs = 0;
7472 if (const VectorType *VT = Ty->getAs<VectorType>()) {
7473 // Compute from the number of elements. The reported size is based on the
7474 // in-memory size, which includes the padding 4th element for 3-vectors.
7475 QualType EltTy = VT->getElementType();
7476 unsigned EltSize = getContext().getTypeSize(EltTy);
7478 // 16-bit element vectors should be passed as packed.
7480 return (VT->getNumElements() + 1) / 2;
7482 unsigned EltNumRegs = (EltSize + 31) / 32;
7483 return EltNumRegs * VT->getNumElements();
7486 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7487 const RecordDecl *RD = RT->getDecl();
7488 assert(!RD->hasFlexibleArrayMember());
7490 for (const FieldDecl *Field : RD->fields()) {
7491 QualType FieldTy = Field->getType();
7492 NumRegs += numRegsForType(FieldTy);
7498 return (getContext().getTypeSize(Ty) + 31) / 32;
7501 void AMDGPUABIInfo::computeInfo(CGFunctionInfo &FI) const {
7502 llvm::CallingConv::ID CC = FI.getCallingConvention();
7504 if (!getCXXABI().classifyReturnType(FI))
7505 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7507 unsigned NumRegsLeft = MaxNumRegsForArgsRet;
7508 for (auto &Arg : FI.arguments()) {
7509 if (CC == llvm::CallingConv::AMDGPU_KERNEL) {
7510 Arg.info = classifyKernelArgumentType(Arg.type);
7512 Arg.info = classifyArgumentType(Arg.type, NumRegsLeft);
7517 ABIArgInfo AMDGPUABIInfo::classifyReturnType(QualType RetTy) const {
7518 if (isAggregateTypeForABI(RetTy)) {
7519 // Records with non-trivial destructors/copy-constructors should not be
7520 // returned by value.
7521 if (!getRecordArgABI(RetTy, getCXXABI())) {
7522 // Ignore empty structs/unions.
7523 if (isEmptyRecord(getContext(), RetTy, true))
7524 return ABIArgInfo::getIgnore();
7526 // Lower single-element structs to just return a regular value.
7527 if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
7528 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7530 if (const RecordType *RT = RetTy->getAs<RecordType>()) {
7531 const RecordDecl *RD = RT->getDecl();
7532 if (RD->hasFlexibleArrayMember())
7533 return DefaultABIInfo::classifyReturnType(RetTy);
7536 // Pack aggregates <= 4 bytes into single VGPR or pair.
7537 uint64_t Size = getContext().getTypeSize(RetTy);
7539 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7542 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7545 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7546 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7549 if (numRegsForType(RetTy) <= MaxNumRegsForArgsRet)
7550 return ABIArgInfo::getDirect();
7554 // Otherwise just do the default thing.
7555 return DefaultABIInfo::classifyReturnType(RetTy);
7558 /// For kernels all parameters are really passed in a special buffer. It doesn't
7559 /// make sense to pass anything byval, so everything must be direct.
7560 ABIArgInfo AMDGPUABIInfo::classifyKernelArgumentType(QualType Ty) const {
7561 Ty = useFirstFieldIfTransparentUnion(Ty);
7563 // TODO: Can we omit empty structs?
7565 // Coerce single element structs to its element.
7566 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7567 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7569 // If we set CanBeFlattened to true, CodeGen will expand the struct to its
7570 // individual elements, which confuses the Clover OpenCL backend; therefore we
7571 // have to set it to false here. Other args of getDirect() are just defaults.
7572 return ABIArgInfo::getDirect(nullptr, 0, nullptr, false);
7575 ABIArgInfo AMDGPUABIInfo::classifyArgumentType(QualType Ty,
7576 unsigned &NumRegsLeft) const {
7577 assert(NumRegsLeft <= MaxNumRegsForArgsRet && "register estimate underflow");
7579 Ty = useFirstFieldIfTransparentUnion(Ty);
7581 if (isAggregateTypeForABI(Ty)) {
7582 // Records with non-trivial destructors/copy-constructors should not be
7584 if (auto RAA = getRecordArgABI(Ty, getCXXABI()))
7585 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
7587 // Ignore empty structs/unions.
7588 if (isEmptyRecord(getContext(), Ty, true))
7589 return ABIArgInfo::getIgnore();
7591 // Lower single-element structs to just pass a regular value. TODO: We
7592 // could do reasonable-size multiple-element structs too, using getExpand(),
7593 // though watch out for things like bitfields.
7594 if (const Type *SeltTy = isSingleElementStruct(Ty, getContext()))
7595 return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
7597 if (const RecordType *RT = Ty->getAs<RecordType>()) {
7598 const RecordDecl *RD = RT->getDecl();
7599 if (RD->hasFlexibleArrayMember())
7600 return DefaultABIInfo::classifyArgumentType(Ty);
7603 // Pack aggregates <= 8 bytes into single VGPR or pair.
7604 uint64_t Size = getContext().getTypeSize(Ty);
7606 unsigned NumRegs = (Size + 31) / 32;
7607 NumRegsLeft -= std::min(NumRegsLeft, NumRegs);
7610 return ABIArgInfo::getDirect(llvm::Type::getInt16Ty(getVMContext()));
7613 return ABIArgInfo::getDirect(llvm::Type::getInt32Ty(getVMContext()));
7615 // XXX: Should this be i64 instead, and should the limit increase?
7616 llvm::Type *I32Ty = llvm::Type::getInt32Ty(getVMContext());
7617 return ABIArgInfo::getDirect(llvm::ArrayType::get(I32Ty, 2));
7620 if (NumRegsLeft > 0) {
7621 unsigned NumRegs = numRegsForType(Ty);
7622 if (NumRegsLeft >= NumRegs) {
7623 NumRegsLeft -= NumRegs;
7624 return ABIArgInfo::getDirect();
7629 // Otherwise just do the default thing.
7630 ABIArgInfo ArgInfo = DefaultABIInfo::classifyArgumentType(Ty);
7631 if (!ArgInfo.isIndirect()) {
7632 unsigned NumRegs = numRegsForType(Ty);
7633 NumRegsLeft -= std::min(NumRegs, NumRegsLeft);
7639 class AMDGPUTargetCodeGenInfo : public TargetCodeGenInfo {
7641 AMDGPUTargetCodeGenInfo(CodeGenTypes &CGT)
7642 : TargetCodeGenInfo(new AMDGPUABIInfo(CGT)) {}
7643 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
7644 CodeGen::CodeGenModule &M) const override;
7645 unsigned getOpenCLKernelCallingConv() const override;
7647 llvm::Constant *getNullPointer(const CodeGen::CodeGenModule &CGM,
7648 llvm::PointerType *T, QualType QT) const override;
7650 LangAS getASTAllocaAddressSpace() const override {
7651 return getLangASFromTargetAS(
7652 getABIInfo().getDataLayout().getAllocaAddrSpace());
7654 LangAS getGlobalVarAddressSpace(CodeGenModule &CGM,
7655 const VarDecl *D) const override;
7656 llvm::SyncScope::ID getLLVMSyncScopeID(SyncScope S,
7657 llvm::LLVMContext &C) const override;
7659 createEnqueuedBlockKernel(CodeGenFunction &CGF,
7660 llvm::Function *BlockInvokeFunc,
7661 llvm::Value *BlockLiteral) const override;
7662 bool shouldEmitStaticExternCAliases() const override;
7663 void setCUDAKernelCallingConvention(const FunctionType *&FT) const override;
7667 void AMDGPUTargetCodeGenInfo::setTargetAttributes(
7668 const Decl *D, llvm::GlobalValue *GV, CodeGen::CodeGenModule &M) const {
7669 if (GV->isDeclaration())
7671 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(D);
7675 llvm::Function *F = cast<llvm::Function>(GV);
7677 const auto *ReqdWGS = M.getLangOpts().OpenCL ?
7678 FD->getAttr<ReqdWorkGroupSizeAttr>() : nullptr;
7680 if (M.getLangOpts().OpenCL && FD->hasAttr<OpenCLKernelAttr>() &&
7681 (M.getTriple().getOS() == llvm::Triple::AMDHSA))
7682 F->addFnAttr("amdgpu-implicitarg-num-bytes", "48");
7684 const auto *FlatWGS = FD->getAttr<AMDGPUFlatWorkGroupSizeAttr>();
7685 if (ReqdWGS || FlatWGS) {
7686 unsigned Min = FlatWGS ? FlatWGS->getMin() : 0;
7687 unsigned Max = FlatWGS ? FlatWGS->getMax() : 0;
7688 if (ReqdWGS && Min == 0 && Max == 0)
7689 Min = Max = ReqdWGS->getXDim() * ReqdWGS->getYDim() * ReqdWGS->getZDim();
7692 assert(Min <= Max && "Min must be less than or equal Max");
7694 std::string AttrVal = llvm::utostr(Min) + "," + llvm::utostr(Max);
7695 F->addFnAttr("amdgpu-flat-work-group-size", AttrVal);
7697 assert(Max == 0 && "Max must be zero");
7700 if (const auto *Attr = FD->getAttr<AMDGPUWavesPerEUAttr>()) {
7701 unsigned Min = Attr->getMin();
7702 unsigned Max = Attr->getMax();
7705 assert((Max == 0 || Min <= Max) && "Min must be less than or equal Max");
7707 std::string AttrVal = llvm::utostr(Min);
7709 AttrVal = AttrVal + "," + llvm::utostr(Max);
7710 F->addFnAttr("amdgpu-waves-per-eu", AttrVal);
7712 assert(Max == 0 && "Max must be zero");
7715 if (const auto *Attr = FD->getAttr<AMDGPUNumSGPRAttr>()) {
7716 unsigned NumSGPR = Attr->getNumSGPR();
7719 F->addFnAttr("amdgpu-num-sgpr", llvm::utostr(NumSGPR));
7722 if (const auto *Attr = FD->getAttr<AMDGPUNumVGPRAttr>()) {
7723 uint32_t NumVGPR = Attr->getNumVGPR();
7726 F->addFnAttr("amdgpu-num-vgpr", llvm::utostr(NumVGPR));
7730 unsigned AMDGPUTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
7731 return llvm::CallingConv::AMDGPU_KERNEL;
7734 // Currently LLVM assumes null pointers always have value 0,
7735 // which results in incorrectly transformed IR. Therefore, instead of
7736 // emitting null pointers in private and local address spaces, a null
7737 // pointer in generic address space is emitted which is casted to a
7738 // pointer in local or private address space.
7739 llvm::Constant *AMDGPUTargetCodeGenInfo::getNullPointer(
7740 const CodeGen::CodeGenModule &CGM, llvm::PointerType *PT,
7741 QualType QT) const {
7742 if (CGM.getContext().getTargetNullPointerValue(QT) == 0)
7743 return llvm::ConstantPointerNull::get(PT);
7745 auto &Ctx = CGM.getContext();
7746 auto NPT = llvm::PointerType::get(PT->getElementType(),
7747 Ctx.getTargetAddressSpace(LangAS::opencl_generic));
7748 return llvm::ConstantExpr::getAddrSpaceCast(
7749 llvm::ConstantPointerNull::get(NPT), PT);
7753 AMDGPUTargetCodeGenInfo::getGlobalVarAddressSpace(CodeGenModule &CGM,
7754 const VarDecl *D) const {
7755 assert(!CGM.getLangOpts().OpenCL &&
7756 !(CGM.getLangOpts().CUDA && CGM.getLangOpts().CUDAIsDevice) &&
7757 "Address space agnostic languages only");
7758 LangAS DefaultGlobalAS = getLangASFromTargetAS(
7759 CGM.getContext().getTargetAddressSpace(LangAS::opencl_global));
7761 return DefaultGlobalAS;
7763 LangAS AddrSpace = D->getType().getAddressSpace();
7764 assert(AddrSpace == LangAS::Default || isTargetAddressSpace(AddrSpace));
7765 if (AddrSpace != LangAS::Default)
7768 if (CGM.isTypeConstant(D->getType(), false)) {
7769 if (auto ConstAS = CGM.getTarget().getConstantAddressSpace())
7770 return ConstAS.getValue();
7772 return DefaultGlobalAS;
7776 AMDGPUTargetCodeGenInfo::getLLVMSyncScopeID(SyncScope S,
7777 llvm::LLVMContext &C) const {
7780 case SyncScope::OpenCLWorkGroup:
7783 case SyncScope::OpenCLDevice:
7786 case SyncScope::OpenCLAllSVMDevices:
7789 case SyncScope::OpenCLSubGroup:
7792 return C.getOrInsertSyncScopeID(Name);
7795 bool AMDGPUTargetCodeGenInfo::shouldEmitStaticExternCAliases() const {
7799 void AMDGPUTargetCodeGenInfo::setCUDAKernelCallingConvention(
7800 const FunctionType *&FT) const {
7801 FT = getABIInfo().getContext().adjustFunctionType(
7802 FT, FT->getExtInfo().withCallingConv(CC_OpenCLKernel));
7805 //===----------------------------------------------------------------------===//
7806 // SPARC v8 ABI Implementation.
7807 // Based on the SPARC Compliance Definition version 2.4.1.
7809 // Ensures that complex values are passed in registers.
7812 class SparcV8ABIInfo : public DefaultABIInfo {
7814 SparcV8ABIInfo(CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
7817 ABIArgInfo classifyReturnType(QualType RetTy) const;
7818 void computeInfo(CGFunctionInfo &FI) const override;
7820 } // end anonymous namespace
7824 SparcV8ABIInfo::classifyReturnType(QualType Ty) const {
7825 if (Ty->isAnyComplexType()) {
7826 return ABIArgInfo::getDirect();
7829 return DefaultABIInfo::classifyReturnType(Ty);
7833 void SparcV8ABIInfo::computeInfo(CGFunctionInfo &FI) const {
7835 FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
7836 for (auto &Arg : FI.arguments())
7837 Arg.info = classifyArgumentType(Arg.type);
7841 class SparcV8TargetCodeGenInfo : public TargetCodeGenInfo {
7843 SparcV8TargetCodeGenInfo(CodeGenTypes &CGT)
7844 : TargetCodeGenInfo(new SparcV8ABIInfo(CGT)) {}
7846 } // end anonymous namespace
7848 //===----------------------------------------------------------------------===//
7849 // SPARC v9 ABI Implementation.
7850 // Based on the SPARC Compliance Definition version 2.4.1.
7852 // Function arguments a mapped to a nominal "parameter array" and promoted to
7853 // registers depending on their type. Each argument occupies 8 or 16 bytes in
7854 // the array, structs larger than 16 bytes are passed indirectly.
7856 // One case requires special care:
7863 // When a struct mixed is passed by value, it only occupies 8 bytes in the
7864 // parameter array, but the int is passed in an integer register, and the float
7865 // is passed in a floating point register. This is represented as two arguments
7866 // with the LLVM IR inreg attribute:
7868 // declare void f(i32 inreg %i, float inreg %f)
7870 // The code generator will only allocate 4 bytes from the parameter array for
7871 // the inreg arguments. All other arguments are allocated a multiple of 8
7875 class SparcV9ABIInfo : public ABIInfo {
7877 SparcV9ABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
7880 ABIArgInfo classifyType(QualType RetTy, unsigned SizeLimit) const;
7881 void computeInfo(CGFunctionInfo &FI) const override;
7882 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
7883 QualType Ty) const override;
7885 // Coercion type builder for structs passed in registers. The coercion type
7886 // serves two purposes:
7888 // 1. Pad structs to a multiple of 64 bits, so they are passed 'left-aligned'
7890 // 2. Expose aligned floating point elements as first-level elements, so the
7891 // code generator knows to pass them in floating point registers.
7893 // We also compute the InReg flag which indicates that the struct contains
7894 // aligned 32-bit floats.
7896 struct CoerceBuilder {
7897 llvm::LLVMContext &Context;
7898 const llvm::DataLayout &DL;
7899 SmallVector<llvm::Type*, 8> Elems;
7903 CoerceBuilder(llvm::LLVMContext &c, const llvm::DataLayout &dl)
7904 : Context(c), DL(dl), Size(0), InReg(false) {}
7906 // Pad Elems with integers until Size is ToSize.
7907 void pad(uint64_t ToSize) {
7908 assert(ToSize >= Size && "Cannot remove elements");
7912 // Finish the current 64-bit word.
7913 uint64_t Aligned = llvm::alignTo(Size, 64);
7914 if (Aligned > Size && Aligned <= ToSize) {
7915 Elems.push_back(llvm::IntegerType::get(Context, Aligned - Size));
7919 // Add whole 64-bit words.
7920 while (Size + 64 <= ToSize) {
7921 Elems.push_back(llvm::Type::getInt64Ty(Context));
7925 // Final in-word padding.
7926 if (Size < ToSize) {
7927 Elems.push_back(llvm::IntegerType::get(Context, ToSize - Size));
7932 // Add a floating point element at Offset.
7933 void addFloat(uint64_t Offset, llvm::Type *Ty, unsigned Bits) {
7934 // Unaligned floats are treated as integers.
7937 // The InReg flag is only required if there are any floats < 64 bits.
7941 Elems.push_back(Ty);
7942 Size = Offset + Bits;
7945 // Add a struct type to the coercion type, starting at Offset (in bits).
7946 void addStruct(uint64_t Offset, llvm::StructType *StrTy) {
7947 const llvm::StructLayout *Layout = DL.getStructLayout(StrTy);
7948 for (unsigned i = 0, e = StrTy->getNumElements(); i != e; ++i) {
7949 llvm::Type *ElemTy = StrTy->getElementType(i);
7950 uint64_t ElemOffset = Offset + Layout->getElementOffsetInBits(i);
7951 switch (ElemTy->getTypeID()) {
7952 case llvm::Type::StructTyID:
7953 addStruct(ElemOffset, cast<llvm::StructType>(ElemTy));
7955 case llvm::Type::FloatTyID:
7956 addFloat(ElemOffset, ElemTy, 32);
7958 case llvm::Type::DoubleTyID:
7959 addFloat(ElemOffset, ElemTy, 64);
7961 case llvm::Type::FP128TyID:
7962 addFloat(ElemOffset, ElemTy, 128);
7964 case llvm::Type::PointerTyID:
7965 if (ElemOffset % 64 == 0) {
7967 Elems.push_back(ElemTy);
7977 // Check if Ty is a usable substitute for the coercion type.
7978 bool isUsableType(llvm::StructType *Ty) const {
7979 return llvm::makeArrayRef(Elems) == Ty->elements();
7982 // Get the coercion type as a literal struct type.
7983 llvm::Type *getType() const {
7984 if (Elems.size() == 1)
7985 return Elems.front();
7987 return llvm::StructType::get(Context, Elems);
7991 } // end anonymous namespace
7994 SparcV9ABIInfo::classifyType(QualType Ty, unsigned SizeLimit) const {
7995 if (Ty->isVoidType())
7996 return ABIArgInfo::getIgnore();
7998 uint64_t Size = getContext().getTypeSize(Ty);
8000 // Anything too big to fit in registers is passed with an explicit indirect
8001 // pointer / sret pointer.
8002 if (Size > SizeLimit)
8003 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
8005 // Treat an enum type as its underlying type.
8006 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8007 Ty = EnumTy->getDecl()->getIntegerType();
8009 // Integer types smaller than a register are extended.
8010 if (Size < 64 && Ty->isIntegerType())
8011 return ABIArgInfo::getExtend(Ty);
8013 // Other non-aggregates go in registers.
8014 if (!isAggregateTypeForABI(Ty))
8015 return ABIArgInfo::getDirect();
8017 // If a C++ object has either a non-trivial copy constructor or a non-trivial
8018 // destructor, it is passed with an explicit indirect pointer / sret pointer.
8019 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI()))
8020 return getNaturalAlignIndirect(Ty, RAA == CGCXXABI::RAA_DirectInMemory);
8022 // This is a small aggregate type that should be passed in registers.
8023 // Build a coercion type from the LLVM struct type.
8024 llvm::StructType *StrTy = dyn_cast<llvm::StructType>(CGT.ConvertType(Ty));
8026 return ABIArgInfo::getDirect();
8028 CoerceBuilder CB(getVMContext(), getDataLayout());
8029 CB.addStruct(0, StrTy);
8030 CB.pad(llvm::alignTo(CB.DL.getTypeSizeInBits(StrTy), 64));
8032 // Try to use the original type for coercion.
8033 llvm::Type *CoerceTy = CB.isUsableType(StrTy) ? StrTy : CB.getType();
8036 return ABIArgInfo::getDirectInReg(CoerceTy);
8038 return ABIArgInfo::getDirect(CoerceTy);
8041 Address SparcV9ABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8042 QualType Ty) const {
8043 ABIArgInfo AI = classifyType(Ty, 16 * 8);
8044 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8045 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8046 AI.setCoerceToType(ArgTy);
8048 CharUnits SlotSize = CharUnits::fromQuantity(8);
8050 CGBuilderTy &Builder = CGF.Builder;
8051 Address Addr(Builder.CreateLoad(VAListAddr, "ap.cur"), SlotSize);
8052 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8054 auto TypeInfo = getContext().getTypeInfoInChars(Ty);
8056 Address ArgAddr = Address::invalid();
8058 switch (AI.getKind()) {
8059 case ABIArgInfo::Expand:
8060 case ABIArgInfo::CoerceAndExpand:
8061 case ABIArgInfo::InAlloca:
8062 llvm_unreachable("Unsupported ABI kind for va_arg");
8064 case ABIArgInfo::Extend: {
8066 CharUnits Offset = SlotSize - TypeInfo.first;
8067 ArgAddr = Builder.CreateConstInBoundsByteGEP(Addr, Offset, "extend");
8071 case ABIArgInfo::Direct: {
8072 auto AllocSize = getDataLayout().getTypeAllocSize(AI.getCoerceToType());
8073 Stride = CharUnits::fromQuantity(AllocSize).alignTo(SlotSize);
8078 case ABIArgInfo::Indirect:
8080 ArgAddr = Builder.CreateElementBitCast(Addr, ArgPtrTy, "indirect");
8081 ArgAddr = Address(Builder.CreateLoad(ArgAddr, "indirect.arg"),
8085 case ABIArgInfo::Ignore:
8086 return Address(llvm::UndefValue::get(ArgPtrTy), TypeInfo.second);
8090 llvm::Value *NextPtr =
8091 Builder.CreateConstInBoundsByteGEP(Addr.getPointer(), Stride, "ap.next");
8092 Builder.CreateStore(NextPtr, VAListAddr);
8094 return Builder.CreateBitCast(ArgAddr, ArgPtrTy, "arg.addr");
8097 void SparcV9ABIInfo::computeInfo(CGFunctionInfo &FI) const {
8098 FI.getReturnInfo() = classifyType(FI.getReturnType(), 32 * 8);
8099 for (auto &I : FI.arguments())
8100 I.info = classifyType(I.type, 16 * 8);
8104 class SparcV9TargetCodeGenInfo : public TargetCodeGenInfo {
8106 SparcV9TargetCodeGenInfo(CodeGenTypes &CGT)
8107 : TargetCodeGenInfo(new SparcV9ABIInfo(CGT)) {}
8109 int getDwarfEHStackPointer(CodeGen::CodeGenModule &M) const override {
8113 bool initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8114 llvm::Value *Address) const override;
8116 } // end anonymous namespace
8119 SparcV9TargetCodeGenInfo::initDwarfEHRegSizeTable(CodeGen::CodeGenFunction &CGF,
8120 llvm::Value *Address) const {
8121 // This is calculated from the LLVM and GCC tables and verified
8122 // against gcc output. AFAIK all ABIs use the same encoding.
8124 CodeGen::CGBuilderTy &Builder = CGF.Builder;
8126 llvm::IntegerType *i8 = CGF.Int8Ty;
8127 llvm::Value *Four8 = llvm::ConstantInt::get(i8, 4);
8128 llvm::Value *Eight8 = llvm::ConstantInt::get(i8, 8);
8130 // 0-31: the 8-byte general-purpose registers
8131 AssignToArrayRange(Builder, Address, Eight8, 0, 31);
8133 // 32-63: f0-31, the 4-byte floating-point registers
8134 AssignToArrayRange(Builder, Address, Four8, 32, 63);
8144 AssignToArrayRange(Builder, Address, Eight8, 64, 71);
8146 // 72-87: d0-15, the 8-byte floating-point registers
8147 AssignToArrayRange(Builder, Address, Eight8, 72, 87);
8153 //===----------------------------------------------------------------------===//
8154 // XCore ABI Implementation
8155 //===----------------------------------------------------------------------===//
8159 /// A SmallStringEnc instance is used to build up the TypeString by passing
8160 /// it by reference between functions that append to it.
8161 typedef llvm::SmallString<128> SmallStringEnc;
8163 /// TypeStringCache caches the meta encodings of Types.
8165 /// The reason for caching TypeStrings is two fold:
8166 /// 1. To cache a type's encoding for later uses;
8167 /// 2. As a means to break recursive member type inclusion.
8169 /// A cache Entry can have a Status of:
8170 /// NonRecursive: The type encoding is not recursive;
8171 /// Recursive: The type encoding is recursive;
8172 /// Incomplete: An incomplete TypeString;
8173 /// IncompleteUsed: An incomplete TypeString that has been used in a
8174 /// Recursive type encoding.
8176 /// A NonRecursive entry will have all of its sub-members expanded as fully
8177 /// as possible. Whilst it may contain types which are recursive, the type
8178 /// itself is not recursive and thus its encoding may be safely used whenever
8179 /// the type is encountered.
8181 /// A Recursive entry will have all of its sub-members expanded as fully as
8182 /// possible. The type itself is recursive and it may contain other types which
8183 /// are recursive. The Recursive encoding must not be used during the expansion
8184 /// of a recursive type's recursive branch. For simplicity the code uses
8185 /// IncompleteCount to reject all usage of Recursive encodings for member types.
8187 /// An Incomplete entry is always a RecordType and only encodes its
8188 /// identifier e.g. "s(S){}". Incomplete 'StubEnc' entries are ephemeral and
8189 /// are placed into the cache during type expansion as a means to identify and
8190 /// handle recursive inclusion of types as sub-members. If there is recursion
8191 /// the entry becomes IncompleteUsed.
8193 /// During the expansion of a RecordType's members:
8195 /// If the cache contains a NonRecursive encoding for the member type, the
8196 /// cached encoding is used;
8198 /// If the cache contains a Recursive encoding for the member type, the
8199 /// cached encoding is 'Swapped' out, as it may be incorrect, and...
8201 /// If the member is a RecordType, an Incomplete encoding is placed into the
8202 /// cache to break potential recursive inclusion of itself as a sub-member;
8204 /// Once a member RecordType has been expanded, its temporary incomplete
8205 /// entry is removed from the cache. If a Recursive encoding was swapped out
8206 /// it is swapped back in;
8208 /// If an incomplete entry is used to expand a sub-member, the incomplete
8209 /// entry is marked as IncompleteUsed. The cache keeps count of how many
8210 /// IncompleteUsed entries it currently contains in IncompleteUsedCount;
8212 /// If a member's encoding is found to be a NonRecursive or Recursive viz:
8213 /// IncompleteUsedCount==0, the member's encoding is added to the cache.
8214 /// Else the member is part of a recursive type and thus the recursion has
8215 /// been exited too soon for the encoding to be correct for the member.
8217 class TypeStringCache {
8218 enum Status {NonRecursive, Recursive, Incomplete, IncompleteUsed};
8220 std::string Str; // The encoded TypeString for the type.
8221 enum Status State; // Information about the encoding in 'Str'.
8222 std::string Swapped; // A temporary place holder for a Recursive encoding
8223 // during the expansion of RecordType's members.
8225 std::map<const IdentifierInfo *, struct Entry> Map;
8226 unsigned IncompleteCount; // Number of Incomplete entries in the Map.
8227 unsigned IncompleteUsedCount; // Number of IncompleteUsed entries in the Map.
8229 TypeStringCache() : IncompleteCount(0), IncompleteUsedCount(0) {}
8230 void addIncomplete(const IdentifierInfo *ID, std::string StubEnc);
8231 bool removeIncomplete(const IdentifierInfo *ID);
8232 void addIfComplete(const IdentifierInfo *ID, StringRef Str,
8234 StringRef lookupStr(const IdentifierInfo *ID);
8237 /// TypeString encodings for enum & union fields must be order.
8238 /// FieldEncoding is a helper for this ordering process.
8239 class FieldEncoding {
8243 FieldEncoding(bool b, SmallStringEnc &e) : HasName(b), Enc(e.c_str()) {}
8244 StringRef str() { return Enc; }
8245 bool operator<(const FieldEncoding &rhs) const {
8246 if (HasName != rhs.HasName) return HasName;
8247 return Enc < rhs.Enc;
8251 class XCoreABIInfo : public DefaultABIInfo {
8253 XCoreABIInfo(CodeGen::CodeGenTypes &CGT) : DefaultABIInfo(CGT) {}
8254 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8255 QualType Ty) const override;
8258 class XCoreTargetCodeGenInfo : public TargetCodeGenInfo {
8259 mutable TypeStringCache TSC;
8261 XCoreTargetCodeGenInfo(CodeGenTypes &CGT)
8262 :TargetCodeGenInfo(new XCoreABIInfo(CGT)) {}
8263 void emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8264 CodeGen::CodeGenModule &M) const override;
8267 } // End anonymous namespace.
8269 // TODO: this implementation is likely now redundant with the default
8271 Address XCoreABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8272 QualType Ty) const {
8273 CGBuilderTy &Builder = CGF.Builder;
8276 CharUnits SlotSize = CharUnits::fromQuantity(4);
8277 Address AP(Builder.CreateLoad(VAListAddr), SlotSize);
8279 // Handle the argument.
8280 ABIArgInfo AI = classifyArgumentType(Ty);
8281 CharUnits TypeAlign = getContext().getTypeAlignInChars(Ty);
8282 llvm::Type *ArgTy = CGT.ConvertType(Ty);
8283 if (AI.canHaveCoerceToType() && !AI.getCoerceToType())
8284 AI.setCoerceToType(ArgTy);
8285 llvm::Type *ArgPtrTy = llvm::PointerType::getUnqual(ArgTy);
8287 Address Val = Address::invalid();
8288 CharUnits ArgSize = CharUnits::Zero();
8289 switch (AI.getKind()) {
8290 case ABIArgInfo::Expand:
8291 case ABIArgInfo::CoerceAndExpand:
8292 case ABIArgInfo::InAlloca:
8293 llvm_unreachable("Unsupported ABI kind for va_arg");
8294 case ABIArgInfo::Ignore:
8295 Val = Address(llvm::UndefValue::get(ArgPtrTy), TypeAlign);
8296 ArgSize = CharUnits::Zero();
8298 case ABIArgInfo::Extend:
8299 case ABIArgInfo::Direct:
8300 Val = Builder.CreateBitCast(AP, ArgPtrTy);
8301 ArgSize = CharUnits::fromQuantity(
8302 getDataLayout().getTypeAllocSize(AI.getCoerceToType()));
8303 ArgSize = ArgSize.alignTo(SlotSize);
8305 case ABIArgInfo::Indirect:
8306 Val = Builder.CreateElementBitCast(AP, ArgPtrTy);
8307 Val = Address(Builder.CreateLoad(Val), TypeAlign);
8312 // Increment the VAList.
8313 if (!ArgSize.isZero()) {
8315 Builder.CreateConstInBoundsByteGEP(AP.getPointer(), ArgSize);
8316 Builder.CreateStore(APN, VAListAddr);
8322 /// During the expansion of a RecordType, an incomplete TypeString is placed
8323 /// into the cache as a means to identify and break recursion.
8324 /// If there is a Recursive encoding in the cache, it is swapped out and will
8325 /// be reinserted by removeIncomplete().
8326 /// All other types of encoding should have been used rather than arriving here.
8327 void TypeStringCache::addIncomplete(const IdentifierInfo *ID,
8328 std::string StubEnc) {
8332 assert( (E.Str.empty() || E.State == Recursive) &&
8333 "Incorrectly use of addIncomplete");
8334 assert(!StubEnc.empty() && "Passing an empty string to addIncomplete()");
8335 E.Swapped.swap(E.Str); // swap out the Recursive
8336 E.Str.swap(StubEnc);
8337 E.State = Incomplete;
8341 /// Once the RecordType has been expanded, the temporary incomplete TypeString
8342 /// must be removed from the cache.
8343 /// If a Recursive was swapped out by addIncomplete(), it will be replaced.
8344 /// Returns true if the RecordType was defined recursively.
8345 bool TypeStringCache::removeIncomplete(const IdentifierInfo *ID) {
8348 auto I = Map.find(ID);
8349 assert(I != Map.end() && "Entry not present");
8350 Entry &E = I->second;
8351 assert( (E.State == Incomplete ||
8352 E.State == IncompleteUsed) &&
8353 "Entry must be an incomplete type");
8354 bool IsRecursive = false;
8355 if (E.State == IncompleteUsed) {
8356 // We made use of our Incomplete encoding, thus we are recursive.
8358 --IncompleteUsedCount;
8360 if (E.Swapped.empty())
8363 // Swap the Recursive back.
8364 E.Swapped.swap(E.Str);
8366 E.State = Recursive;
8372 /// Add the encoded TypeString to the cache only if it is NonRecursive or
8373 /// Recursive (viz: all sub-members were expanded as fully as possible).
8374 void TypeStringCache::addIfComplete(const IdentifierInfo *ID, StringRef Str,
8376 if (!ID || IncompleteUsedCount)
8377 return; // No key or it is is an incomplete sub-type so don't add.
8379 if (IsRecursive && !E.Str.empty()) {
8380 assert(E.State==Recursive && E.Str.size() == Str.size() &&
8381 "This is not the same Recursive entry");
8382 // The parent container was not recursive after all, so we could have used
8383 // this Recursive sub-member entry after all, but we assumed the worse when
8384 // we started viz: IncompleteCount!=0.
8387 assert(E.Str.empty() && "Entry already present");
8389 E.State = IsRecursive? Recursive : NonRecursive;
8392 /// Return a cached TypeString encoding for the ID. If there isn't one, or we
8393 /// are recursively expanding a type (IncompleteCount != 0) and the cached
8394 /// encoding is Recursive, return an empty StringRef.
8395 StringRef TypeStringCache::lookupStr(const IdentifierInfo *ID) {
8397 return StringRef(); // We have no key.
8398 auto I = Map.find(ID);
8400 return StringRef(); // We have no encoding.
8401 Entry &E = I->second;
8402 if (E.State == Recursive && IncompleteCount)
8403 return StringRef(); // We don't use Recursive encodings for member types.
8405 if (E.State == Incomplete) {
8406 // The incomplete type is being used to break out of recursion.
8407 E.State = IncompleteUsed;
8408 ++IncompleteUsedCount;
8413 /// The XCore ABI includes a type information section that communicates symbol
8414 /// type information to the linker. The linker uses this information to verify
8415 /// safety/correctness of things such as array bound and pointers et al.
8416 /// The ABI only requires C (and XC) language modules to emit TypeStrings.
8417 /// This type information (TypeString) is emitted into meta data for all global
8418 /// symbols: definitions, declarations, functions & variables.
8420 /// The TypeString carries type, qualifier, name, size & value details.
8421 /// Please see 'Tools Development Guide' section 2.16.2 for format details:
8422 /// https://www.xmos.com/download/public/Tools-Development-Guide%28X9114A%29.pdf
8423 /// The output is tested by test/CodeGen/xcore-stringtype.c.
8425 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8426 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC);
8428 /// XCore uses emitTargetMD to emit TypeString metadata for global symbols.
8429 void XCoreTargetCodeGenInfo::emitTargetMD(const Decl *D, llvm::GlobalValue *GV,
8430 CodeGen::CodeGenModule &CGM) const {
8432 if (getTypeString(Enc, D, CGM, TSC)) {
8433 llvm::LLVMContext &Ctx = CGM.getModule().getContext();
8434 llvm::Metadata *MDVals[] = {llvm::ConstantAsMetadata::get(GV),
8435 llvm::MDString::get(Ctx, Enc.str())};
8436 llvm::NamedMDNode *MD =
8437 CGM.getModule().getOrInsertNamedMetadata("xcore.typestrings");
8438 MD->addOperand(llvm::MDNode::get(Ctx, MDVals));
8442 //===----------------------------------------------------------------------===//
8443 // SPIR ABI Implementation
8444 //===----------------------------------------------------------------------===//
8447 class SPIRTargetCodeGenInfo : public TargetCodeGenInfo {
8449 SPIRTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT)
8450 : TargetCodeGenInfo(new DefaultABIInfo(CGT)) {}
8451 unsigned getOpenCLKernelCallingConv() const override;
8454 } // End anonymous namespace.
8458 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI) {
8459 DefaultABIInfo SPIRABI(CGM.getTypes());
8460 SPIRABI.computeInfo(FI);
8465 unsigned SPIRTargetCodeGenInfo::getOpenCLKernelCallingConv() const {
8466 return llvm::CallingConv::SPIR_KERNEL;
8469 static bool appendType(SmallStringEnc &Enc, QualType QType,
8470 const CodeGen::CodeGenModule &CGM,
8471 TypeStringCache &TSC);
8473 /// Helper function for appendRecordType().
8474 /// Builds a SmallVector containing the encoded field types in declaration
8476 static bool extractFieldType(SmallVectorImpl<FieldEncoding> &FE,
8477 const RecordDecl *RD,
8478 const CodeGen::CodeGenModule &CGM,
8479 TypeStringCache &TSC) {
8480 for (const auto *Field : RD->fields()) {
8483 Enc += Field->getName();
8485 if (Field->isBitField()) {
8487 llvm::raw_svector_ostream OS(Enc);
8488 OS << Field->getBitWidthValue(CGM.getContext());
8491 if (!appendType(Enc, Field->getType(), CGM, TSC))
8493 if (Field->isBitField())
8496 FE.emplace_back(!Field->getName().empty(), Enc);
8501 /// Appends structure and union types to Enc and adds encoding to cache.
8502 /// Recursively calls appendType (via extractFieldType) for each field.
8503 /// Union types have their fields ordered according to the ABI.
8504 static bool appendRecordType(SmallStringEnc &Enc, const RecordType *RT,
8505 const CodeGen::CodeGenModule &CGM,
8506 TypeStringCache &TSC, const IdentifierInfo *ID) {
8507 // Append the cached TypeString if we have one.
8508 StringRef TypeString = TSC.lookupStr(ID);
8509 if (!TypeString.empty()) {
8514 // Start to emit an incomplete TypeString.
8515 size_t Start = Enc.size();
8516 Enc += (RT->isUnionType()? 'u' : 's');
8519 Enc += ID->getName();
8522 // We collect all encoded fields and order as necessary.
8523 bool IsRecursive = false;
8524 const RecordDecl *RD = RT->getDecl()->getDefinition();
8525 if (RD && !RD->field_empty()) {
8526 // An incomplete TypeString stub is placed in the cache for this RecordType
8527 // so that recursive calls to this RecordType will use it whilst building a
8528 // complete TypeString for this RecordType.
8529 SmallVector<FieldEncoding, 16> FE;
8530 std::string StubEnc(Enc.substr(Start).str());
8531 StubEnc += '}'; // StubEnc now holds a valid incomplete TypeString.
8532 TSC.addIncomplete(ID, std::move(StubEnc));
8533 if (!extractFieldType(FE, RD, CGM, TSC)) {
8534 (void) TSC.removeIncomplete(ID);
8537 IsRecursive = TSC.removeIncomplete(ID);
8538 // The ABI requires unions to be sorted but not structures.
8539 // See FieldEncoding::operator< for sort algorithm.
8540 if (RT->isUnionType())
8541 llvm::sort(FE.begin(), FE.end());
8542 // We can now complete the TypeString.
8543 unsigned E = FE.size();
8544 for (unsigned I = 0; I != E; ++I) {
8551 TSC.addIfComplete(ID, Enc.substr(Start), IsRecursive);
8555 /// Appends enum types to Enc and adds the encoding to the cache.
8556 static bool appendEnumType(SmallStringEnc &Enc, const EnumType *ET,
8557 TypeStringCache &TSC,
8558 const IdentifierInfo *ID) {
8559 // Append the cached TypeString if we have one.
8560 StringRef TypeString = TSC.lookupStr(ID);
8561 if (!TypeString.empty()) {
8566 size_t Start = Enc.size();
8569 Enc += ID->getName();
8572 // We collect all encoded enumerations and order them alphanumerically.
8573 if (const EnumDecl *ED = ET->getDecl()->getDefinition()) {
8574 SmallVector<FieldEncoding, 16> FE;
8575 for (auto I = ED->enumerator_begin(), E = ED->enumerator_end(); I != E;
8577 SmallStringEnc EnumEnc;
8579 EnumEnc += I->getName();
8581 I->getInitVal().toString(EnumEnc);
8583 FE.push_back(FieldEncoding(!I->getName().empty(), EnumEnc));
8585 llvm::sort(FE.begin(), FE.end());
8586 unsigned E = FE.size();
8587 for (unsigned I = 0; I != E; ++I) {
8594 TSC.addIfComplete(ID, Enc.substr(Start), false);
8598 /// Appends type's qualifier to Enc.
8599 /// This is done prior to appending the type's encoding.
8600 static void appendQualifier(SmallStringEnc &Enc, QualType QT) {
8601 // Qualifiers are emitted in alphabetical order.
8602 static const char *const Table[]={"","c:","r:","cr:","v:","cv:","rv:","crv:"};
8604 if (QT.isConstQualified())
8606 if (QT.isRestrictQualified())
8608 if (QT.isVolatileQualified())
8610 Enc += Table[Lookup];
8613 /// Appends built-in types to Enc.
8614 static bool appendBuiltinType(SmallStringEnc &Enc, const BuiltinType *BT) {
8615 const char *EncType;
8616 switch (BT->getKind()) {
8617 case BuiltinType::Void:
8620 case BuiltinType::Bool:
8623 case BuiltinType::Char_U:
8626 case BuiltinType::UChar:
8629 case BuiltinType::SChar:
8632 case BuiltinType::UShort:
8635 case BuiltinType::Short:
8638 case BuiltinType::UInt:
8641 case BuiltinType::Int:
8644 case BuiltinType::ULong:
8647 case BuiltinType::Long:
8650 case BuiltinType::ULongLong:
8653 case BuiltinType::LongLong:
8656 case BuiltinType::Float:
8659 case BuiltinType::Double:
8662 case BuiltinType::LongDouble:
8672 /// Appends a pointer encoding to Enc before calling appendType for the pointee.
8673 static bool appendPointerType(SmallStringEnc &Enc, const PointerType *PT,
8674 const CodeGen::CodeGenModule &CGM,
8675 TypeStringCache &TSC) {
8677 if (!appendType(Enc, PT->getPointeeType(), CGM, TSC))
8683 /// Appends array encoding to Enc before calling appendType for the element.
8684 static bool appendArrayType(SmallStringEnc &Enc, QualType QT,
8685 const ArrayType *AT,
8686 const CodeGen::CodeGenModule &CGM,
8687 TypeStringCache &TSC, StringRef NoSizeEnc) {
8688 if (AT->getSizeModifier() != ArrayType::Normal)
8691 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT))
8692 CAT->getSize().toStringUnsigned(Enc);
8694 Enc += NoSizeEnc; // Global arrays use "*", otherwise it is "".
8696 // The Qualifiers should be attached to the type rather than the array.
8697 appendQualifier(Enc, QT);
8698 if (!appendType(Enc, AT->getElementType(), CGM, TSC))
8704 /// Appends a function encoding to Enc, calling appendType for the return type
8705 /// and the arguments.
8706 static bool appendFunctionType(SmallStringEnc &Enc, const FunctionType *FT,
8707 const CodeGen::CodeGenModule &CGM,
8708 TypeStringCache &TSC) {
8710 if (!appendType(Enc, FT->getReturnType(), CGM, TSC))
8713 if (const FunctionProtoType *FPT = FT->getAs<FunctionProtoType>()) {
8714 // N.B. we are only interested in the adjusted param types.
8715 auto I = FPT->param_type_begin();
8716 auto E = FPT->param_type_end();
8719 if (!appendType(Enc, *I, CGM, TSC))
8725 if (FPT->isVariadic())
8728 if (FPT->isVariadic())
8738 /// Handles the type's qualifier before dispatching a call to handle specific
8740 static bool appendType(SmallStringEnc &Enc, QualType QType,
8741 const CodeGen::CodeGenModule &CGM,
8742 TypeStringCache &TSC) {
8744 QualType QT = QType.getCanonicalType();
8746 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe())
8747 // The Qualifiers should be attached to the type rather than the array.
8748 // Thus we don't call appendQualifier() here.
8749 return appendArrayType(Enc, QT, AT, CGM, TSC, "");
8751 appendQualifier(Enc, QT);
8753 if (const BuiltinType *BT = QT->getAs<BuiltinType>())
8754 return appendBuiltinType(Enc, BT);
8756 if (const PointerType *PT = QT->getAs<PointerType>())
8757 return appendPointerType(Enc, PT, CGM, TSC);
8759 if (const EnumType *ET = QT->getAs<EnumType>())
8760 return appendEnumType(Enc, ET, TSC, QT.getBaseTypeIdentifier());
8762 if (const RecordType *RT = QT->getAsStructureType())
8763 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8765 if (const RecordType *RT = QT->getAsUnionType())
8766 return appendRecordType(Enc, RT, CGM, TSC, QT.getBaseTypeIdentifier());
8768 if (const FunctionType *FT = QT->getAs<FunctionType>())
8769 return appendFunctionType(Enc, FT, CGM, TSC);
8774 static bool getTypeString(SmallStringEnc &Enc, const Decl *D,
8775 CodeGen::CodeGenModule &CGM, TypeStringCache &TSC) {
8779 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
8780 if (FD->getLanguageLinkage() != CLanguageLinkage)
8782 return appendType(Enc, FD->getType(), CGM, TSC);
8785 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
8786 if (VD->getLanguageLinkage() != CLanguageLinkage)
8788 QualType QT = VD->getType().getCanonicalType();
8789 if (const ArrayType *AT = QT->getAsArrayTypeUnsafe()) {
8790 // Global ArrayTypes are given a size of '*' if the size is unknown.
8791 // The Qualifiers should be attached to the type rather than the array.
8792 // Thus we don't call appendQualifier() here.
8793 return appendArrayType(Enc, QT, AT, CGM, TSC, "*");
8795 return appendType(Enc, QT, CGM, TSC);
8800 //===----------------------------------------------------------------------===//
8801 // RISCV ABI Implementation
8802 //===----------------------------------------------------------------------===//
8805 class RISCVABIInfo : public DefaultABIInfo {
8807 unsigned XLen; // Size of the integer ('x') registers in bits.
8808 static const int NumArgGPRs = 8;
8811 RISCVABIInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
8812 : DefaultABIInfo(CGT), XLen(XLen) {}
8814 // DefaultABIInfo's classifyReturnType and classifyArgumentType are
8815 // non-virtual, but computeInfo is virtual, so we overload it.
8816 void computeInfo(CGFunctionInfo &FI) const override;
8818 ABIArgInfo classifyArgumentType(QualType Ty, bool IsFixed,
8819 int &ArgGPRsLeft) const;
8820 ABIArgInfo classifyReturnType(QualType RetTy) const;
8822 Address EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8823 QualType Ty) const override;
8825 ABIArgInfo extendType(QualType Ty) const;
8827 } // end anonymous namespace
8829 void RISCVABIInfo::computeInfo(CGFunctionInfo &FI) const {
8830 QualType RetTy = FI.getReturnType();
8831 if (!getCXXABI().classifyReturnType(FI))
8832 FI.getReturnInfo() = classifyReturnType(RetTy);
8834 // IsRetIndirect is true if classifyArgumentType indicated the value should
8835 // be passed indirect or if the type size is greater than 2*xlen. e.g. fp128
8836 // is passed direct in LLVM IR, relying on the backend lowering code to
8837 // rewrite the argument list and pass indirectly on RV32.
8838 bool IsRetIndirect = FI.getReturnInfo().getKind() == ABIArgInfo::Indirect ||
8839 getContext().getTypeSize(RetTy) > (2 * XLen);
8841 // We must track the number of GPRs used in order to conform to the RISC-V
8842 // ABI, as integer scalars passed in registers should have signext/zeroext
8843 // when promoted, but are anyext if passed on the stack. As GPR usage is
8844 // different for variadic arguments, we must also track whether we are
8845 // examining a vararg or not.
8846 int ArgGPRsLeft = IsRetIndirect ? NumArgGPRs - 1 : NumArgGPRs;
8847 int NumFixedArgs = FI.getNumRequiredArgs();
8850 for (auto &ArgInfo : FI.arguments()) {
8851 bool IsFixed = ArgNum < NumFixedArgs;
8852 ArgInfo.info = classifyArgumentType(ArgInfo.type, IsFixed, ArgGPRsLeft);
8857 ABIArgInfo RISCVABIInfo::classifyArgumentType(QualType Ty, bool IsFixed,
8858 int &ArgGPRsLeft) const {
8859 assert(ArgGPRsLeft <= NumArgGPRs && "Arg GPR tracking underflow");
8860 Ty = useFirstFieldIfTransparentUnion(Ty);
8862 // Structures with either a non-trivial destructor or a non-trivial
8863 // copy constructor are always passed indirectly.
8864 if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, getCXXABI())) {
8867 return getNaturalAlignIndirect(Ty, /*ByVal=*/RAA ==
8868 CGCXXABI::RAA_DirectInMemory);
8871 // Ignore empty structs/unions.
8872 if (isEmptyRecord(getContext(), Ty, true))
8873 return ABIArgInfo::getIgnore();
8875 uint64_t Size = getContext().getTypeSize(Ty);
8876 uint64_t NeededAlign = getContext().getTypeAlign(Ty);
8877 bool MustUseStack = false;
8878 // Determine the number of GPRs needed to pass the current argument
8879 // according to the ABI. 2*XLen-aligned varargs are passed in "aligned"
8880 // register pairs, so may consume 3 registers.
8881 int NeededArgGPRs = 1;
8882 if (!IsFixed && NeededAlign == 2 * XLen)
8883 NeededArgGPRs = 2 + (ArgGPRsLeft % 2);
8884 else if (Size > XLen && Size <= 2 * XLen)
8887 if (NeededArgGPRs > ArgGPRsLeft) {
8888 MustUseStack = true;
8889 NeededArgGPRs = ArgGPRsLeft;
8892 ArgGPRsLeft -= NeededArgGPRs;
8894 if (!isAggregateTypeForABI(Ty) && !Ty->isVectorType()) {
8895 // Treat an enum type as its underlying type.
8896 if (const EnumType *EnumTy = Ty->getAs<EnumType>())
8897 Ty = EnumTy->getDecl()->getIntegerType();
8899 // All integral types are promoted to XLen width, unless passed on the
8901 if (Size < XLen && Ty->isIntegralOrEnumerationType() && !MustUseStack) {
8902 return extendType(Ty);
8905 return ABIArgInfo::getDirect();
8908 // Aggregates which are <= 2*XLen will be passed in registers if possible,
8909 // so coerce to integers.
8910 if (Size <= 2 * XLen) {
8911 unsigned Alignment = getContext().getTypeAlign(Ty);
8913 // Use a single XLen int if possible, 2*XLen if 2*XLen alignment is
8914 // required, and a 2-element XLen array if only XLen alignment is required.
8916 return ABIArgInfo::getDirect(
8917 llvm::IntegerType::get(getVMContext(), XLen));
8918 } else if (Alignment == 2 * XLen) {
8919 return ABIArgInfo::getDirect(
8920 llvm::IntegerType::get(getVMContext(), 2 * XLen));
8922 return ABIArgInfo::getDirect(llvm::ArrayType::get(
8923 llvm::IntegerType::get(getVMContext(), XLen), 2));
8926 return getNaturalAlignIndirect(Ty, /*ByVal=*/false);
8929 ABIArgInfo RISCVABIInfo::classifyReturnType(QualType RetTy) const {
8930 if (RetTy->isVoidType())
8931 return ABIArgInfo::getIgnore();
8933 int ArgGPRsLeft = 2;
8935 // The rules for return and argument types are the same, so defer to
8936 // classifyArgumentType.
8937 return classifyArgumentType(RetTy, /*IsFixed=*/true, ArgGPRsLeft);
8940 Address RISCVABIInfo::EmitVAArg(CodeGenFunction &CGF, Address VAListAddr,
8941 QualType Ty) const {
8942 CharUnits SlotSize = CharUnits::fromQuantity(XLen / 8);
8944 // Empty records are ignored for parameter passing purposes.
8945 if (isEmptyRecord(getContext(), Ty, true)) {
8946 Address Addr(CGF.Builder.CreateLoad(VAListAddr), SlotSize);
8947 Addr = CGF.Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(Ty));
8951 std::pair<CharUnits, CharUnits> SizeAndAlign =
8952 getContext().getTypeInfoInChars(Ty);
8954 // Arguments bigger than 2*Xlen bytes are passed indirectly.
8955 bool IsIndirect = SizeAndAlign.first > 2 * SlotSize;
8957 return emitVoidPtrVAArg(CGF, VAListAddr, Ty, IsIndirect, SizeAndAlign,
8958 SlotSize, /*AllowHigherAlign=*/true);
8961 ABIArgInfo RISCVABIInfo::extendType(QualType Ty) const {
8962 int TySize = getContext().getTypeSize(Ty);
8963 // RV64 ABI requires unsigned 32 bit integers to be sign extended.
8964 if (XLen == 64 && Ty->isUnsignedIntegerOrEnumerationType() && TySize == 32)
8965 return ABIArgInfo::getSignExtend(Ty);
8966 return ABIArgInfo::getExtend(Ty);
8970 class RISCVTargetCodeGenInfo : public TargetCodeGenInfo {
8972 RISCVTargetCodeGenInfo(CodeGen::CodeGenTypes &CGT, unsigned XLen)
8973 : TargetCodeGenInfo(new RISCVABIInfo(CGT, XLen)) {}
8975 void setTargetAttributes(const Decl *D, llvm::GlobalValue *GV,
8976 CodeGen::CodeGenModule &CGM) const override {
8977 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
8980 const auto *Attr = FD->getAttr<RISCVInterruptAttr>();
8985 switch (Attr->getInterrupt()) {
8986 case RISCVInterruptAttr::user: Kind = "user"; break;
8987 case RISCVInterruptAttr::supervisor: Kind = "supervisor"; break;
8988 case RISCVInterruptAttr::machine: Kind = "machine"; break;
8991 auto *Fn = cast<llvm::Function>(GV);
8993 Fn->addFnAttr("interrupt", Kind);
8998 //===----------------------------------------------------------------------===//
9000 //===----------------------------------------------------------------------===//
9002 bool CodeGenModule::supportsCOMDAT() const {
9003 return getTriple().supportsCOMDAT();
9006 const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
9007 if (TheTargetCodeGenInfo)
9008 return *TheTargetCodeGenInfo;
9010 // Helper to set the unique_ptr while still keeping the return value.
9011 auto SetCGInfo = [&](TargetCodeGenInfo *P) -> const TargetCodeGenInfo & {
9012 this->TheTargetCodeGenInfo.reset(P);
9016 const llvm::Triple &Triple = getTarget().getTriple();
9017 switch (Triple.getArch()) {
9019 return SetCGInfo(new DefaultTargetCodeGenInfo(Types));
9021 case llvm::Triple::le32:
9022 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9023 case llvm::Triple::mips:
9024 case llvm::Triple::mipsel:
9025 if (Triple.getOS() == llvm::Triple::NaCl)
9026 return SetCGInfo(new PNaClTargetCodeGenInfo(Types));
9027 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, true));
9029 case llvm::Triple::mips64:
9030 case llvm::Triple::mips64el:
9031 return SetCGInfo(new MIPSTargetCodeGenInfo(Types, false));
9033 case llvm::Triple::avr:
9034 return SetCGInfo(new AVRTargetCodeGenInfo(Types));
9036 case llvm::Triple::aarch64:
9037 case llvm::Triple::aarch64_be: {
9038 AArch64ABIInfo::ABIKind Kind = AArch64ABIInfo::AAPCS;
9039 if (getTarget().getABI() == "darwinpcs")
9040 Kind = AArch64ABIInfo::DarwinPCS;
9041 else if (Triple.isOSWindows())
9043 new WindowsAArch64TargetCodeGenInfo(Types, AArch64ABIInfo::Win64));
9045 return SetCGInfo(new AArch64TargetCodeGenInfo(Types, Kind));
9048 case llvm::Triple::wasm32:
9049 case llvm::Triple::wasm64:
9050 return SetCGInfo(new WebAssemblyTargetCodeGenInfo(Types));
9052 case llvm::Triple::arm:
9053 case llvm::Triple::armeb:
9054 case llvm::Triple::thumb:
9055 case llvm::Triple::thumbeb: {
9056 if (Triple.getOS() == llvm::Triple::Win32) {
9058 new WindowsARMTargetCodeGenInfo(Types, ARMABIInfo::AAPCS_VFP));
9061 ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
9062 StringRef ABIStr = getTarget().getABI();
9063 if (ABIStr == "apcs-gnu")
9064 Kind = ARMABIInfo::APCS;
9065 else if (ABIStr == "aapcs16")
9066 Kind = ARMABIInfo::AAPCS16_VFP;
9067 else if (CodeGenOpts.FloatABI == "hard" ||
9068 (CodeGenOpts.FloatABI != "soft" &&
9069 (Triple.getEnvironment() == llvm::Triple::GNUEABIHF ||
9070 Triple.getEnvironment() == llvm::Triple::MuslEABIHF ||
9071 Triple.getEnvironment() == llvm::Triple::EABIHF)))
9072 Kind = ARMABIInfo::AAPCS_VFP;
9074 return SetCGInfo(new ARMTargetCodeGenInfo(Types, Kind));
9077 case llvm::Triple::ppc:
9079 new PPC32TargetCodeGenInfo(Types, CodeGenOpts.FloatABI == "soft"));
9080 case llvm::Triple::ppc64:
9081 if (Triple.isOSBinFormatELF()) {
9082 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv1;
9083 if (getTarget().getABI() == "elfv2")
9084 Kind = PPC64_SVR4_ABIInfo::ELFv2;
9085 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
9086 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
9088 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9091 return SetCGInfo(new PPC64TargetCodeGenInfo(Types));
9092 case llvm::Triple::ppc64le: {
9093 assert(Triple.isOSBinFormatELF() && "PPC64 LE non-ELF not supported!");
9094 PPC64_SVR4_ABIInfo::ABIKind Kind = PPC64_SVR4_ABIInfo::ELFv2;
9095 if (getTarget().getABI() == "elfv1" || getTarget().getABI() == "elfv1-qpx")
9096 Kind = PPC64_SVR4_ABIInfo::ELFv1;
9097 bool HasQPX = getTarget().getABI() == "elfv1-qpx";
9098 bool IsSoftFloat = CodeGenOpts.FloatABI == "soft";
9100 return SetCGInfo(new PPC64_SVR4_TargetCodeGenInfo(Types, Kind, HasQPX,
9104 case llvm::Triple::nvptx:
9105 case llvm::Triple::nvptx64:
9106 return SetCGInfo(new NVPTXTargetCodeGenInfo(Types));
9108 case llvm::Triple::msp430:
9109 return SetCGInfo(new MSP430TargetCodeGenInfo(Types));
9111 case llvm::Triple::riscv32:
9112 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 32));
9113 case llvm::Triple::riscv64:
9114 return SetCGInfo(new RISCVTargetCodeGenInfo(Types, 64));
9116 case llvm::Triple::systemz: {
9117 bool HasVector = getTarget().getABI() == "vector";
9118 return SetCGInfo(new SystemZTargetCodeGenInfo(Types, HasVector));
9121 case llvm::Triple::tce:
9122 case llvm::Triple::tcele:
9123 return SetCGInfo(new TCETargetCodeGenInfo(Types));
9125 case llvm::Triple::x86: {
9126 bool IsDarwinVectorABI = Triple.isOSDarwin();
9127 bool RetSmallStructInRegABI =
9128 X86_32TargetCodeGenInfo::isStructReturnInRegABI(Triple, CodeGenOpts);
9129 bool IsWin32FloatStructABI = Triple.isOSWindows() && !Triple.isOSCygMing();
9131 if (Triple.getOS() == llvm::Triple::Win32) {
9132 return SetCGInfo(new WinX86_32TargetCodeGenInfo(
9133 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9134 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters));
9136 return SetCGInfo(new X86_32TargetCodeGenInfo(
9137 Types, IsDarwinVectorABI, RetSmallStructInRegABI,
9138 IsWin32FloatStructABI, CodeGenOpts.NumRegisterParameters,
9139 CodeGenOpts.FloatABI == "soft"));
9143 case llvm::Triple::x86_64: {
9144 StringRef ABI = getTarget().getABI();
9145 X86AVXABILevel AVXLevel =
9147 ? X86AVXABILevel::AVX512
9148 : ABI == "avx" ? X86AVXABILevel::AVX : X86AVXABILevel::None);
9150 switch (Triple.getOS()) {
9151 case llvm::Triple::Win32:
9152 return SetCGInfo(new WinX86_64TargetCodeGenInfo(Types, AVXLevel));
9153 case llvm::Triple::PS4:
9154 return SetCGInfo(new PS4TargetCodeGenInfo(Types, AVXLevel));
9156 return SetCGInfo(new X86_64TargetCodeGenInfo(Types, AVXLevel));
9159 case llvm::Triple::hexagon:
9160 return SetCGInfo(new HexagonTargetCodeGenInfo(Types));
9161 case llvm::Triple::lanai:
9162 return SetCGInfo(new LanaiTargetCodeGenInfo(Types));
9163 case llvm::Triple::r600:
9164 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
9165 case llvm::Triple::amdgcn:
9166 return SetCGInfo(new AMDGPUTargetCodeGenInfo(Types));
9167 case llvm::Triple::sparc:
9168 return SetCGInfo(new SparcV8TargetCodeGenInfo(Types));
9169 case llvm::Triple::sparcv9:
9170 return SetCGInfo(new SparcV9TargetCodeGenInfo(Types));
9171 case llvm::Triple::xcore:
9172 return SetCGInfo(new XCoreTargetCodeGenInfo(Types));
9173 case llvm::Triple::spir:
9174 case llvm::Triple::spir64:
9175 return SetCGInfo(new SPIRTargetCodeGenInfo(Types));
9179 /// Create an OpenCL kernel for an enqueued block.
9181 /// The kernel has the same function type as the block invoke function. Its
9182 /// name is the name of the block invoke function postfixed with "_kernel".
9183 /// It simply calls the block invoke function then returns.
9185 TargetCodeGenInfo::createEnqueuedBlockKernel(CodeGenFunction &CGF,
9186 llvm::Function *Invoke,
9187 llvm::Value *BlockLiteral) const {
9188 auto *InvokeFT = Invoke->getFunctionType();
9189 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9190 for (auto &P : InvokeFT->params())
9191 ArgTys.push_back(P);
9192 auto &C = CGF.getLLVMContext();
9193 std::string Name = Invoke->getName().str() + "_kernel";
9194 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9195 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9196 &CGF.CGM.getModule());
9197 auto IP = CGF.Builder.saveIP();
9198 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9199 auto &Builder = CGF.Builder;
9200 Builder.SetInsertPoint(BB);
9201 llvm::SmallVector<llvm::Value *, 2> Args;
9202 for (auto &A : F->args())
9204 Builder.CreateCall(Invoke, Args);
9205 Builder.CreateRetVoid();
9206 Builder.restoreIP(IP);
9210 /// Create an OpenCL kernel for an enqueued block.
9212 /// The type of the first argument (the block literal) is the struct type
9213 /// of the block literal instead of a pointer type. The first argument
9214 /// (block literal) is passed directly by value to the kernel. The kernel
9215 /// allocates the same type of struct on stack and stores the block literal
9216 /// to it and passes its pointer to the block invoke function. The kernel
9217 /// has "enqueued-block" function attribute and kernel argument metadata.
9218 llvm::Function *AMDGPUTargetCodeGenInfo::createEnqueuedBlockKernel(
9219 CodeGenFunction &CGF, llvm::Function *Invoke,
9220 llvm::Value *BlockLiteral) const {
9221 auto &Builder = CGF.Builder;
9222 auto &C = CGF.getLLVMContext();
9224 auto *BlockTy = BlockLiteral->getType()->getPointerElementType();
9225 auto *InvokeFT = Invoke->getFunctionType();
9226 llvm::SmallVector<llvm::Type *, 2> ArgTys;
9227 llvm::SmallVector<llvm::Metadata *, 8> AddressQuals;
9228 llvm::SmallVector<llvm::Metadata *, 8> AccessQuals;
9229 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeNames;
9230 llvm::SmallVector<llvm::Metadata *, 8> ArgBaseTypeNames;
9231 llvm::SmallVector<llvm::Metadata *, 8> ArgTypeQuals;
9232 llvm::SmallVector<llvm::Metadata *, 8> ArgNames;
9234 ArgTys.push_back(BlockTy);
9235 ArgTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9236 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(0)));
9237 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "__block_literal"));
9238 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9239 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9240 ArgNames.push_back(llvm::MDString::get(C, "block_literal"));
9241 for (unsigned I = 1, E = InvokeFT->getNumParams(); I < E; ++I) {
9242 ArgTys.push_back(InvokeFT->getParamType(I));
9243 ArgTypeNames.push_back(llvm::MDString::get(C, "void*"));
9244 AddressQuals.push_back(llvm::ConstantAsMetadata::get(Builder.getInt32(3)));
9245 AccessQuals.push_back(llvm::MDString::get(C, "none"));
9246 ArgBaseTypeNames.push_back(llvm::MDString::get(C, "void*"));
9247 ArgTypeQuals.push_back(llvm::MDString::get(C, ""));
9249 llvm::MDString::get(C, (Twine("local_arg") + Twine(I)).str()));
9251 std::string Name = Invoke->getName().str() + "_kernel";
9252 auto *FT = llvm::FunctionType::get(llvm::Type::getVoidTy(C), ArgTys, false);
9253 auto *F = llvm::Function::Create(FT, llvm::GlobalValue::InternalLinkage, Name,
9254 &CGF.CGM.getModule());
9255 F->addFnAttr("enqueued-block");
9256 auto IP = CGF.Builder.saveIP();
9257 auto *BB = llvm::BasicBlock::Create(C, "entry", F);
9258 Builder.SetInsertPoint(BB);
9259 unsigned BlockAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(BlockTy);
9260 auto *BlockPtr = Builder.CreateAlloca(BlockTy, nullptr);
9261 BlockPtr->setAlignment(BlockAlign);
9262 Builder.CreateAlignedStore(F->arg_begin(), BlockPtr, BlockAlign);
9263 auto *Cast = Builder.CreatePointerCast(BlockPtr, InvokeFT->getParamType(0));
9264 llvm::SmallVector<llvm::Value *, 2> Args;
9265 Args.push_back(Cast);
9266 for (auto I = F->arg_begin() + 1, E = F->arg_end(); I != E; ++I)
9268 Builder.CreateCall(Invoke, Args);
9269 Builder.CreateRetVoid();
9270 Builder.restoreIP(IP);
9272 F->setMetadata("kernel_arg_addr_space", llvm::MDNode::get(C, AddressQuals));
9273 F->setMetadata("kernel_arg_access_qual", llvm::MDNode::get(C, AccessQuals));
9274 F->setMetadata("kernel_arg_type", llvm::MDNode::get(C, ArgTypeNames));
9275 F->setMetadata("kernel_arg_base_type",
9276 llvm::MDNode::get(C, ArgBaseTypeNames));
9277 F->setMetadata("kernel_arg_type_qual", llvm::MDNode::get(C, ArgTypeQuals));
9278 if (CGF.CGM.getCodeGenOpts().EmitOpenCLArgMetadata)
9279 F->setMetadata("kernel_arg_name", llvm::MDNode::get(C, ArgNames));