37#include "llvm/ABI/FunctionInfo.h"
38#include "llvm/ABI/IRTypeMapper.h"
39#include "llvm/ABI/TargetInfo.h"
40#include "llvm/ABI/Types.h"
41#include "llvm/ADT/STLExtras.h"
42#include "llvm/ADT/StringExtras.h"
43#include "llvm/Analysis/ValueTracking.h"
44#include "llvm/IR/Assumptions.h"
45#include "llvm/IR/AttributeMask.h"
46#include "llvm/IR/Attributes.h"
47#include "llvm/IR/CallingConv.h"
48#include "llvm/IR/DataLayout.h"
49#include "llvm/IR/DebugInfoMetadata.h"
50#include "llvm/IR/InlineAsm.h"
51#include "llvm/IR/IntrinsicInst.h"
52#include "llvm/IR/Intrinsics.h"
53#include "llvm/IR/Type.h"
54#include "llvm/Transforms/Utils/Local.h"
67 if (Target.getTriple().isSPIROrSPIRV())
68 return llvm::CallingConv::SPIR_FUNC;
69 return llvm::CallingConv::C;
71 return llvm::CallingConv::X86_StdCall;
73 return llvm::CallingConv::X86_FastCall;
75 return llvm::CallingConv::X86_RegCall;
77 return llvm::CallingConv::X86_ThisCall;
79 return llvm::CallingConv::Win64;
81 return llvm::CallingConv::X86_64_SysV;
83 return llvm::CallingConv::ARM_AAPCS;
85 return llvm::CallingConv::ARM_AAPCS_VFP;
87 return llvm::CallingConv::Intel_OCL_BI;
90 return llvm::CallingConv::C;
93 return llvm::CallingConv::X86_VectorCall;
95 return llvm::CallingConv::AArch64_VectorCall;
97 return llvm::CallingConv::AArch64_SVE_VectorCall;
99 return CGM.getTargetCodeGenInfo().getDeviceKernelCallingConv();
101 return llvm::CallingConv::PreserveMost;
103 return llvm::CallingConv::PreserveAll;
105 return llvm::CallingConv::Swift;
107 return llvm::CallingConv::SwiftTail;
109 return llvm::CallingConv::M68k_RTD;
111 return llvm::CallingConv::PreserveNone;
115#define CC_VLS_CASE(ABI_VLEN) \
116 case CC_RISCVVLSCall_##ABI_VLEN: \
117 return llvm::CallingConv::RISCV_VLSCall_##ABI_VLEN;
132 llvm_unreachable(
"unhandled calling convention");
143 RecTy = Context.getCanonicalTagType(RD);
145 RecTy = Context.VoidTy;
150 return Context.getPointerType(RecTy);
183 assert(paramInfos.size() <= prefixArgs);
184 assert(proto->
getNumParams() + prefixArgs <= totalArgs);
186 paramInfos.reserve(totalArgs);
189 paramInfos.resize(prefixArgs);
193 paramInfos.push_back(ParamInfo);
195 if (ParamInfo.hasPassObjectSize())
196 paramInfos.emplace_back();
199 assert(paramInfos.size() <= totalArgs &&
200 "Did we forget to insert pass_object_size args?");
202 paramInfos.resize(totalArgs);
212 if (!FPT->hasExtParameterInfos()) {
213 assert(paramInfos.empty() &&
214 "We have paramInfos, but the prototype doesn't?");
215 prefix.append(FPT->param_type_begin(), FPT->param_type_end());
219 unsigned PrefixSize = prefix.size();
223 prefix.reserve(prefix.size() + FPT->getNumParams());
225 auto ExtInfos = FPT->getExtParameterInfos();
226 assert(ExtInfos.size() == FPT->getNumParams());
227 for (
unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
228 prefix.push_back(FPT->getParamType(I));
229 if (ExtInfos[I].hasPassObjectSize())
254 FTP->getExtInfo(), paramInfos,
Required,
265 return ::arrangeLLVMFunctionInfo(*
this,
false, argTypes,
270 bool IsTargetDefaultMSABI) {
275 if (D->
hasAttr<FastCallAttr>())
281 if (D->
hasAttr<ThisCallAttr>())
284 if (D->
hasAttr<VectorCallAttr>())
290 if (PcsAttr *PCS = D->
getAttr<PcsAttr>())
293 if (D->
hasAttr<AArch64VectorPcsAttr>())
296 if (D->
hasAttr<AArch64SVEPcsAttr>())
299 if (D->
hasAttr<DeviceKernelAttr>())
302 if (D->
hasAttr<IntelOclBiccAttr>())
311 if (D->
hasAttr<PreserveMostAttr>())
314 if (D->
hasAttr<PreserveAllAttr>())
320 if (D->
hasAttr<PreserveNoneAttr>())
323 if (D->
hasAttr<RISCVVectorCCAttr>())
326 if (RISCVVLSCCAttr *PCS = D->
getAttr<RISCVVLSCCAttr>()) {
327 switch (PCS->getVectorWidth()) {
329 llvm_unreachable(
"Invalid RISC-V VLS ABI VLEN");
330#define CC_VLS_CASE(ABI_VLEN) \
332 return CC_RISCVVLSCall_##ABI_VLEN;
370 CanonicalFTP.getTypePtr(), argTypes.size());
373 CanonicalFTP->getReturnType().getUnqualifiedType(),
375 paramInfos, required, MD);
381 if (FD->
hasAttr<CUDAGlobalAttr>()) {
413 argTypes, prototype->getExtInfo(), paramInfos,
423 !Target.getCXXABI().hasConstructorVariants();
436 bool PassParams =
true;
438 if (
auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
441 if (
auto Inherited = CD->getInheritedConstructor())
453 if (!paramInfos.empty()) {
456 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.
Prefix,
459 paramInfos.append(AddedArgs.
Suffix,
464 (PassParams && MD->isVariadic() ?
RequiredArgs(argTypes.size())
470 ? CGM.getContext().VoidPtrTy
473 argTypes, extInfo, paramInfos, required, MD);
479 for (
auto &arg : args)
487 for (
auto &arg : args)
494 unsigned totalArgs) {
512 unsigned ExtraPrefixArgs,
unsigned ExtraSuffixArgs,
515 for (
const auto &Arg : args)
516 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
519 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
524 FPT, TotalPrefixArgs + ExtraSuffixArgs)
530 ? CGM.getContext().VoidPtrTy
537 if (PassProtoArgs && FPT->hasExtParameterInfos()) {
544 ArgTypes, Info, ParamInfos,
Required,
554 if (MD->isImplicitObjectMemberFunction())
562 if (DeviceKernelAttr::isOpenCLSpelling(FD->
getAttr<DeviceKernelAttr>()) &&
565 CGM.getTargetCodeGenInfo().setOCLKernelStubCallingConvention(FT);
573 {}, noProto->getExtInfo(), {},
607 argTys.push_back(Context.getCanonicalParamType(receiverType));
609 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
611 argTys.push_back(Context.getCanonicalParamType(I->getType()));
613 I->hasAttr<NoEscapeAttr>());
614 extParamInfos.push_back(extParamInfo);
618 bool IsTargetDefaultMSABI =
624 if (
getContext().getLangOpts().ObjCAutoRefCount &&
625 MD->
hasAttr<NSReturnsRetainedAttr>())
663 assert(MD->
isVirtual() &&
"only methods have thunks");
680 ArgTys.push_back(*FTP->param_type_begin());
682 ArgTys.push_back(Context.IntTy);
683 CallingConv CC = Context.getDefaultCallingConvention(
695 unsigned numExtraRequiredArgs,
bool chainCall,
697 assert(args.size() >= numExtraRequiredArgs);
707 if (proto->isVariadic())
710 if (proto->hasExtParameterInfos())
724 for (
const auto &arg : args)
729 paramInfos, required, ABIInfoFD);
740 chainCall ? 1 : 0, chainCall, ABIInfoFD);
772 for (
const auto &Arg : args)
773 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
815 assert(numPrefixArgs + 1 <= args.size() &&
816 "Emitting a call with less args than the required prefix?");
827 paramInfos, required, ABIInfoFD);
839 assert(signature.
arg_size() <= args.size());
840 unsigned X86ABIAVXLevel =
841 CGM.getABIInfo().getX86ABIAVXLevel(ABIInfoFD, signature.
getExtInfo());
842 if (signature.
arg_size() == args.size() &&
848 if (!sigParamInfos.empty()) {
849 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
850 paramInfos.resize(args.size());
888 return "IndirectAliased";
894 return "CoerceAndExpand";
896 return "TargetSpecific";
900 llvm_unreachable(
"Unknown kind");
906 MappedArgTypes.reserve(FI.
arg_size());
908 MappedArgTypes.push_back(AbiMapper->convertType(Arg.type));
911 llvm::abi::RequiredArgs AbiRequired = llvm::abi::RequiredArgs::All;
913 AbiRequired = llvm::abi::RequiredArgs(
Required.getNumRequiredArgs());
915 auto AbiFI = llvm::abi::FunctionInfo::create(
917 MappedArgTypes, AbiRequired);
926 auto ConvertABIArgInfo = [&](
ABIArgInfo &Target,
929 auto Check = [&](
bool Cond, llvm::function_ref<void()> MessageFn) {
933 llvm::dbgs() <<
"For return value of type ";
935 llvm::dbgs() <<
"For argument " << ArgNo <<
" of type ";
936 llvm::dbgs() <<
Type <<
": ";
938 llvm::dbgs() <<
"\n";
941 auto CheckSimple = [&](
auto TargetVal,
auto ResVal, StringRef What) {
942 Check(TargetVal == ResVal, [&]() {
943 llvm::dbgs() << What <<
" mismatch (expected: " << TargetVal
944 <<
", given: " << ResVal <<
")";
949 Check(Target.getKind() == Res.
getKind(), [&]() {
950 llvm::dbgs() <<
"Kind mismatch (expected: "
951 << abiKindToString(Target.getKind())
952 <<
", given: " << abiKindToString(Res.getKind()) <<
")";
957 llvm::Type *TargetType = Target.getCoerceToType();
964 Check(TargetType == ResType, [&]() {
965 llvm::dbgs() <<
"CoerceToType mismatch (expected: " << *TargetType
966 <<
", given: " << *ResType <<
")";
972 CheckSimple(Target.isSignExt(), Res.
isSignExt(),
"SignExt");
973 CheckSimple(Target.isZeroExt(), Res.
isZeroExt(),
"ZeroExt");
976 CheckSimple(Target.getDirectAlign(), Res.
getDirectAlign(),
"DirectAlign");
986 "IndirectAddrSpace");
990 llvm::dbgs() <<
"IndirectAlign mismatch (expected: "
991 << Target.getIndirectAlign().getQuantity()
992 <<
", given: " << Res.getIndirectAlign().getQuantity()
1003 auto ConvertABIArgInfo =
1005 int ArgNo) { Target = convertABIArgInfo(AbiInfo,
Type); };
1008 ConvertABIArgInfo(FI.
getReturnInfo(), AbiFI->getReturnInfo(),
1012 for (
auto [CGArg, AbiArg] :
1013 llvm::zip_equal(FI.
arguments(), AbiFI->arguments()))
1014 ConvertABIArgInfo(CGArg.info, AbiArg.Info, CGArg.type, ArgNo++);
1017ABIArgInfo CodeGenModule::convertABIArgInfo(
const llvm::abi::ArgInfo &AbiInfo,
1019 switch (AbiInfo.getKind()) {
1020 case llvm::abi::ArgInfo::Direct: {
1021 llvm::Type *CoercedType =
nullptr;
1022 if (AbiInfo.getCoerceToType())
1023 CoercedType = AbiReverseMapper->convertType(AbiInfo.getCoerceToType());
1025 CoercedType = getTypes().ConvertType(
Type);
1028 case llvm::abi::ArgInfo::Extend: {
1029 llvm::Type *CoercedType =
nullptr;
1030 if (AbiInfo.getCoerceToType())
1031 CoercedType = AbiReverseMapper->convertType(AbiInfo.getCoerceToType());
1033 CoercedType = getTypes().ConvertType(
Type);
1039 if (AbiInfo.isSignExt())
1041 if (AbiInfo.isZeroExt())
1045 case llvm::abi::ArgInfo::Indirect: {
1049 AbiInfo.getIndirectByVal(),
1050 AbiInfo.getIndirectRealign());
1052 case llvm::abi::ArgInfo::Ignore:
1055 llvm_unreachable(
"Unexpected llvm::abi::ArgInfo kind");
1066 assert(llvm::all_of(argTypes,
1070 llvm::FoldingSetNodeID ID;
1075 bool isDelegateCall =
1077 unsigned X86ABIAVXLevel = CGM.getABIInfo().getX86ABIAVXLevel(ABIInfoFD, info);
1081 paramInfos, required, resultType, argTypes);
1091 llvm::FoldingSetNodeID ID;
1093 X86ABIAVXLevel, info, paramInfos, required,
1094 resultType, argTypes);
1096 llvm::FoldingSetInsertToken InsertToken;
1101 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
1105 X86ABIAVXLevel, info, paramInfos, resultType,
1106 argTypes, required);
1107 FunctionInfos.insert(FI, InsertToken);
1109 bool inserted = FunctionsBeingProcessed.insert(FI).second;
1111 assert(inserted &&
"Recursively being processed?");
1115 (CC == llvm::CallingConv::SPIR_KERNEL || CC == llvm::CallingConv::C)) {
1120 assert(CC != llvm::CallingConv::C || getContext().getLangOpts().
OpenCL);
1124 }
else if (CGM.shouldUseLLVMABILowering(CC)) {
1125 CGM.computeABIInfoUsingLib(*FI);
1127 CGM.getABIInfo().computeInfo(*FI);
1138 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() ==
nullptr)
1139 I.info.setCoerceToType(ConvertType(I.type));
1141 bool erased = FunctionsBeingProcessed.erase(FI);
1143 assert(erased &&
"Not in set?");
1149 unsigned llvmCC,
bool instanceMethod,
bool chainCall,
bool delegateCall,
1153 assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
1157 void *buffer =
operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
1158 argTypes.size() + 1, paramInfos.size()));
1160 CGFunctionInfo *FI =
new (buffer) CGFunctionInfo();
1161 FI->CallingConvention = llvmCC;
1162 FI->EffectiveCallingConvention = llvmCC;
1163 FI->ASTCallingConvention = info.getCC();
1164 FI->InstanceMethod = instanceMethod;
1165 FI->ChainCall = chainCall;
1166 FI->DelegateCall = delegateCall;
1167 FI->CmseNSCall = info.getCmseNSCall();
1168 FI->NoReturn = info.getNoReturn();
1169 FI->ReturnsRetained = info.getProducesResult();
1170 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
1171 FI->NoCfCheck = info.getNoCfCheck();
1172 FI->Required = required;
1173 FI->HasRegParm = info.getHasRegParm();
1174 FI->RegParm = info.getRegParm();
1175 FI->X86ABIAVXLevel = X86ABIAVXLevel;
1176 FI->ArgStruct =
nullptr;
1177 FI->ArgStructAlign = 0;
1178 FI->NumArgs = argTypes.size();
1179 FI->HasExtParameterInfos = !paramInfos.empty();
1180 FI->getArgsBuffer()[0].
type = resultType;
1181 FI->MaxVectorWidth = 0;
1182 for (
unsigned i = 0, e = argTypes.size(); i != e; ++i)
1183 FI->getArgsBuffer()[i + 1].
type = argTypes[i];
1184 for (
unsigned i = 0, e = paramInfos.size(); i != e; ++i)
1185 FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
1195struct TypeExpansion {
1196 enum TypeExpansionKind {
1208 const TypeExpansionKind Kind;
1210 TypeExpansion(TypeExpansionKind K) : Kind(K) {}
1211 virtual ~TypeExpansion() {}
1214struct ConstantArrayExpansion : TypeExpansion {
1218 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
1219 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
1220 static bool classof(
const TypeExpansion *TE) {
1221 return TE->Kind == TEK_ConstantArray;
1225struct RecordExpansion : TypeExpansion {
1226 SmallVector<const CXXBaseSpecifier *, 1> Bases;
1228 SmallVector<const FieldDecl *, 1> Fields;
1230 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
1231 SmallVector<const FieldDecl *, 1> &&Fields)
1232 : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
1233 Fields(std::move(Fields)) {}
1234 static bool classof(
const TypeExpansion *TE) {
1235 return TE->Kind == TEK_Record;
1239struct ComplexExpansion : TypeExpansion {
1242 ComplexExpansion(QualType EltTy) : TypeExpansion(
TEK_Complex), EltTy(EltTy) {}
1243 static bool classof(
const TypeExpansion *TE) {
1248struct NoExpansion : TypeExpansion {
1249 NoExpansion() : TypeExpansion(TEK_None) {}
1250 static bool classof(
const TypeExpansion *TE) {
return TE->Kind == TEK_None; }
1254static std::unique_ptr<TypeExpansion>
1257 return std::make_unique<ConstantArrayExpansion>(AT->getElementType(),
1263 assert(!RD->hasFlexibleArrayMember() &&
1264 "Cannot expand structure with flexible array.");
1265 if (RD->isUnion()) {
1271 for (
const auto *FD : RD->fields()) {
1272 if (FD->isZeroLengthBitField())
1274 assert(!FD->isBitField() &&
1275 "Cannot expand structure with bit-field members.");
1276 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
1277 if (UnionSize < FieldSize) {
1278 UnionSize = FieldSize;
1283 Fields.push_back(LargestFD);
1285 if (
const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
1286 assert(!CXXRD->isDynamicClass() &&
1287 "cannot expand vtable pointers in dynamic classes");
1288 llvm::append_range(Bases, llvm::make_pointer_range(CXXRD->bases()));
1291 for (
const auto *FD : RD->fields()) {
1292 if (FD->isZeroLengthBitField())
1294 assert(!FD->isBitField() &&
1295 "Cannot expand structure with bit-field members.");
1296 Fields.push_back(FD);
1299 return std::make_unique<RecordExpansion>(std::move(Bases),
1303 return std::make_unique<ComplexExpansion>(CT->getElementType());
1305 return std::make_unique<NoExpansion>();
1310 if (
auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1313 if (
auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1315 for (
auto BS : RExp->Bases)
1317 for (
auto FD : RExp->Fields)
1330 if (
auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1331 for (
int i = 0, n = CAExp->NumElts; i < n; i++) {
1334 }
else if (
auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1335 for (
auto BS : RExp->Bases)
1337 for (
auto FD : RExp->Fields)
1339 }
else if (
auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
1350 ConstantArrayExpansion *CAE,
1352 llvm::function_ref<
void(
Address)> Fn) {
1353 for (
int i = 0, n = CAE->NumElts; i < n; i++) {
1359void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
1360 llvm::Function::arg_iterator &AI) {
1361 assert(LV.isSimple() &&
1362 "Unexpected non-simple lvalue during struct expansion.");
1365 if (
auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1367 *
this, CAExp, LV.getAddress(), [&](Address EltAddr) {
1368 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
1369 ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
1371 }
else if (
auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1373 for (
const CXXBaseSpecifier *BS : RExp->Bases) {
1377 false, SourceLocation());
1378 LValue SubLV = MakeAddrLValue(Base, BS->
getType());
1381 ExpandTypeFromArgs(BS->
getType(), SubLV, AI);
1383 for (
auto FD : RExp->Fields) {
1385 LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
1386 ExpandTypeFromArgs(FD->getType(), SubLV, AI);
1389 auto realValue = &*AI++;
1390 auto imagValue = &*AI++;
1391 EmitStoreOfComplex(
ComplexPairTy(realValue, imagValue), LV,
true);
1396 llvm::Value *Arg = &*AI++;
1397 if (LV.isBitField()) {
1403 if (Arg->getType()->isPointerTy()) {
1405 Arg = Builder.CreateBitCast(Arg,
Addr.getElementType());
1407 EmitStoreOfScalar(Arg, LV);
1412void CodeGenFunction::ExpandTypeToArgs(
1413 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
1414 SmallVectorImpl<llvm::Value *> &IRCallArgs,
unsigned &IRCallArgPos) {
1416 if (
auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
1421 CallArg(convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
1423 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
1426 }
else if (
auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
1429 for (
const CXXBaseSpecifier *BS : RExp->Bases) {
1433 false, SourceLocation());
1437 ExpandTypeToArgs(BS->
getType(), BaseArg, IRFuncTy, IRCallArgs,
1441 LValue LV = MakeAddrLValue(This, Ty);
1442 for (
auto FD : RExp->Fields) {
1444 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
1445 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
1450 IRCallArgs[IRCallArgPos++] = CV.first;
1451 IRCallArgs[IRCallArgPos++] = CV.second;
1455 assert(RV.isScalar() &&
1456 "Unexpected non-scalar rvalue during struct expansion.");
1459 llvm::Value *
V = RV.getScalarVal();
1460 if (IRCallArgPos < IRFuncTy->getNumParams() &&
1461 V->getType() != IRFuncTy->getParamType(IRCallArgPos))
1462 V = Builder.CreateBitCast(
V, IRFuncTy->getParamType(IRCallArgPos));
1464 IRCallArgs[IRCallArgPos++] =
V;
1472 const Twine &Name =
"tmp") {
1485 llvm::StructType *SrcSTy,
1489 if (SrcSTy->getNumElements() == 0)
1498 uint64_t FirstEltSize = CGF.
CGM.
getDataLayout().getTypeStoreSize(FirstElt);
1499 if (FirstEltSize < DstSize &&
1508 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
1523 if (Val->getType() == Ty)
1529 return CGF.
Builder.CreateBitCast(Val, Ty,
"coerce.val");
1535 llvm::Type *DestIntTy = Ty;
1539 if (Val->getType() != DestIntTy) {
1541 if (DL.isBigEndian()) {
1544 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
1545 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
1547 if (SrcSize > DstSize) {
1548 Val = CGF.
Builder.CreateLShr(Val, SrcSize - DstSize,
"coerce.highbits");
1549 Val = CGF.
Builder.CreateTrunc(Val, DestIntTy,
"coerce.val.ii");
1551 Val = CGF.
Builder.CreateZExt(Val, DestIntTy,
"coerce.val.ii");
1552 Val = CGF.
Builder.CreateShl(Val, DstSize - SrcSize,
"coerce.highbits");
1556 Val = CGF.
Builder.CreateIntCast(Val, DestIntTy,
false,
"coerce.val.ii");
1561 Val = CGF.
Builder.CreateIntToPtr(Val, Ty,
"coerce.val.ip");
1568 if (PFPFields.empty())
1571 auto LoadCoercedField = [&](
CharUnits Offset,
1572 llvm::Type *FieldType) -> llvm::Value * {
1577 if (!PFPFields.empty() && PFPFields[0].Offset == Offset) {
1581 FieldVal = CGF.
Builder.CreatePtrToInt(FieldVal, FieldType);
1582 PFPFields.erase(PFPFields.begin());
1599 Val = CGF.
Builder.CreatePtrToInt(Val, Ty);
1603 auto *ET = AT->getElementType();
1607 llvm::Value *Val = llvm::PoisonValue::get(AT);
1608 for (
unsigned Idx = 0; Idx != AT->getNumElements(); ++Idx, Offset += WordSize)
1609 Val = CGF.
Builder.CreateInsertValue(Val, LoadCoercedField(Offset, ET), Idx);
1633 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
1635 DstSize.getFixedValue(), CGF);
1650 if (!SrcSize.isScalable() && !DstSize.isScalable() &&
1651 SrcSize.getFixedValue() >= DstSize.getFixedValue()) {
1665 if (
auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Ty)) {
1666 if (
auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
1669 if (ScalableDstTy->getElementType()->isIntegerTy(1) &&
1670 FixedSrcTy->getElementType()->isIntegerTy(8)) {
1671 ScalableDstTy = llvm::ScalableVectorType::get(
1672 FixedSrcTy->getElementType(),
1674 ScalableDstTy->getElementCount().getKnownMinValue(), 8));
1676 if (ScalableDstTy->getElementType() == FixedSrcTy->getElementType()) {
1678 auto *PoisonVec = llvm::PoisonValue::get(ScalableDstTy);
1680 ScalableDstTy, PoisonVec, Load, uint64_t(0),
"cast.scalable");
1682 llvm::VectorType::getWithSizeAndScalar(ScalableDstTy, Ty));
1683 if (
Result->getType() != ScalableDstTy)
1685 if (
Result->getType() != Ty)
1698 llvm::ConstantInt::get(CGF.
IntPtrTy, SrcSize.getKnownMinValue()));
1705 if (PFPFields.empty())
1708 llvm::Type *SrcTy = Src->getType();
1709 auto StoreCoercedField = [&](
CharUnits Offset, llvm::Value *FieldVal) {
1710 if (!PFPFields.empty() && PFPFields[0].Offset == Offset) {
1715 PFPFields.erase(PFPFields.begin());
1735 auto *ET = AT->getElementType();
1739 for (
unsigned i = 0; i != AT->getNumElements(); ++i, Offset += WordSize)
1740 StoreCoercedField(Offset, CGF.
Builder.CreateExtractValue(Src, i));
1746 Address Dst, llvm::TypeSize DstSize,
1747 bool DstIsVolatile) {
1751 llvm::Type *SrcTy = Src->getType();
1752 llvm::TypeSize SrcSize =
CGM.getDataLayout().getTypeAllocSize(SrcTy);
1758 if (llvm::StructType *DstSTy =
1760 assert(!SrcSize.isScalable());
1762 SrcSize.getFixedValue(), *
this);
1769 if (SrcSize.isScalable() || SrcSize <= DstSize) {
1770 if (SrcTy->isIntegerTy() && Dst.
getElementType()->isPointerTy() &&
1774 auto *I =
Builder.CreateStore(Src, Dst, DstIsVolatile);
1776 }
else if (llvm::StructType *STy =
1777 dyn_cast<llvm::StructType>(Src->getType())) {
1780 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1782 llvm::Value *Elt =
Builder.CreateExtractValue(Src, i);
1783 auto *I =
Builder.CreateStore(Elt, EltPtr, DstIsVolatile);
1791 }
else if (SrcTy->isIntegerTy()) {
1793 llvm::Type *DstIntTy =
Builder.getIntNTy(DstSize.getFixedValue() * 8);
1810 Builder.CreateStore(Src, Tmp);
1811 auto *I =
Builder.CreateMemCpy(
1821 if (
unsigned offset = info.getDirectOffset()) {
1830static std::pair<llvm::Value *, bool>
1832 llvm::ScalableVectorType *FromTy, llvm::Value *
V,
1833 StringRef Name =
"") {
1836 if (FromTy->getElementType()->isIntegerTy(1) &&
1837 ToTy->getElementType() == CGF.
Builder.getInt8Ty()) {
1838 if (!FromTy->getElementCount().isKnownMultipleOf(8)) {
1839 FromTy = llvm::ScalableVectorType::get(
1840 FromTy->getElementType(),
1841 llvm::alignTo<8>(FromTy->getElementCount().getKnownMinValue()));
1842 llvm::Value *ZeroVec = llvm::Constant::getNullValue(FromTy);
1843 V = CGF.
Builder.CreateInsertVector(FromTy, ZeroVec,
V, uint64_t(0));
1845 FromTy = llvm::ScalableVectorType::get(
1846 ToTy->getElementType(),
1847 FromTy->getElementCount().getKnownMinValue() / 8);
1848 V = CGF.
Builder.CreateBitCast(
V, FromTy);
1850 if (FromTy->getElementType() == ToTy->getElementType()) {
1851 V->setName(Name +
".coerce");
1852 V = CGF.
Builder.CreateExtractVector(ToTy,
V, uint64_t(0),
"cast.fixed");
1862class ClangToLLVMArgMapping {
1863 static const unsigned InvalidIndex = ~0U;
1864 unsigned InallocaArgNo;
1866 unsigned TotalIRArgs;
1870 unsigned PaddingArgIndex;
1873 unsigned FirstArgIndex;
1874 unsigned NumberOfArgs;
1877 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
1881 SmallVector<IRArgs, 8> ArgInfo;
1884 ClangToLLVMArgMapping(
const ASTContext &Context,
const CGFunctionInfo &FI,
1885 bool OnlyRequiredArgs =
false)
1886 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
1887 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
1888 construct(Context, FI, OnlyRequiredArgs);
1891 bool hasInallocaArg()
const {
return InallocaArgNo != InvalidIndex; }
1892 unsigned getInallocaArgNo()
const {
1893 assert(hasInallocaArg());
1894 return InallocaArgNo;
1897 bool hasSRetArg()
const {
return SRetArgNo != InvalidIndex; }
1898 unsigned getSRetArgNo()
const {
1899 assert(hasSRetArg());
1903 unsigned totalIRArgs()
const {
return TotalIRArgs; }
1905 bool hasPaddingArg(
unsigned ArgNo)
const {
1906 assert(ArgNo < ArgInfo.size());
1907 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
1909 unsigned getPaddingArgNo(
unsigned ArgNo)
const {
1910 assert(hasPaddingArg(ArgNo));
1911 return ArgInfo[ArgNo].PaddingArgIndex;
1916 std::pair<unsigned, unsigned> getIRArgs(
unsigned ArgNo)
const {
1917 assert(ArgNo < ArgInfo.size());
1918 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
1919 ArgInfo[ArgNo].NumberOfArgs);
1923 void construct(
const ASTContext &Context,
const CGFunctionInfo &FI,
1924 bool OnlyRequiredArgs);
1927void ClangToLLVMArgMapping::construct(
const ASTContext &Context,
1928 const CGFunctionInfo &FI,
1929 bool OnlyRequiredArgs) {
1930 unsigned IRArgNo = 0;
1931 bool SwapThisWithSRet =
false;
1936 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
1944 QualType ArgType = I->type;
1945 const ABIArgInfo &AI = I->info;
1947 auto &IRArgs = ArgInfo[ArgNo];
1950 IRArgs.PaddingArgIndex = IRArgNo++;
1957 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.
getCoerceToType());
1959 IRArgs.NumberOfArgs = STy->getNumElements();
1961 IRArgs.NumberOfArgs = 1;
1967 IRArgs.NumberOfArgs = 1;
1972 IRArgs.NumberOfArgs = 0;
1982 if (IRArgs.NumberOfArgs > 0) {
1983 IRArgs.FirstArgIndex = IRArgNo;
1984 IRArgNo += IRArgs.NumberOfArgs;
1989 if (IRArgNo == 1 && SwapThisWithSRet)
1992 assert(ArgNo == ArgInfo.size());
1995 InallocaArgNo = IRArgNo++;
1997 TotalIRArgs = IRArgNo;
2005 return RI.
isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
2020 switch (BT->getKind()) {
2023 case BuiltinType::Float:
2025 case BuiltinType::Double:
2027 case BuiltinType::LongDouble:
2038 if (BT->getKind() == BuiltinType::LongDouble)
2039 return getTarget().useObjCFP2RetForComplexLongDouble();
2053 bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
2055 assert(Inserted &&
"Recursively being processed?");
2057 llvm::Type *resultType =
nullptr;
2062 llvm_unreachable(
"Invalid ABI kind for return argument");
2074 unsigned addressSpace = CGM.getTypes().getTargetAddressSpace(ret);
2075 resultType = llvm::PointerType::get(
getLLVMContext(), addressSpace);
2091 ClangToLLVMArgMapping IRFunctionArgs(
getContext(), FI,
true);
2095 if (IRFunctionArgs.hasSRetArg()) {
2096 ArgTypes[IRFunctionArgs.getSRetArgNo()] = llvm::PointerType::get(
2101 if (IRFunctionArgs.hasInallocaArg())
2102 ArgTypes[IRFunctionArgs.getInallocaArgNo()] =
2109 for (; it != ie; ++it, ++ArgNo) {
2113 if (IRFunctionArgs.hasPaddingArg(ArgNo))
2114 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
2117 unsigned FirstIRArg, NumIRArgs;
2118 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
2123 assert(NumIRArgs == 0);
2127 assert(NumIRArgs == 1);
2129 ArgTypes[FirstIRArg] = llvm::PointerType::get(
2133 assert(NumIRArgs == 1);
2134 ArgTypes[FirstIRArg] = llvm::PointerType::get(
2143 llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
2145 assert(NumIRArgs == st->getNumElements());
2146 for (
unsigned i = 0, e = st->getNumElements(); i != e; ++i)
2147 ArgTypes[FirstIRArg + i] = st->getElementType(i);
2149 assert(NumIRArgs == 1);
2150 ArgTypes[FirstIRArg] = argType;
2156 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
2158 *ArgTypesIter++ = EltTy;
2160 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
2165 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
2167 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
2172 bool Erased = FunctionsBeingProcessed.erase(&FI);
2174 assert(Erased &&
"Not in set?");
2176 return llvm::FunctionType::get(resultType, ArgTypes, FI.
isVariadic());
2190 llvm::AttrBuilder &FuncAttrs,
2197 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2201 FuncAttrs.addAttribute(
"aarch64_pstate_sm_enabled");
2203 FuncAttrs.addAttribute(
"aarch64_pstate_sm_compatible");
2205 FuncAttrs.addAttribute(
"aarch64_za_state_agnostic");
2209 FuncAttrs.addAttribute(
"aarch64_preserves_za");
2211 FuncAttrs.addAttribute(
"aarch64_in_za");
2213 FuncAttrs.addAttribute(
"aarch64_out_za");
2215 FuncAttrs.addAttribute(
"aarch64_inout_za");
2219 FuncAttrs.addAttribute(
"aarch64_preserves_zt0");
2221 FuncAttrs.addAttribute(
"aarch64_in_zt0");
2223 FuncAttrs.addAttribute(
"aarch64_out_zt0");
2225 FuncAttrs.addAttribute(
"aarch64_inout_zt0");
2229 const Decl *Callee) {
2235 for (
const OMPAssumeAttr *AA : Callee->specific_attrs<OMPAssumeAttr>())
2236 AA->getAssumption().split(Attrs,
",");
2239 FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
2240 llvm::join(Attrs.begin(), Attrs.end(),
","));
2247 if (
const RecordType *RT =
2249 if (
const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2250 return ClassDecl->hasTrivialDestructor();
2256 const Decl *TargetDecl) {
2262 if (
Module.getLangOpts().Sanitize.has(SanitizerKind::Memory))
2266 if (!
Module.getLangOpts().CPlusPlus)
2269 if (
const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl)) {
2270 if (FDecl->isExternC())
2272 }
else if (
const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl)) {
2274 if (VDecl->isExternC())
2282 return Module.getCodeGenOpts().StrictReturn ||
2283 !
Module.MayDropFunctionReturn(
Module.getContext(), RetTy) ||
2284 Module.getLangOpts().Sanitize.has(SanitizerKind::Return);
2291 llvm::DenormalMode FP32DenormalMode,
2292 llvm::AttrBuilder &FuncAttrs) {
2293 llvm::DenormalFPEnv FPEnv(FPDenormalMode, FP32DenormalMode);
2294 if (FPEnv != llvm::DenormalFPEnv::getDefault())
2295 FuncAttrs.addDenormalFPEnvAttr(FPEnv);
2303 llvm::AttrBuilder &FuncAttrs) {
2309 StringRef Name,
bool HasOptnone,
const CodeGenOptions &CodeGenOpts,
2311 llvm::AttrBuilder &FuncAttrs) {
2314 if (CodeGenOpts.OptimizeSize)
2315 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
2316 if (CodeGenOpts.OptimizeSize == 2)
2317 FuncAttrs.addAttribute(llvm::Attribute::MinSize);
2320 if (CodeGenOpts.DisableRedZone)
2321 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
2322 if (CodeGenOpts.IndirectTlsSegRefs)
2323 FuncAttrs.addAttribute(
"indirect-tls-seg-refs");
2324 if (CodeGenOpts.NoImplicitFloat)
2325 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
2327 if (AttrOnCallSite) {
2332 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
2334 FuncAttrs.addAttribute(
"trap-func-name", CodeGenOpts.
TrapFuncName);
2336 switch (CodeGenOpts.getFramePointer()) {
2344 FuncAttrs.addAttribute(
"frame-pointer",
2346 CodeGenOpts.getFramePointer()));
2349 if (CodeGenOpts.LessPreciseFPMAD)
2350 FuncAttrs.addAttribute(
"less-precise-fpmad",
"true");
2352 if (CodeGenOpts.NullPointerIsValid)
2353 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
2356 FuncAttrs.addAttribute(
"no-trapping-math",
"true");
2360 if (CodeGenOpts.SoftFloat)
2361 FuncAttrs.addAttribute(
"use-soft-float",
"true");
2362 FuncAttrs.addAttribute(
"stack-protector-buffer-size",
2363 llvm::utostr(CodeGenOpts.SSPBufferSize));
2364 if (LangOpts.NoSignedZero)
2365 FuncAttrs.addAttribute(
"no-signed-zeros-fp-math",
"true");
2368 const std::vector<std::string> &Recips = CodeGenOpts.
Reciprocals;
2369 if (!Recips.empty())
2370 FuncAttrs.addAttribute(
"reciprocal-estimates", llvm::join(Recips,
","));
2374 FuncAttrs.addAttribute(
"prefer-vector-width",
2377 if (CodeGenOpts.StackRealignment)
2378 FuncAttrs.addAttribute(
"stackrealign");
2379 if (CodeGenOpts.Backchain)
2380 FuncAttrs.addAttribute(
"backchain");
2381 if (CodeGenOpts.EnableSegmentedStacks)
2382 FuncAttrs.addAttribute(
"split-stack");
2384 if (CodeGenOpts.SpeculativeLoadHardening)
2385 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2388 switch (CodeGenOpts.getZeroCallUsedRegs()) {
2389 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Skip:
2390 FuncAttrs.removeAttribute(
"zero-call-used-regs");
2392 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPRArg:
2393 FuncAttrs.addAttribute(
"zero-call-used-regs",
"used-gpr-arg");
2395 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedGPR:
2396 FuncAttrs.addAttribute(
"zero-call-used-regs",
"used-gpr");
2398 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::UsedArg:
2399 FuncAttrs.addAttribute(
"zero-call-used-regs",
"used-arg");
2401 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::Used:
2402 FuncAttrs.addAttribute(
"zero-call-used-regs",
"used");
2404 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPRArg:
2405 FuncAttrs.addAttribute(
"zero-call-used-regs",
"all-gpr-arg");
2407 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllGPR:
2408 FuncAttrs.addAttribute(
"zero-call-used-regs",
"all-gpr");
2410 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::AllArg:
2411 FuncAttrs.addAttribute(
"zero-call-used-regs",
"all-arg");
2413 case llvm::ZeroCallUsedRegs::ZeroCallUsedRegsKind::All:
2414 FuncAttrs.addAttribute(
"zero-call-used-regs",
"all");
2425 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2430 if ((LangOpts.CUDA && LangOpts.CUDAIsDevice) || LangOpts.OpenCL ||
2431 LangOpts.SYCLIsDevice) {
2432 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2435 if (CodeGenOpts.SaveRegParams && !AttrOnCallSite)
2436 FuncAttrs.addAttribute(
"save-reg-params");
2439 StringRef Var,
Value;
2441 FuncAttrs.addAttribute(Var,
Value);
2455 const llvm::Function &F,
2457 auto FFeatures = F.getFnAttribute(
"target-features");
2459 llvm::StringSet<> MergedNames;
2461 MergedFeatures.reserve(TargetOpts.
Features.size());
2463 auto AddUnmergedFeatures = [&](
auto &&FeatureRange) {
2464 for (StringRef
Feature : FeatureRange) {
2468 StringRef Name =
Feature.drop_front(1);
2469 bool Merged = !MergedNames.insert(Name).second;
2471 MergedFeatures.push_back(
Feature);
2475 if (FFeatures.isValid())
2476 AddUnmergedFeatures(llvm::split(FFeatures.getValueAsString(),
','));
2477 AddUnmergedFeatures(TargetOpts.
Features);
2479 if (!MergedFeatures.empty()) {
2480 llvm::sort(MergedFeatures);
2481 FuncAttr.addAttribute(
"target-features", llvm::join(MergedFeatures,
","));
2488 bool WillInternalize) {
2490 llvm::AttrBuilder FuncAttrs(F.getContext());
2493 if (!TargetOpts.
CPU.empty())
2494 FuncAttrs.addAttribute(
"target-cpu", TargetOpts.
CPU);
2495 if (!TargetOpts.
TuneCPU.empty())
2496 FuncAttrs.addAttribute(
"tune-cpu", TargetOpts.
TuneCPU);
2499 CodeGenOpts, LangOpts,
2502 if (!WillInternalize && F.isInterposable()) {
2507 F.addFnAttrs(FuncAttrs);
2511 llvm::AttributeMask AttrsToRemove;
2515 llvm::DenormalFPEnv MergedFPEnv =
2516 OptsFPEnv.mergeCalleeMode(F.getDenormalFPEnv());
2518 if (MergedFPEnv == llvm::DenormalFPEnv::getDefault()) {
2519 AttrsToRemove.addAttribute(llvm::Attribute::DenormalFPEnv);
2522 FuncAttrs.addDenormalFPEnvAttr(MergedFPEnv);
2525 F.removeFnAttrs(AttrsToRemove);
2529 F.addFnAttrs(FuncAttrs);
2532void CodeGenModule::getTrivialDefaultFunctionAttributes(
2533 StringRef Name,
bool HasOptnone,
bool AttrOnCallSite,
2534 llvm::AttrBuilder &FuncAttrs) {
2536 getLangOpts(), AttrOnCallSite,
2540void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
2542 bool AttrOnCallSite,
2543 llvm::AttrBuilder &FuncAttrs) {
2547 if (!AttrOnCallSite)
2553 if (!AttrOnCallSite)
2558 llvm::AttrBuilder &attrs) {
2559 getDefaultFunctionAttributes(
"",
false,
2561 GetCPUAndFeaturesAttributes(
GlobalDecl(), attrs);
2566 const NoBuiltinAttr *NBA =
nullptr) {
2567 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
2569 AttributeName +=
"no-builtin-";
2570 AttributeName += BuiltinName;
2571 FuncAttrs.addAttribute(AttributeName);
2575 if (LangOpts.NoBuiltin) {
2577 FuncAttrs.addAttribute(
"no-builtins");
2591 if (llvm::is_contained(NBA->builtinNames(),
"*")) {
2592 FuncAttrs.addAttribute(
"no-builtins");
2597 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
2601 const llvm::DataLayout &DL,
const ABIArgInfo &AI,
2602 bool CheckCoerce =
true) {
2609 if (!DL.typeSizeEqualsStoreSize(Ty))
2616 if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
2617 DL.getTypeSizeInBits(Ty)))
2641 if (
const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
2652 unsigned NumRequiredArgs,
unsigned ArgNo) {
2653 const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
2658 if (ArgNo >= NumRequiredArgs)
2662 if (ArgNo < FD->getNumParams()) {
2663 const ParmVarDecl *Param = FD->getParamDecl(ArgNo);
2664 if (Param && Param->hasAttr<MaybeUndefAttr>())
2681 if (llvm::AttributeFuncs::isNoFPClassCompatibleType(IRTy))
2684 if (llvm::StructType *ST = dyn_cast<llvm::StructType>(IRTy)) {
2686 llvm::all_of(ST->elements(),
2687 llvm::AttributeFuncs::isNoFPClassCompatibleType);
2695 llvm::FPClassTest Mask = llvm::fcNone;
2696 if (LangOpts.NoHonorInfs)
2697 Mask |= llvm::fcInf;
2698 if (LangOpts.NoHonorNaNs)
2699 Mask |= llvm::fcNan;
2705 llvm::AttributeList &Attrs) {
2706 if (Attrs.getMemoryEffects().getModRef() == llvm::ModRefInfo::NoModRef) {
2707 Attrs = Attrs.removeFnAttribute(
getLLVMContext(), llvm::Attribute::Memory);
2708 llvm::Attribute MemoryAttr = llvm::Attribute::getWithMemoryEffects(
2734 llvm::AttributeList &AttrList,
2736 bool AttrOnCallSite,
bool IsThunk) {
2744 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2746 FuncAttrs.addAttribute(
"cmse_nonsecure_call");
2757 bool HasOptnone =
false;
2759 const NoBuiltinAttr *NBA =
nullptr;
2763 std::optional<llvm::Attribute::AttrKind> MemAttrForPtrArgs;
2764 bool AddedPotentialArgAccess =
false;
2765 auto AddPotentialArgAccess = [&]() {
2766 AddedPotentialArgAccess =
true;
2767 llvm::Attribute A = FuncAttrs.getAttribute(llvm::Attribute::Memory);
2769 FuncAttrs.addMemoryAttr(A.getMemoryEffects() |
2770 llvm::MemoryEffects::argMemOnly());
2777 if (TargetDecl->
hasAttr<ReturnsTwiceAttr>())
2778 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2779 if (TargetDecl->
hasAttr<NoThrowAttr>())
2780 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2781 if (TargetDecl->
hasAttr<NoReturnAttr>())
2782 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2783 if (TargetDecl->
hasAttr<ColdAttr>())
2784 FuncAttrs.addAttribute(llvm::Attribute::Cold);
2785 if (TargetDecl->
hasAttr<HotAttr>())
2786 FuncAttrs.addAttribute(llvm::Attribute::Hot);
2787 if (TargetDecl->
hasAttr<NoDuplicateAttr>())
2788 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
2789 if (TargetDecl->
hasAttr<ConvergentAttr>())
2790 FuncAttrs.addAttribute(llvm::Attribute::Convergent);
2792 if (
const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2795 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
2799 Fn->getDeclName().isAnyOperatorNew()) {
2800 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2803 FuncAttrs.addMemoryAttr(
2804 llvm::MemoryEffects::inaccessibleOrErrnoMemOnly(
2805 llvm::ModRefInfo::ModRef, llvm::ModRefInfo::Mod));
2809 const bool IsVirtualCall = MD && MD->
isVirtual();
2812 if (!(AttrOnCallSite && IsVirtualCall)) {
2813 if (Fn->isNoReturn())
2814 FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
2815 NBA = Fn->getAttr<NoBuiltinAttr>();
2822 if (AttrOnCallSite && TargetDecl->
hasAttr<NoMergeAttr>())
2823 FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
2827 if (TargetDecl->
hasAttr<ConstAttr>()) {
2828 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::none());
2829 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2832 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2833 MemAttrForPtrArgs = llvm::Attribute::ReadNone;
2834 }
else if (TargetDecl->
hasAttr<PureAttr>()) {
2835 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::readOnly());
2836 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2838 FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
2839 MemAttrForPtrArgs = llvm::Attribute::ReadOnly;
2840 }
else if (TargetDecl->
hasAttr<NoAliasAttr>()) {
2841 FuncAttrs.addMemoryAttr(llvm::MemoryEffects::inaccessibleOrArgMemOnly());
2842 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
2844 if (
const auto *RA = TargetDecl->
getAttr<RestrictAttr>();
2845 RA && RA->getDeallocator() ==
nullptr)
2846 RetAttrs.addAttribute(llvm::Attribute::NoAlias);
2847 if (TargetDecl->
hasAttr<ReturnsNonNullAttr>() &&
2848 !CodeGenOpts.NullPointerIsValid)
2849 RetAttrs.addAttribute(llvm::Attribute::NonNull);
2850 if (TargetDecl->
hasAttr<AnyX86NoCallerSavedRegistersAttr>())
2851 FuncAttrs.addAttribute(
"no_caller_saved_registers");
2852 if (TargetDecl->
hasAttr<AnyX86NoCfCheckAttr>())
2853 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
2854 if (TargetDecl->
hasAttr<LeafAttr>())
2855 FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
2856 if (TargetDecl->
hasAttr<BPFFastCallAttr>())
2857 FuncAttrs.addAttribute(
"bpf_fastcall");
2859 HasOptnone = TargetDecl->
hasAttr<OptimizeNoneAttr>();
2860 if (
auto *AllocSize = TargetDecl->
getAttr<AllocSizeAttr>()) {
2861 std::optional<unsigned> NumElemsParam;
2862 if (AllocSize->getNumElemsParam().isValid())
2863 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
2864 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
2874 FuncAttrs.addAttribute(
"uniform-work-group-size");
2876 if (TargetDecl->
hasAttr<ArmLocallyStreamingAttr>())
2877 FuncAttrs.addAttribute(
"aarch64_pstate_sm_body");
2879 if (
auto *ModularFormat = TargetDecl->
getAttr<ModularFormatAttr>()) {
2880 FormatAttr *Format = TargetDecl->
getAttr<FormatAttr>();
2881 StringRef
Type = Format->getType()->getName();
2882 std::string FormatIdx = std::to_string(Format->getFormatIdx());
2883 std::string FirstArg = std::to_string(Format->getFirstArg());
2885 Type, FormatIdx, FirstArg,
2886 ModularFormat->getModularImplFn()->getName(),
2887 ModularFormat->getImplName()};
2888 llvm::append_range(Args, ModularFormat->aspects());
2889 FuncAttrs.addAttribute(
"modular-format", llvm::join(Args,
","));
2902 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
2907 if (TargetDecl->
hasAttr<NoSpeculativeLoadHardeningAttr>())
2908 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
2909 if (TargetDecl->
hasAttr<SpeculativeLoadHardeningAttr>())
2910 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
2911 if (TargetDecl->
hasAttr<NoSplitStackAttr>())
2912 FuncAttrs.removeAttribute(
"split-stack");
2913 if (TargetDecl->
hasAttr<ZeroCallUsedRegsAttr>()) {
2916 TargetDecl->
getAttr<ZeroCallUsedRegsAttr>()->getZeroCallUsedRegs();
2917 FuncAttrs.removeAttribute(
"zero-call-used-regs");
2918 FuncAttrs.addAttribute(
2919 "zero-call-used-regs",
2920 ZeroCallUsedRegsAttr::ConvertZeroCallUsedRegsKindToStr(Kind));
2927 if (CodeGenOpts.NoPLT) {
2928 if (
auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
2929 if (!Fn->isDefined() && !AttrOnCallSite) {
2930 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
2935 if (TargetDecl->
hasAttr<NoConvergentAttr>())
2936 FuncAttrs.removeAttribute(llvm::Attribute::Convergent);
2941 if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
2942 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
2943 if (!FD->isExternallyVisible())
2944 FuncAttrs.addAttribute(
"sample-profile-suffix-elision-policy",
2951 if (!AttrOnCallSite) {
2952 if (TargetDecl && TargetDecl->
hasAttr<CmseNSEntryAttr>())
2953 FuncAttrs.addAttribute(
"cmse_nonsecure_entry");
2956 auto shouldDisableTailCalls = [&] {
2958 if (CodeGenOpts.DisableTailCalls)
2964 if (TargetDecl->
hasAttr<DisableTailCallsAttr>() ||
2965 TargetDecl->
hasAttr<AnyX86InterruptAttr>())
2968 if (CodeGenOpts.NoEscapingBlockTailCalls) {
2969 if (
const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
2970 if (!BD->doesNotEscape())
2976 if (shouldDisableTailCalls())
2977 FuncAttrs.addAttribute(
"disable-tail-calls",
"true");
2982 static const llvm::StringSet<> ReturnsTwiceFn{
2983 "_setjmpex",
"setjmp",
"_setjmp",
"vfork",
2984 "sigsetjmp",
"__sigsetjmp",
"savectx",
"getcontext"};
2985 if (ReturnsTwiceFn.contains(Name))
2986 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
2990 GetCPUAndFeaturesAttributes(CalleeInfo.
getCalleeDecl(), FuncAttrs);
2993 if (!MSHotPatchFunctions.empty()) {
2994 bool IsHotPatched = llvm::binary_search(MSHotPatchFunctions, Name);
2996 FuncAttrs.addAttribute(
"marked_for_windows_hot_patching");
3001 if (CodeGenOpts.isLoaderReplaceableFunctionName(Name))
3002 FuncAttrs.addAttribute(
"loader-replaceable");
3005 ClangToLLVMArgMapping IRFunctionArgs(
getContext(), FI);
3012 if (CodeGenOpts.EnableNoundefAttrs &&
3016 RetAttrs.addAttribute(llvm::Attribute::NoUndef);
3022 RetAttrs.addAttribute(llvm::Attribute::SExt);
3024 RetAttrs.addAttribute(llvm::Attribute::ZExt);
3026 RetAttrs.addAttribute(llvm::Attribute::NoExt);
3031 RetAttrs.addAttribute(llvm::Attribute::InReg);
3043 AddPotentialArgAccess();
3052 llvm_unreachable(
"Invalid ABI kind for return argument");
3060 RetAttrs.addDereferenceableAttr(
3062 if (
getTypes().getTargetAddressSpace(PTy) == 0 &&
3063 !CodeGenOpts.NullPointerIsValid)
3064 RetAttrs.addAttribute(llvm::Attribute::NonNull);
3066 llvm::Align Alignment =
3068 RetAttrs.addAlignmentAttr(Alignment);
3073 bool hasUsedSRet =
false;
3075 for (
unsigned I = 0; I < IRFunctionArgs.totalIRArgs(); ++I)
3079 if (IRFunctionArgs.hasSRetArg()) {
3080 llvm::AttrBuilder &SRETAttrs = ArgAttrs[IRFunctionArgs.getSRetArgNo()];
3081 SRETAttrs.addStructRetAttr(
getTypes().ConvertTypeForMem(RetTy));
3082 SRETAttrs.addAttribute(llvm::Attribute::Writable);
3083 SRETAttrs.addAttribute(llvm::Attribute::DeadOnUnwind);
3086 SRETAttrs.addAttribute(llvm::Attribute::InReg);
3091 if (IRFunctionArgs.hasInallocaArg()) {
3092 ArgAttrs[IRFunctionArgs.getInallocaArgNo()].addInAllocaAttr(
3102 auto IRArgs = IRFunctionArgs.getIRArgs(0);
3104 assert(IRArgs.second == 1 &&
"Expected only a single `this` pointer.");
3106 llvm::AttrBuilder &Attrs = ArgAttrs[IRArgs.first];
3111 if (!CodeGenOpts.NullPointerIsValid &&
3113 Attrs.addAttribute(llvm::Attribute::NonNull);
3114 Attrs.addDereferenceableAttr(ThisSz);
3120 Attrs.addDereferenceableOrNullAttr(ThisSz);
3123 llvm::Align Alignment =
3127 Attrs.addAlignmentAttr(Alignment);
3129 const auto *DD = dyn_cast_if_present<CXXDestructorDecl>(
3143 CodeGenOpts.StrictLifetimes) {
3145 dyn_cast<CXXRecordDecl>(DD->getDeclContext());
3149 Attrs.addDeadOnReturnAttr(llvm::DeadOnReturnInfo(
3150 Context.getASTRecordLayout(ClassDecl).getDataSize().getQuantity()));
3156 I != E; ++I, ++ArgNo) {
3162 if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
3164 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)].addAttribute(
3165 llvm::Attribute::InReg);
3170 if (CodeGenOpts.EnableNoundefAttrs &&
3172 Attrs.addAttribute(llvm::Attribute::NoUndef);
3181 Attrs.addAttribute(llvm::Attribute::SExt);
3183 Attrs.addAttribute(llvm::Attribute::ZExt);
3185 Attrs.addAttribute(llvm::Attribute::NoExt);
3190 Attrs.addAttribute(llvm::Attribute::Nest);
3192 Attrs.addAttribute(llvm::Attribute::InReg);
3193 Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.
getDirectAlign()));
3200 "Pass-by-value parameter has incomplete definition?");
3203 Attrs.addAttribute(llvm::Attribute::InReg);
3215 Attrs.addByValAttr(
getTypes().ConvertTypeForMem(ParamType));
3223 Attrs.addDeadOnReturnAttr(llvm::DeadOnReturnInfo());
3228 if (CodeGenOpts.PassByValueIsNoAlias &&
Decl &&
3229 Decl->getArgPassingRestrictions() ==
3233 Attrs.addAttribute(llvm::Attribute::NoAlias);
3263 Attrs.addAttribute(llvm::Attribute::NoFreeObj);
3264 Attrs.addDereferenceableAttr(
3265 Context.getTypeSizeInChars(ParamType).getQuantity());
3269 AddPotentialArgAccess();
3274 Attrs.addByRefAttr(
getTypes().ConvertTypeForMem(ParamType));
3285 AddPotentialArgAccess();
3293 if (
getTypes().getTargetAddressSpace(PTy) == 0 &&
3294 !CodeGenOpts.NullPointerIsValid)
3295 Attrs.addAttribute(llvm::Attribute::NonNull);
3297 llvm::Align Alignment =
3299 Attrs.addAlignmentAttr(Alignment);
3308 DeviceKernelAttr::isOpenCLSpelling(
3309 TargetDecl->
getAttr<DeviceKernelAttr>()) &&
3313 llvm::Align Alignment =
3315 Attrs.addAlignmentAttr(Alignment);
3322 Attrs.addAttribute(llvm::Attribute::NoAlias);
3331 Attrs.addStructRetAttr(
getTypes().ConvertTypeForMem(ParamType));
3336 Attrs.addAttribute(llvm::Attribute::NoAlias);
3340 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
3341 auto info =
getContext().getTypeInfoInChars(PTy);
3342 Attrs.addDereferenceableAttr(info.Width.getQuantity());
3343 Attrs.addAlignmentAttr(info.Align.getAsAlign());
3349 Attrs.addAttribute(llvm::Attribute::SwiftError);
3353 Attrs.addAttribute(llvm::Attribute::SwiftSelf);
3357 Attrs.addAttribute(llvm::Attribute::SwiftAsync);
3362 Attrs.addCapturesAttr(
3363 llvm::CaptureInfo(llvm::CaptureComponents::Address));
3365 if (Attrs.hasAttributes()) {
3366 unsigned FirstIRArg, NumIRArgs;
3367 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3368 for (
unsigned i = 0; i < NumIRArgs; i++)
3369 ArgAttrs[FirstIRArg + i].merge(Attrs);
3377 AddPotentialArgAccess();
3380 if (AddedPotentialArgAccess && MemAttrForPtrArgs) {
3384 I != E; ++I, ++ArgNo) {
3385 if (I->info.isDirect() || I->info.isExpand() ||
3386 I->info.isCoerceAndExpand()) {
3387 unsigned FirstIRArg, NumIRArgs;
3388 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3389 for (
unsigned i = FirstIRArg; i < FirstIRArg + NumIRArgs; ++i) {
3396 if (i < FunctionType->getNumParams() &&
3398 ArgAttrs[i].addAttribute(*MemAttrForPtrArgs);
3406 for (
const llvm::AttrBuilder &Attrs : ArgAttrs)
3407 ArgAttrSets.push_back(llvm::AttributeSet::get(
getLLVMContext(), Attrs));
3409 AttrList = llvm::AttributeList::get(
3411 llvm::AttributeSet::get(
getLLVMContext(), RetAttrs), ArgAttrSets);
3418 llvm::Value *value) {
3419 llvm::Type *varType = CGF.
ConvertType(var->getType());
3423 if (value->getType() == varType)
3426 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) &&
3427 "unexpected promotion type");
3430 return CGF.
Builder.CreateTrunc(value, varType,
"arg.unpromote");
3432 return CGF.
Builder.CreateFPCast(value, varType,
"arg.unpromote");
3438 QualType ArgType,
unsigned ArgNo) {
3446 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
3450 if (
auto ParmNNAttr = PVD->
getAttr<NonNullAttr>())
3457 if (NNAttr->isNonNull(ArgNo))
3464struct CopyBackSwiftError final : EHScopeStack::Cleanup {
3467 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(
arg) {}
3468 void Emit(CodeGenFunction &CGF, Flags flags)
override {
3487 if (FD->hasImplicitReturnZero()) {
3488 QualType RetTy = FD->getReturnType().getUnqualifiedType();
3489 llvm::Type *LLVMTy =
CGM.getTypes().ConvertType(RetTy);
3490 llvm::Constant *
Zero = llvm::Constant::getNullValue(LLVMTy);
3498 ClangToLLVMArgMapping IRFunctionArgs(
CGM.getContext(), FI);
3499 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
3504 if (IRFunctionArgs.hasInallocaArg())
3505 ArgStruct =
Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
3509 if (IRFunctionArgs.hasSRetArg()) {
3510 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
3511 AI->setName(
"agg.result");
3512 AI->addAttr(llvm::Attribute::NoAlias);
3519 ArgVals.reserve(Args.size());
3525 assert(FI.
arg_size() == Args.size() &&
3526 "Mismatch between function signature & arguments.");
3529 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); i != e;
3530 ++i, ++info_it, ++ArgNo) {
3543 unsigned FirstIRArg, NumIRArgs;
3544 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
3548 assert(NumIRArgs == 0);
3561 assert(NumIRArgs == 1);
3584 llvm::ConstantInt::get(
IntPtrTy, Size.getQuantity()));
3585 ParamAddr = AlignedTemp;
3602 auto AI = Fn->getArg(FirstIRArg);
3610 assert(NumIRArgs == 1);
3612 if (
const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
3615 PVD->getFunctionScopeIndex()) &&
3616 !
CGM.getCodeGenOpts().NullPointerIsValid)
3617 AI->addAttr(llvm::Attribute::NonNull);
3619 QualType OTy = PVD->getOriginalType();
3620 if (
const auto *ArrTy =
getContext().getAsConstantArrayType(OTy)) {
3626 QualType ETy = ArrTy->getElementType();
3627 llvm::Align Alignment =
3628 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
3630 .addAlignmentAttr(Alignment));
3631 uint64_t ArrSize = ArrTy->getZExtSize();
3635 Attrs.addDereferenceableAttr(
3636 getContext().getTypeSizeInChars(ETy).getQuantity() *
3638 AI->addAttrs(Attrs);
3639 }
else if (
getContext().getTargetInfo().getNullPointerValue(
3641 !
CGM.getCodeGenOpts().NullPointerIsValid) {
3642 AI->addAttr(llvm::Attribute::NonNull);
3645 }
else if (
const auto *ArrTy =
3651 QualType ETy = ArrTy->getElementType();
3652 llvm::Align Alignment =
3653 CGM.getNaturalTypeAlignment(ETy).getAsAlign();
3655 .addAlignmentAttr(Alignment));
3656 if (!
getTypes().getTargetAddressSpace(ETy) &&
3657 !
CGM.getCodeGenOpts().NullPointerIsValid)
3658 AI->addAttr(llvm::Attribute::NonNull);
3663 const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
3666 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
3667 if (AVAttr && !
SanOpts.has(SanitizerKind::Alignment)) {
3671 llvm::ConstantInt *AlignmentCI =
3673 uint64_t AlignmentInt =
3674 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
3675 if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
3676 AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
3678 .addAlignmentAttr(llvm::Align(AlignmentInt)));
3685 AI->addAttr(llvm::Attribute::NoAlias);
3693 assert(NumIRArgs == 1);
3697 llvm::Value *
V = AI;
3705 V, pointeeTy,
getContext().getTypeAlignInChars(pointeeTy));
3706 llvm::Value *incomingErrorValue =
Builder.CreateLoad(arg);
3707 Builder.CreateStore(incomingErrorValue, temp);
3728 if (
V->getType() != LTy)
3739 if (
auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(
ConvertType(Ty))) {
3740 llvm::Value *ArgVal = Fn->getArg(FirstIRArg);
3741 if (
auto *VecTyFrom =
3742 dyn_cast<llvm::ScalableVectorType>(ArgVal->getType())) {
3744 *
this, VecTyTo, VecTyFrom, ArgVal, Arg->
getName());
3746 assert(NumIRArgs == 1);
3753 llvm::StructType *STy =
3764 STy->getNumElements() > 1) {
3765 llvm::TypeSize StructSize =
CGM.getDataLayout().getTypeAllocSize(STy);
3766 llvm::TypeSize PtrElementSize =
3767 CGM.getDataLayout().getTypeAllocSize(Ptr.getElementType());
3768 if (StructSize.isScalable()) {
3769 assert(STy->containsHomogeneousScalableVectorTypes() &&
3770 "ABI only supports structure with homogeneous scalable vector "
3772 assert(StructSize == PtrElementSize &&
3773 "Only allow non-fractional movement of structure with"
3774 "homogeneous scalable vector type");
3775 assert(STy->getNumElements() == NumIRArgs);
3777 llvm::Value *LoadedStructValue = llvm::PoisonValue::get(STy);
3778 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3779 auto *AI = Fn->getArg(FirstIRArg + i);
3780 AI->setName(Arg->
getName() +
".coerce" + Twine(i));
3782 Builder.CreateInsertValue(LoadedStructValue, AI, i);
3785 Builder.CreateStore(LoadedStructValue, Ptr);
3787 uint64_t SrcSize = StructSize.getFixedValue();
3788 uint64_t DstSize = PtrElementSize.getFixedValue();
3791 if (SrcSize <= DstSize) {
3792 AddrToStoreInto = Ptr.withElementType(STy);
3798 assert(STy->getNumElements() == NumIRArgs);
3799 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
3800 auto AI = Fn->getArg(FirstIRArg + i);
3801 AI->setName(Arg->
getName() +
".coerce" + Twine(i));
3803 Builder.CreateStore(AI, EltPtr);
3806 if (SrcSize > DstSize) {
3807 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
3819 assert(NumIRArgs == 1);
3820 auto AI = Fn->getArg(FirstIRArg);
3821 AI->setName(Arg->
getName() +
".coerce");
3824 llvm::TypeSize::getFixed(
3825 getContext().getTypeSizeInChars(Ty).getQuantity() -
3851 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
3855 unsigned argIndex = FirstIRArg;
3856 unsigned unpaddedIndex = 0;
3857 for (
unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
3858 llvm::Type *eltType = coercionType->getElementType(i);
3862 auto eltAddr =
Builder.CreateStructGEP(alloca, i);
3863 llvm::Value *elt = Fn->getArg(argIndex++);
3865 auto paramType = unpaddedStruct
3866 ? unpaddedStruct->getElementType(unpaddedIndex++)
3867 : unpaddedCoercionType;
3869 if (
auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(eltType)) {
3870 if (
auto *VecTyFrom = dyn_cast<llvm::ScalableVectorType>(paramType)) {
3873 *
this, VecTyTo, VecTyFrom, elt, elt->getName());
3874 assert(Extracted &&
"Unexpected scalable to fixed vector coercion");
3877 Builder.CreateStore(elt, eltAddr);
3879 assert(argIndex == FirstIRArg + NumIRArgs);
3892 auto FnArgIter = Fn->arg_begin() + FirstIRArg;
3893 ExpandTypeFromArgs(Ty, LV, FnArgIter);
3894 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
3895 for (
unsigned i = 0, e = NumIRArgs; i != e; ++i) {
3896 auto AI = Fn->getArg(FirstIRArg + i);
3897 AI->setName(Arg->
getName() +
"." + Twine(i));
3903 auto *AI = Fn->getArg(FirstIRArg);
3904 AI->setName(Arg->
getName() +
".target_coerce");
3908 CGM.getABIInfo().createCoercedStore(AI, Ptr, ArgI,
false, *
this);
3922 assert(NumIRArgs == 0);
3935 if (
getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
3936 for (
int I = Args.size() - 1; I >= 0; --I)
3939 for (
unsigned I = 0, E = Args.size(); I != E; ++I)
3945 while (insn->use_empty()) {
3946 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
3952 bitcast->eraseFromParent();
3958 llvm::Value *result) {
3960 llvm::BasicBlock *BB = CGF.
Builder.GetInsertBlock();
3963 if (&BB->back() != result)
3966 llvm::Type *resultType = result->getType();
3975 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
3981 if (generator->getNextNode() != bitcast)
3984 InstsToKill.push_back(bitcast);
3991 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
3995 bool doRetainAutorelease;
3998 doRetainAutorelease =
true;
3999 }
else if (call->getCalledOperand() ==
4001 doRetainAutorelease =
false;
4009 llvm::Instruction *prev = call->getPrevNode();
4012 prev = prev->getPrevNode();
4018 InstsToKill.push_back(prev);
4024 result = call->getArgOperand(0);
4025 InstsToKill.push_back(call);
4029 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
4030 if (!bitcast->hasOneUse())
4032 InstsToKill.push_back(bitcast);
4033 result = bitcast->getOperand(0);
4037 for (
auto *I : InstsToKill)
4038 I->eraseFromParent();
4041 if (doRetainAutorelease)
4045 return CGF.
Builder.CreateBitCast(result, resultType);
4050 llvm::Value *result) {
4053 dyn_cast_or_null<ObjCMethodDecl>(CGF.
CurCodeDecl);
4062 llvm::CallInst *retainCall = dyn_cast<llvm::CallInst>(result);
4063 if (!retainCall || retainCall->getCalledOperand() !=
4068 llvm::Value *retainedValue = retainCall->getArgOperand(0);
4069 llvm::LoadInst *load =
4070 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
4071 if (!load || load->isAtomic() || load->isVolatile() ||
4078 llvm::Type *resultType = result->getType();
4080 assert(retainCall->use_empty());
4081 retainCall->eraseFromParent();
4084 return CGF.
Builder.CreateBitCast(load, resultType);
4091 llvm::Value *result) {
4114 auto GetStoreIfValid = [&CGF,
4115 ReturnValuePtr](llvm::User *
U) -> llvm::StoreInst * {
4116 auto *SI = dyn_cast<llvm::StoreInst>(
U);
4117 if (!SI || SI->getPointerOperand() != ReturnValuePtr ||
4123 assert(!SI->isAtomic() &&
4131 if (!ReturnValuePtr->hasOneUse()) {
4132 llvm::BasicBlock *IP = CGF.
Builder.GetInsertBlock();
4138 const llvm::Instruction *LoadIntoFakeUse =
nullptr;
4139 for (llvm::Instruction &I : llvm::reverse(*IP)) {
4143 if (LoadIntoFakeUse == &I)
4147 if (
auto *II = dyn_cast<llvm::IntrinsicInst>(&I)) {
4148 if (II->getIntrinsicID() == llvm::Intrinsic::lifetime_end)
4151 if (II->getIntrinsicID() == llvm::Intrinsic::fake_use) {
4152 LoadIntoFakeUse = dyn_cast<llvm::Instruction>(II->getArgOperand(0));
4156 return GetStoreIfValid(&I);
4161 llvm::StoreInst *store = GetStoreIfValid(ReturnValuePtr->user_back());
4167 llvm::BasicBlock *StoreBB = store->getParent();
4168 llvm::BasicBlock *IP = CGF.
Builder.GetInsertBlock();
4170 while (IP != StoreBB) {
4171 if (!SeenBBs.insert(IP).second || !(IP = IP->getSinglePredecessor()))
4187 int BitWidth,
int CharWidth) {
4188 assert(CharWidth <= 64);
4189 assert(
static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
4192 if (BitOffset >= CharWidth) {
4193 Pos += BitOffset / CharWidth;
4194 BitOffset = BitOffset % CharWidth;
4197 const uint64_t
Used = (uint64_t(1) << CharWidth) - 1;
4198 if (BitOffset + BitWidth >= CharWidth) {
4199 Bits[Pos++] |= (
Used << BitOffset) &
Used;
4200 BitWidth -= CharWidth - BitOffset;
4204 while (BitWidth >= CharWidth) {
4206 BitWidth -= CharWidth;
4210 Bits[Pos++] |= (
Used >> (CharWidth - BitWidth)) << BitOffset;
4218 int StorageSize,
int BitOffset,
int BitWidth,
4219 int CharWidth,
bool BigEndian) {
4222 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
4225 std::reverse(TmpBits.begin(), TmpBits.end());
4227 for (uint64_t
V : TmpBits)
4228 Bits[StorageOffset++] |=
V;
4231static void setUsedBits(CodeGenModule &, QualType,
int,
4232 SmallVectorImpl<uint64_t> &);
4274 QualType ETy = Context.getBaseElementType(ATy);
4275 int Size = Context.getTypeSizeInChars(ETy).getQuantity();
4279 for (
int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
4280 auto Src = TmpBits.begin();
4281 auto Dst = Bits.begin() + Offset + I * Size;
4282 for (
int J = 0; J < Size; ++J)
4295 if (
const auto *ATy = Context.getAsConstantArrayType(QTy))
4298 int Size = Context.getTypeSizeInChars(QTy).getQuantity();
4302 std::fill_n(Bits.begin() + Offset, Size,
4303 (uint64_t(1) << Context.getCharWidth()) - 1);
4307 int Pos,
int Size,
int CharWidth,
4312 for (
auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
4314 Mask = (Mask << CharWidth) | *P;
4316 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
4318 Mask = (Mask << CharWidth) | *--P;
4327 llvm::IntegerType *ITy,
4329 assert(Src->getType() == ITy);
4330 assert(ITy->getScalarSizeInBits() <= 64);
4332 const llvm::DataLayout &DataLayout =
CGM.getDataLayout();
4333 int Size = DataLayout.getTypeStoreSize(ITy);
4337 int CharWidth =
CGM.getContext().getCharWidth();
4341 return Builder.CreateAnd(Src, Mask,
"cmse.clear");
4347 llvm::ArrayType *ATy,
4349 const llvm::DataLayout &DataLayout =
CGM.getDataLayout();
4350 int Size = DataLayout.getTypeStoreSize(ATy);
4355 int CharWidth =
CGM.getContext().getCharWidth();
4357 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
4359 llvm::Value *R = llvm::PoisonValue::get(ATy);
4360 for (
int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
4362 DataLayout.isBigEndian());
4363 MaskIndex += CharsPerElt;
4364 llvm::Value *T0 =
Builder.CreateExtractValue(Src, I);
4365 llvm::Value *T1 =
Builder.CreateAnd(T0, Mask,
"cmse.clear");
4366 R =
Builder.CreateInsertValue(R, T1, I);
4374 uint64_t RetKeyInstructionsSourceAtom) {
4389 auto *I =
Builder.CreateRetVoid();
4390 if (RetKeyInstructionsSourceAtom)
4397 llvm::DebugLoc RetDbgLoc;
4398 llvm::Value *RV =
nullptr;
4408 llvm::Function::arg_iterator EI =
CurFn->arg_end();
4410 llvm::Value *ArgStruct = &*EI;
4411 llvm::Value *SRet =
Builder.CreateStructGEP(
4420 auto AI =
CurFn->arg_begin();
4438 CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
4465 RetDbgLoc = SI->getDebugLoc();
4467 RV = SI->getValueOperand();
4468 SI->eraseFromParent();
4491 if (
auto *FD = dyn_cast<FunctionDecl>(
CurCodeDecl))
4492 RT = FD->getReturnType();
4493 else if (
auto *MD = dyn_cast<ObjCMethodDecl>(
CurCodeDecl))
4494 RT = MD->getReturnType();
4496 RT =
BlockInfo->BlockExpression->getFunctionType()->getReturnType();
4498 llvm_unreachable(
"Unexpected function/method type");
4514 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
4519 unsigned unpaddedIndex = 0;
4520 for (
unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
4521 auto coercedEltType = coercionType->getElementType(i);
4525 auto eltAddr =
Builder.CreateStructGEP(addr, i);
4528 unpaddedStruct ? unpaddedStruct->getElementType(unpaddedIndex++)
4529 : unpaddedCoercionType,
4531 results.push_back(elt);
4535 if (results.size() == 1) {
4543 RV = llvm::PoisonValue::get(returnType);
4544 for (
unsigned i = 0, e = results.size(); i != e; ++i) {
4545 RV =
Builder.CreateInsertValue(RV, results[i], i);
4552 RV =
CGM.getABIInfo().createCoercedLoad(
V, RetAI, *
this);
4557 llvm_unreachable(
"Invalid ABI kind for return argument");
4560 llvm::Instruction *Ret;
4566 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
4573 Ret =
Builder.CreateRetVoid();
4577 Ret->setDebugLoc(std::move(RetDbgLoc));
4579 llvm::Value *Backup = RV ? Ret->getOperand(0) :
nullptr;
4580 if (RetKeyInstructionsSourceAtom)
4596 ReturnsNonNullAttr *RetNNAttr =
nullptr;
4597 if (
SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
4598 RetNNAttr =
CurCodeDecl->getAttr<ReturnsNonNullAttr>();
4600 if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
4608 assert(!requiresReturnValueNullabilityCheck() &&
4609 "Cannot check nullability and the nonnull attribute");
4610 AttrLoc = RetNNAttr->getLocation();
4611 CheckKind = SanitizerKind::SO_ReturnsNonnullAttribute;
4612 Handler = SanitizerHandler::NonnullReturn;
4614 if (
auto *DD = dyn_cast<DeclaratorDecl>(
CurCodeDecl))
4615 if (
auto *TSI = DD->getTypeSourceInfo())
4617 AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
4618 CheckKind = SanitizerKind::SO_NullabilityReturn;
4619 Handler = SanitizerHandler::NullabilityReturn;
4628 llvm::Value *SLocPtr =
Builder.CreateLoad(ReturnLocation,
"return.sloc.load");
4629 llvm::Value *CanNullCheck =
Builder.CreateIsNotNull(SLocPtr);
4630 if (requiresReturnValueNullabilityCheck())
4632 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
4633 Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
4637 llvm::Value *Cond =
Builder.CreateIsNotNull(RV);
4639 llvm::Value *DynamicData[] = {SLocPtr};
4640 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
4659 llvm::Type *IRPtrTy = llvm::PointerType::getUnqual(CGF.
getLLVMContext());
4660 llvm::Value *Placeholder = llvm::PoisonValue::get(IRPtrTy);
4685 if (
type->isReferenceType()) {
4694 param->
hasAttr<NSConsumedAttr>() &&
type->isObjCRetainableType()) {
4695 llvm::Value *ptr =
Builder.CreateLoad(local);
4698 Builder.CreateStore(null, local);
4709 type->castAsRecordDecl()->isParamDestroyedInCallee() &&
4713 assert(cleanup.isValid() &&
4714 "cleanup for callee-destructed param not recorded");
4716 llvm::Instruction *isActive =
Builder.CreateUnreachable();
4722 return llvm::isa_and_nonnull<llvm::ConstantPointerNull>(addr);
4732 const LValue &srcLV = writeback.
Source;
4733 Address srcAddr = srcLV.getAddress();
4735 "shouldn't have writeback for provably null argument");
4743 llvm::BasicBlock *contBB =
nullptr;
4749 if (!provablyNonNull) {
4754 CGF.
Builder.CreateCondBr(isNull, contBB, writebackBB);
4763 "icr.writeback-cast");
4772 if (writeback.
ToUse) {
4797 if (!provablyNonNull)
4806 for (
const auto &I : llvm::reverse(Cleanups)) {
4808 I.IsActiveIP->eraseFromParent();
4814 if (uop->getOpcode() == UO_AddrOf)
4815 return uop->getSubExpr();
4840 Address srcAddr = srcLV.getAddress();
4845 llvm::PointerType *destType =
4847 llvm::Type *destElemType =
4874 llvm::BasicBlock *contBB =
nullptr;
4875 llvm::BasicBlock *originBB =
nullptr;
4878 llvm::Value *finalArgument;
4882 if (provablyNonNull) {
4887 finalArgument = CGF.
Builder.CreateSelect(
4888 isNull, llvm::ConstantPointerNull::get(destType),
4894 originBB = CGF.
Builder.GetInsertBlock();
4897 CGF.
Builder.CreateCondBr(isNull, contBB, copyBB);
4899 condEval.
begin(CGF);
4903 llvm::Value *valueToUse =
nullptr;
4911 src = CGF.
Builder.CreateBitCast(src, destElemType,
"icr.cast");
4928 if (shouldCopy && !provablyNonNull) {
4929 llvm::BasicBlock *copyBB = CGF.
Builder.GetInsertBlock();
4934 llvm::PHINode *phiToUse =
4935 CGF.
Builder.CreatePHI(valueToUse->getType(), 2,
"icr.to-use");
4936 phiToUse->addIncoming(valueToUse, copyBB);
4937 phiToUse->addIncoming(llvm::PoisonValue::get(valueToUse->getType()),
4939 valueToUse = phiToUse;
4953 StackBase = CGF.
Builder.CreateStackSave(
"inalloca.save");
4959 CGF.
Builder.CreateStackRestore(StackBase);
4966 if (!AC.
getDecl() || !(
SanOpts.has(SanitizerKind::NonnullAttribute) ||
4967 SanOpts.has(SanitizerKind::NullabilityArg)))
4972 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
4975 const NonNullAttr *NNAttr =
nullptr;
4976 if (
SanOpts.has(SanitizerKind::NonnullAttribute))
4979 bool CanCheckNullability =
false;
4980 if (
SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD &&
4981 !PVD->getType()->isRecordType()) {
4982 auto Nullability = PVD->getType()->getNullability();
4983 CanCheckNullability = Nullability &&
4985 PVD->getTypeSourceInfo();
4988 if (!NNAttr && !CanCheckNullability)
4995 AttrLoc = NNAttr->getLocation();
4996 CheckKind = SanitizerKind::SO_NonnullAttribute;
4997 Handler = SanitizerHandler::NonnullArg;
4999 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
5000 CheckKind = SanitizerKind::SO_NullabilityArg;
5001 Handler = SanitizerHandler::NullabilityArg;
5006 llvm::Constant *StaticData[] = {
5009 llvm::ConstantInt::get(
Int32Ty, ArgNo + 1),
5011 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, {});
5017 if (!AC.
getDecl() || !(
SanOpts.has(SanitizerKind::NonnullAttribute) ||
5018 SanOpts.has(SanitizerKind::NullabilityArg)))
5037 return llvm::any_of(ArgTypes, [&](
QualType Ty) {
5048 return classDecl->getTypeParamListAsWritten();
5052 return catDecl->getTypeParamList();
5062 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
5066 assert((ParamsToSkip == 0 ||
Prototype.P) &&
5067 "Can't skip parameters if type info is not provided");
5077 bool IsVariadic =
false;
5079 const auto *MD = dyn_cast<const ObjCMethodDecl *>(
Prototype.P);
5081 IsVariadic = MD->isVariadic();
5083 MD,
CGM.getTarget().getTriple().isOSWindows());
5084 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
5085 MD->param_type_end());
5088 IsVariadic = FPT->isVariadic();
5089 ExplicitCC = FPT->getExtInfo().getCC();
5090 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
5091 FPT->param_type_end());
5099 assert(Arg != ArgRange.end() &&
"Running over edge of argument list!");
5101 QualType ArgTy = (*Arg)->getType();
5102 if (
const auto *OBT = ParamTy->
getAs<OverflowBehaviorType>())
5103 ParamTy = OBT->getUnderlyingType();
5104 if (
const auto *OBT = ArgTy->
getAs<OverflowBehaviorType>())
5105 ArgTy = OBT->getUnderlyingType();
5108 getContext().getCanonicalType(ParamTy).getTypePtr() ==
5109 getContext().getCanonicalType(ArgTy).getTypePtr()) &&
5110 "type mismatch in call argument!");
5116 assert((Arg == ArgRange.end() || IsVariadic) &&
5117 "Extra arguments in non-variadic function!");
5122 for (
auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
5123 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
5124 assert((
int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
5132 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
5136 auto MaybeEmitImplicitObjectSize = [&](
unsigned I,
const Expr *Arg,
5145 auto SizeTy = Context.getSizeType();
5147 assert(EmittedArg.getScalarVal() &&
"We emitted nothing for the arg?");
5148 llvm::Value *
V = evaluateOrEmitBuiltinObjectSize(
5149 Arg, PS->getType(),
T, EmittedArg.getScalarVal(), PS->isDynamic());
5154 std::swap(Args.back(), *(&Args.back() - 1));
5160 "inalloca only supported on x86");
5165 size_t CallArgsStart = Args.size();
5166 for (
unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
5167 unsigned Idx = LeftToRight ? I : E - I - 1;
5169 unsigned InitialArgSize = Args.size();
5173 getContext().hasSameUnqualifiedType((*Arg)->getType(),
5177 "Argument and parameter types don't match");
5181 assert(InitialArgSize + 1 == Args.size() &&
5182 "The code below depends on only adding one arg per EmitCallArg");
5183 (void)InitialArgSize;
5186 if (!Args.back().hasLValue()) {
5187 RValue RVArg = Args.back().getKnownRValue();
5189 ParamsToSkip + Idx);
5193 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
5200 std::reverse(Args.begin() + CallArgsStart, Args.end());
5209struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
5219 assert(!Dtor->isTrivial());
5242 if (!HasLV &&
RV.isScalar())
5244 else if (!HasLV &&
RV.isComplex())
5247 auto Addr = HasLV ?
LV.getAddress() :
RV.getAggregateAddress();
5251 HasLV ?
LV.isVolatileQualified()
5252 :
RV.isVolatileQualified());
5264 std::optional<DisableDebugLocationUpdates> Dis;
5268 dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
5282 "reference binding to unmaterialized r-value!");
5294 if (
type->isRecordType() &&
5295 type->castAsRecordDecl()->isParamDestroyedInCallee()) {
5302 bool DestroyedInCallee =
true, NeedsCleanup =
true;
5303 if (
const auto *RD =
type->getAsCXXRecordDecl())
5304 DestroyedInCallee = RD->hasNonTrivialDestructor();
5306 NeedsCleanup =
type.isDestructedType();
5308 if (DestroyedInCallee)
5315 if (DestroyedInCallee && NeedsCleanup) {
5322 llvm::Instruction *IsActive =
5329 if (HasAggregateEvalKind) {
5330 auto *ICE = dyn_cast<ImplicitCastExpr>(E);
5331 if (ICE && ICE->getCastKind() == CK_LValueToRValue &&
5332 ICE->getSubExpr()->getType().getAddressSpace() !=
5334 !
type->isArrayParameterType() && !
type.isNonTrivialToPrimitiveCopy()) {
5345QualType CodeGenFunction::getVarArgType(
const Expr *Arg) {
5349 if (!getTarget().
getTriple().isOSWindows())
5353 getContext().getTypeSize(Arg->
getType()) <
5357 return getContext().getIntPtrType();
5365void CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
5366 if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
5367 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
5368 Inst->setMetadata(
"clang.arc.no_objc_arc_exceptions",
5369 CGM.getNoObjCARCExceptionsMetadata());
5375 const llvm::Twine &name) {
5376 return EmitNounwindRuntimeCall(callee, ArrayRef<llvm::Value *>(), name);
5382 ArrayRef<Address> args,
5383 const llvm::Twine &name) {
5384 SmallVector<llvm::Value *, 3> values;
5385 for (
auto arg : args)
5386 values.push_back(
arg.emitRawPointer(*
this));
5387 return EmitNounwindRuntimeCall(callee, values, name);
5392 ArrayRef<llvm::Value *> args,
5393 const llvm::Twine &name) {
5394 llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
5395 call->setDoesNotThrow();
5402 const llvm::Twine &name) {
5403 return EmitRuntimeCall(callee, {},
name);
5408SmallVector<llvm::OperandBundleDef, 1>
5417 if (
auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts())) {
5418 if (CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) {
5419 auto IID = CalleeFn->getIntrinsicID();
5420 if (!llvm::IntrinsicInst::mayLowerToFunctionCall(IID))
5433 const llvm::Twine &name) {
5434 llvm::CallInst *call = Builder.CreateCall(
5435 callee, args, getBundlesForFunclet(callee.getCallee()), name);
5436 call->setCallingConv(getRuntimeCC());
5438 if (CGM.shouldEmitConvergenceTokens() && call->isConvergent())
5444 const llvm::Twine &Name) {
5445 return EmitIntrinsicCall(ID, {}, {}, Name);
5449 ArrayRef<llvm::Value *> Args,
5450 const llvm::Twine &Name) {
5451 return EmitIntrinsicCall(ID, {}, Args, Name);
5455 ArrayRef<llvm::Type *> Types,
5456 ArrayRef<llvm::Value *> Args,
5457 const llvm::Twine &Name) {
5459 llvm::Intrinsic::getOrInsertDeclaration(&CGM.getModule(), ID, Types);
5460 llvm::CallInst *
Call =
5461 Builder.CreateCall(F, Args, getBundlesForFunclet(F), Name);
5462 if (CGM.shouldEmitConvergenceTokens() &&
Call->isConvergent())
5468 ArrayRef<llvm::Value *> Args,
5470 const llvm::Twine &Name) {
5471 SmallVector<llvm::Type *> ArgTys;
5472 ArgTys.reserve(Args.size());
5473 for (llvm::Value *Arg : Args)
5474 ArgTys.push_back(Arg->
getType());
5475 llvm::Function *F = llvm::Intrinsic::getOrInsertDeclaration(
5476 &CGM.getModule(), ID, RetTy, ArgTys);
5477 llvm::CallInst *
Call =
5478 Builder.CreateCall(F, Args, getBundlesForFunclet(F), Name);
5479 if (CGM.shouldEmitConvergenceTokens() &&
Call->isConvergent())
5491 llvm::InvokeInst *invoke =
Builder.CreateInvoke(
5493 invoke->setDoesNotReturn();
5496 llvm::CallInst *call =
Builder.CreateCall(callee, args, BundleList);
5497 call->setDoesNotReturn();
5506 const Twine &name) {
5514 const Twine &name) {
5524 const Twine &Name) {
5529 llvm::CallBase *Inst;
5531 Inst =
Builder.CreateCall(Callee, Args, BundleList, Name);
5534 Inst =
Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
5541 if (
CGM.getLangOpts().ObjCAutoRefCount)
5542 AddObjCARCExceptionMetadata(Inst);
5547void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
5549 DeferredReplacements.push_back(
5550 std::make_pair(llvm::WeakTrackingVH(Old),
New));
5557[[nodiscard]] llvm::AttributeList
5558maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
5559 const llvm::AttributeList &Attrs,
5560 llvm::Align NewAlign) {
5561 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
5562 if (CurAlign >= NewAlign)
5564 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
5565 return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
5566 .addRetAttribute(Ctx, AlignAttr);
5569template <
typename AlignedAttrTy>
class AbstractAssumeAlignedAttrEmitter {
5574 const AlignedAttrTy *AA =
nullptr;
5576 llvm::Value *Alignment =
nullptr;
5577 llvm::ConstantInt *OffsetCI =
nullptr;
5583 AA = FuncDecl->
getAttr<AlignedAttrTy>();
5588 [[nodiscard]] llvm::AttributeList
5589 TryEmitAsCallSiteAttribute(
const llvm::AttributeList &Attrs) {
5590 if (!AA || OffsetCI || CGF.
SanOpts.
has(SanitizerKind::Alignment))
5592 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
5597 if (!AlignmentCI->getValue().isPowerOf2())
5599 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
5602 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
5610 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
5614 AA->getLocation(), Alignment, OffsetCI);
5620class AssumeAlignedAttrEmitter final
5621 :
public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
5623 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_,
const Decl *FuncDecl)
5624 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5629 if (Expr *Offset = AA->getOffset()) {
5631 if (OffsetCI->isNullValue())
5638class AllocAlignAttrEmitter final
5639 :
public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
5641 AllocAlignAttrEmitter(CodeGenFunction &CGF_,
const Decl *FuncDecl,
5642 const CallArgList &CallArgs)
5643 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
5647 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
5656 if (
auto *VT = dyn_cast<llvm::VectorType>(Ty))
5657 return VT->getPrimitiveSizeInBits().getKnownMinValue();
5658 if (
auto *AT = dyn_cast<llvm::ArrayType>(Ty))
5661 unsigned MaxVectorWidth = 0;
5662 if (
auto *ST = dyn_cast<llvm::StructType>(Ty))
5663 for (
auto *I : ST->elements())
5665 return MaxVectorWidth;
5672 llvm::CallBase **callOrInvoke,
bool IsMustTail,
5674 bool IsVirtualFunctionPointerThunk) {
5677 assert(Callee.isOrdinary() || Callee.isVirtual());
5684 llvm::FunctionType *IRFuncTy =
getTypes().GetFunctionType(CallInfo);
5686 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
5687 if (
const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
5694 if ((TargetDecl->
hasAttr<AlwaysInlineAttr>() &&
5695 (TargetDecl->
hasAttr<TargetAttr>() ||
5699 TargetDecl->
hasAttr<TargetAttr>())))
5706 const FunctionDecl *CalleeDecl = dyn_cast_or_null<FunctionDecl>(TargetDecl);
5707 CGM.getTargetCodeGenInfo().checkFunctionCallABI(
CGM, Loc, CallerDecl,
5708 CalleeDecl, CallArgs, RetTy);
5715 if (llvm::StructType *ArgStruct = CallInfo.
getArgStruct()) {
5716 const llvm::DataLayout &DL =
CGM.getDataLayout();
5718 llvm::AllocaInst *AI;
5720 IP = IP->getNextNode();
5721 AI =
new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
"argmem",
5727 AI->setAlignment(Align.getAsAlign());
5728 AI->setUsedWithInAlloca(
true);
5729 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
5730 ArgMemory =
RawAddress(AI, ArgStruct, Align);
5733 ClangToLLVMArgMapping IRFunctionArgs(
CGM.getContext(), CallInfo);
5741 bool NeedSRetLifetimeEnd =
false;
5747 if ((IsVirtualFunctionPointerThunk || IsMustTail) && RetAI.
isIndirect()) {
5749 IRFunctionArgs.getSRetArgNo(),
5757 if (NeedSRetLifetimeEnd)
5758 SRetAlloca = SRetPtr;
5761 if (IRFunctionArgs.hasSRetArg()) {
5774 IRCallArgs[IRFunctionArgs.getSRetArgNo()] =
5792 assert(CallInfo.
arg_size() == CallArgs.size() &&
5793 "Mismatch between function signature & arguments.");
5796 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
5797 I != E; ++I, ++info_it, ++ArgNo) {
5801 if (IRFunctionArgs.hasPaddingArg(ArgNo))
5802 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
5805 unsigned FirstIRArg, NumIRArgs;
5806 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
5808 bool ArgHasMaybeUndefAttr =
5813 assert(NumIRArgs == 0);
5815 if (I->isAggregate()) {
5817 ? I->getKnownLValue().getAddress()
5818 : I->getKnownRValue().getAggregateAddress();
5819 llvm::Instruction *Placeholder =
5824 CGBuilderTy::InsertPoint IP =
Builder.saveIP();
5825 Builder.SetInsertPoint(Placeholder);
5839 deferPlaceholderReplacement(Placeholder,
Addr.getPointer());
5844 I->Ty,
getContext().getTypeAlignInChars(I->Ty),
5845 "indirect-arg-temp");
5846 I->copyInto(*
this,
Addr);
5855 I->copyInto(*
this,
Addr);
5862 assert(NumIRArgs == 1);
5863 if (I->isAggregate()) {
5873 ? I->getKnownLValue().getAddress()
5874 : I->getKnownRValue().getAggregateAddress();
5876 const llvm::DataLayout *TD = &
CGM.getDataLayout();
5878 assert((FirstIRArg >= IRFuncTy->getNumParams() ||
5879 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
5880 TD->getAllocaAddrSpace()) &&
5881 "indirect argument must be in alloca address space");
5883 bool NeedCopy =
false;
5884 if (
Addr.getAlignment() < Align &&
5885 llvm::getOrEnforceKnownAlignment(
Addr.emitRawPointer(*
this),
5889 }
else if (I->hasLValue()) {
5890 auto LV = I->getKnownLValue();
5895 if (!isByValOrRef ||
5896 (LV.getAlignment() <
getContext().getTypeAlignInChars(I->Ty))) {
5900 if (isByValOrRef &&
Addr.getType()->getAddressSpace() !=
5909 auto *
T = llvm::PointerType::get(
CGM.getLLVMContext(),
5917 if (ArgHasMaybeUndefAttr)
5918 Val =
Builder.CreateFreeze(Val);
5919 IRCallArgs[FirstIRArg] = Val;
5922 }
else if (I->getType()->isArrayParameterType()) {
5928 IRCallArgs[FirstIRArg] = I->getKnownRValue().getScalarVal();
5937 if (ArgHasMaybeUndefAttr)
5938 Val =
Builder.CreateFreeze(Val);
5939 IRCallArgs[FirstIRArg] = Val;
5944 CallLifetimeEndAfterCall.emplace_back(AI);
5947 I->copyInto(*
this, AI);
5952 assert(NumIRArgs == 0);
5960 assert(NumIRArgs == 1);
5962 if (!I->isAggregate())
5963 V = I->getKnownRValue().getScalarVal();
5966 I->hasLValue() ? I->getKnownLValue().getAddress()
5967 : I->getKnownRValue().getAggregateAddress());
5973 assert(!swiftErrorTemp.
isValid() &&
"multiple swifterror args");
5977 V, pointeeTy,
getContext().getTypeAlignInChars(pointeeTy));
5984 llvm::Value *errorValue =
Builder.CreateLoad(swiftErrorArg);
5985 Builder.CreateStore(errorValue, swiftErrorTemp);
5990 V->getType()->isIntegerTy())
5997 if (FirstIRArg < IRFuncTy->getNumParams() &&
5998 V->getType() != IRFuncTy->getParamType(FirstIRArg)) {
5999 assert(
V->getType()->isPointerTy() &&
"Only pointers can mismatch!");
6003 if (ArgHasMaybeUndefAttr)
6005 IRCallArgs[FirstIRArg] =
V;
6009 llvm::StructType *STy =
6014 if (!I->isAggregate()) {
6016 I->copyInto(*
this, Src);
6018 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
6019 : I->getKnownRValue().getAggregateAddress();
6029 llvm::TypeSize SrcTypeSize =
6030 CGM.getDataLayout().getTypeAllocSize(SrcTy);
6031 llvm::TypeSize DstTypeSize =
CGM.getDataLayout().getTypeAllocSize(STy);
6032 if (SrcTypeSize.isScalable()) {
6033 assert(STy->containsHomogeneousScalableVectorTypes() &&
6034 "ABI only supports structure with homogeneous scalable vector "
6036 assert(SrcTypeSize == DstTypeSize &&
6037 "Only allow non-fractional movement of structure with "
6038 "homogeneous scalable vector type");
6039 assert(NumIRArgs == STy->getNumElements());
6041 llvm::Value *StoredStructValue =
6043 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6044 llvm::Value *Extract =
Builder.CreateExtractValue(
6045 StoredStructValue, i, Src.
getName() +
".extract" + Twine(i));
6046 IRCallArgs[FirstIRArg + i] = Extract;
6049 uint64_t SrcSize = SrcTypeSize.getFixedValue();
6050 uint64_t DstSize = DstTypeSize.getFixedValue();
6051 bool HasPFPFields =
getContext().hasPFPFields(I->Ty);
6057 if (HasPFPFields || SrcSize < DstSize) {
6068 Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
6074 assert(NumIRArgs == STy->getNumElements());
6075 for (
unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
6077 llvm::Value *LI =
Builder.CreateLoad(EltPtr);
6078 if (ArgHasMaybeUndefAttr)
6079 LI =
Builder.CreateFreeze(LI);
6080 IRCallArgs[FirstIRArg + i] = LI;
6085 assert(NumIRArgs == 1);
6093 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
6098 if (ArgHasMaybeUndefAttr)
6099 Load =
Builder.CreateFreeze(Load);
6100 IRCallArgs[FirstIRArg] = Load;
6108 auto layout =
CGM.getDataLayout().getStructLayout(coercionType);
6110 auto *unpaddedStruct = dyn_cast<llvm::StructType>(unpaddedCoercionType);
6114 bool NeedLifetimeEnd =
false;
6115 if (I->isAggregate()) {
6116 addr = I->hasLValue() ? I->getKnownLValue().getAddress()
6117 : I->getKnownRValue().getAggregateAddress();
6120 RValue RV = I->getKnownRValue();
6124 auto scalarAlign =
CGM.getDataLayout().getPrefTypeAlign(scalarType);
6129 layout->getAlignment(), scalarAlign)),
6131 nullptr, &AllocaAddr);
6139 unsigned IRArgPos = FirstIRArg;
6140 unsigned unpaddedIndex = 0;
6141 for (
unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
6142 llvm::Type *eltType = coercionType->getElementType(i);
6149 : unpaddedCoercionType,
6151 if (ArgHasMaybeUndefAttr)
6152 elt =
Builder.CreateFreeze(elt);
6153 IRCallArgs[IRArgPos++] = elt;
6155 assert(IRArgPos == FirstIRArg + NumIRArgs);
6157 if (NeedLifetimeEnd)
6163 unsigned IRArgPos = FirstIRArg;
6164 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
6165 assert(IRArgPos == FirstIRArg + NumIRArgs);
6171 if (!I->isAggregate()) {
6173 I->copyInto(*
this, Src);
6175 Src = I->hasLValue() ? I->getKnownLValue().getAddress()
6176 : I->getKnownRValue().getAggregateAddress();
6182 CGM.getABIInfo().createCoercedLoad(Src, ArgInfo, *
this);
6183 IRCallArgs[FirstIRArg] = Load;
6189 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*
this);
6195 assert(IRFunctionArgs.hasInallocaArg());
6196 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
6207 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
6208 llvm::Value *Ptr) -> llvm::Function * {
6209 if (!CalleeFT->isVarArg())
6213 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
6214 if (CE->getOpcode() == llvm::Instruction::BitCast)
6215 Ptr = CE->getOperand(0);
6218 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
6222 llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
6226 if (OrigFT->isVarArg() ||
6227 OrigFT->getNumParams() != CalleeFT->getNumParams() ||
6228 OrigFT->getReturnType() != CalleeFT->getReturnType())
6231 for (
unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
6232 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
6238 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
6240 IRFuncTy = OrigFn->getFunctionType();
6251 for (
unsigned i = 0; i < IRCallArgs.size(); ++i)
6252 LargestVectorWidth = std::max(LargestVectorWidth,
6257 llvm::AttributeList Attrs;
6258 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
6263 if (
CallingConv == llvm::CallingConv::X86_VectorCall &&
6265 CGM.Error(Loc,
"__vectorcall calling convention is not currently "
6270 if (FD->hasAttr<StrictFPAttr>())
6272 Attrs = Attrs.addFnAttribute(
getLLVMContext(), llvm::Attribute::StrictFP);
6277 if (FD->hasAttr<OptimizeNoneAttr>() &&
getLangOpts().FastMath)
6278 CGM.AdjustMemoryAttribute(CalleePtr->getName(), Callee.getAbstractInfo(),
6283 Attrs = Attrs.addFnAttribute(
getLLVMContext(), llvm::Attribute::NoMerge);
6287 Attrs = Attrs.addFnAttribute(
getLLVMContext(), llvm::Attribute::NoInline);
6292 !
CGM.getTargetCodeGenInfo().wouldInliningViolateFunctionCallABI(
6293 CallerDecl, CalleeDecl))
6295 Attrs.addFnAttribute(
getLLVMContext(), llvm::Attribute::AlwaysInline);
6300 Attrs.removeFnAttribute(
getLLVMContext(), llvm::Attribute::Convergent);
6309 !(TargetDecl && TargetDecl->
hasAttr<NoInlineAttr>()) &&
6310 !
CGM.getTargetCodeGenInfo().wouldInliningViolateFunctionCallABI(
6311 CallerDecl, CalleeDecl)) {
6313 Attrs.addFnAttribute(
getLLVMContext(), llvm::Attribute::AlwaysInline);
6318 Attrs = Attrs.addFnAttribute(
getLLVMContext(), llvm::Attribute::NoInline);
6325 CannotThrow =
false;
6334 CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
6336 if (
auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
6337 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
6348 if (NeedSRetLifetimeEnd)
6356 if (
SanOpts.has(SanitizerKind::KCFI) &&
6357 !isa_and_nonnull<FunctionDecl>(TargetDecl))
6364 if (FD->hasAttr<StrictFPAttr>())
6366 Attrs = Attrs.addFnAttribute(
getLLVMContext(), llvm::Attribute::StrictFP);
6368 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*
this, TargetDecl);
6369 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
6371 AllocAlignAttrEmitter AllocAlignAttrEmitter(*
this, TargetDecl, CallArgs);
6372 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
6377 CI =
Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
6380 CI =
Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
6384 if (CI->getCalledFunction() && CI->getCalledFunction()->hasName() &&
6385 CI->getCalledFunction()->getName().starts_with(
"_Z4sqrt")) {
6390 if (
CGM.getCodeGenOpts().CallGraphSection) {
6394 else if (
const auto *FPT =
6395 Callee.getAbstractInfo().getCalleeFunctionProtoType())
6397 else if (
const auto *FT =
6398 Callee.getAbstractInfo().getCalleeFunctionType())
6402 "Cannot find the callee type to generate callee_type metadata.");
6445 for (
const CallArg &Arg : CallArgs)
6446 ParamTypes.push_back(Arg.
getType());
6448 CST =
getContext().getFunctionType(FNPT->getReturnType(),
6452 llvm::Metadata *MD =
6453 CGM.CreateMetadataIdentifierForCallGraphType(CST);
6455 if (
auto *MDS = dyn_cast_or_null<llvm::MDString>(MD))
6456 TypeStr = MDS->getString();
6458 CGM.getDiags().Report(Loc, diag::warn_cgs_no_proto) << CST << TypeStr;
6460 CGM.createCalleeTypeMetadataForIcall(CST, *callOrInvoke);
6468 if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(
CurFuncDecl)) {
6469 if (
const auto *A = FD->getAttr<CFGuardAttr>()) {
6470 if (A->getGuard() == CFGuardAttr::GuardArg::nocf &&
6471 !CI->getCalledFunction())
6477 CI->setAttributes(Attrs);
6478 CI->setCallingConv(
static_cast<llvm::CallingConv::ID
>(
CallingConv));
6482 if (!CI->getType()->isVoidTy())
6483 CI->setName(
"call");
6485 if (
CGM.shouldEmitConvergenceTokens() && CI->isConvergent())
6486 CI = addConvergenceControlToken(CI);
6489 LargestVectorWidth =
6495 if (!CI->getCalledFunction())
6496 PGO->valueProfile(
Builder, llvm::IPVK_IndirectCallTarget, CI, CalleePtr);
6500 if (
CGM.getLangOpts().ObjCAutoRefCount)
6501 AddObjCARCExceptionMetadata(CI);
6504 bool IsPPC =
getTarget().getTriple().isPPC();
6505 bool IsMIPS =
getTarget().getTriple().isMIPS();
6506 bool HasMips16 =
false;
6509 HasMips16 = TargetOpts.
FeatureMap.lookup(
"mips16");
6511 HasMips16 = llvm::is_contained(TargetOpts.
Features,
"+mips16");
6513 if (llvm::CallInst *
Call = dyn_cast<llvm::CallInst>(CI)) {
6514 if (TargetDecl && TargetDecl->
hasAttr<NotTailCalledAttr>())
6515 Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
6516 else if (IsMustTail) {
6519 CGM.getDiags().Report(Loc, diag::err_aix_musttail_unsupported);
6522 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 0;
6523 else if (
Call->isIndirectCall())
6524 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail) << 1;
6525 else if (isa_and_nonnull<FunctionDecl>(TargetDecl)) {
6530 CGM.addUndefinedGlobalForTailCall(
6533 llvm::GlobalValue::LinkageTypes
Linkage =
CGM.getFunctionLinkage(
6535 if (llvm::GlobalValue::isWeakForLinker(
Linkage) ||
6536 llvm::GlobalValue::isDiscardableIfUnused(
Linkage))
6537 CGM.getDiags().Report(Loc, diag::err_ppc_impossible_musttail)
6545 CGM.getDiags().Report(Loc, diag::err_mips_impossible_musttail) << 0;
6546 else if (
const auto *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
6547 CGM.addUndefinedGlobalForTailCall({FD, Loc});
6549 Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
6563 bool NeedSrcLoc = TargetDecl->
hasAttr<ErrorAttr>();
6564 if (!NeedSrcLoc &&
CGM.getCodeGenOpts().ShowInliningChain) {
6565 if (
const auto *FD = dyn_cast<FunctionDecl>(TargetDecl))
6566 NeedSrcLoc = FD->isInlined() || FD->hasAttr<AlwaysInlineAttr>() ||
6568 FD->isInAnonymousNamespace();
6572 auto *MD = llvm::ConstantAsMetadata::get(
Line);
6573 CI->setMetadata(
"srcloc", llvm::MDNode::get(
getLLVMContext(), {MD}));
6582 if (CI->doesNotReturn()) {
6583 if (NeedSRetLifetimeEnd)
6587 if (
SanOpts.has(SanitizerKind::Unreachable)) {
6590 if (
auto *F = CI->getCalledFunction())
6591 F->removeFnAttr(llvm::Attribute::NoReturn);
6592 CI->removeFnAttr(llvm::Attribute::NoReturn);
6596 if (
SanOpts.hasOneOf(SanitizerKind::Address |
6597 SanitizerKind::KernelAddress)) {
6599 llvm::IRBuilder<>::InsertPointGuard IPGuard(
Builder);
6601 auto *FnType = llvm::FunctionType::get(
CGM.VoidTy,
false);
6602 llvm::FunctionCallee Fn =
6603 CGM.CreateRuntimeFunction(FnType,
"__asan_handle_no_return");
6609 Builder.ClearInsertionPoint();
6631 if (CI->doesNotThrow())
6634 diag::err_musttail_noexcept_mismatch);
6640 if (Cleanup && Cleanup->isFakeUse()) {
6641 CGBuilderTy::InsertPointGuard IPG(
Builder);
6643 Cleanup->getCleanup()->Emit(*
this, EHScopeStack::Cleanup::Flags());
6644 }
else if (!(Cleanup &&
6645 Cleanup->getCleanup()->isRedundantBeforeReturn())) {
6646 CGM.ErrorUnsupported(
MustTailCall,
"tail call skipping over cleanups");
6649 if (CI->getType()->isVoidTy())
6653 Builder.ClearInsertionPoint();
6659 if (swiftErrorTemp.
isValid()) {
6660 llvm::Value *errorResult =
Builder.CreateLoad(swiftErrorTemp);
6661 Builder.CreateStore(errorResult, swiftErrorArg);
6678 if (IsVirtualFunctionPointerThunk) {
6691 unsigned unpaddedIndex = 0;
6692 for (
unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
6693 llvm::Type *eltType = coercionType->getElementType(i);
6697 llvm::Value *elt = CI;
6698 if (requiresExtract)
6699 elt =
Builder.CreateExtractValue(elt, unpaddedIndex++);
6701 assert(unpaddedIndex == 0);
6702 Builder.CreateStore(elt, eltAddr);
6710 if (NeedSRetLifetimeEnd)
6727 llvm::Value *Real =
Builder.CreateExtractValue(CI, 0);
6728 llvm::Value *Imag =
Builder.CreateExtractValue(CI, 1);
6736 llvm::Value *
V = CI;
6737 if (
V->getType() != RetIRTy)
6747 if (
auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(RetIRTy)) {
6748 llvm::Value *
V = CI;
6749 if (
auto *ScalableSrcTy =
6750 dyn_cast<llvm::ScalableVectorType>(
V->getType())) {
6751 if (FixedDstTy->getElementType() ==
6752 ScalableSrcTy->getElementType()) {
6753 V =
Builder.CreateExtractVector(FixedDstTy,
V, uint64_t(0),
6763 getContext().getTypeInfoDataSizeInChars(RetTy).Width.getQuantity();
6767 DestIsVolatile =
false;
6768 DestSize =
getContext().getTypeSizeInChars(RetTy).getQuantity();
6778 CI, RetTy, StorePtr,
6792 DestIsVolatile =
false;
6794 CGM.getABIInfo().createCoercedStore(CI, StorePtr, RetAI, DestIsVolatile,
6801 llvm_unreachable(
"Invalid ABI kind for return argument");
6804 llvm_unreachable(
"Unhandled ABIArgInfo::Kind");
6809 if (Ret.isScalar() && TargetDecl) {
6810 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6811 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
6829 if (CalleeDecl && !CalleeDecl->
hasAttr<NoDebugAttr>() &&
6830 DI->getCallSiteRelatedAttrs() != llvm::DINode::FlagZero) {
6831 CodeGenFunction CalleeCGF(
CGM);
6833 Callee.getAbstractInfo().getCalleeDecl();
6834 CalleeCGF.
CurGD = CalleeGlobalDecl;
6837 DI->EmitFuncDeclForCallSite(
6838 CI, DI->getFunctionType(CalleeDecl, ResTy, Args), CalleeGlobalDecl);
6841 DI->addCallTargetIfVirtual(CalleeDecl, CI);
6862 VAListAddr =
VE->isMicrosoftABI()
6869 if (
VE->isMicrosoftABI())
6870 return CGM.getABIInfo().EmitMSVAArg(*
this, VAListAddr, Ty, Slot);
6872 return CGM.getABIInfo().EmitZOSVAArg(*
this, VAListAddr, Ty, Slot);
6873 return CGM.getABIInfo().EmitVAArg(*
this, VAListAddr, Ty, Slot);
6878 CGF.disableDebugInfo();
6882 CGF.enableDebugInfo();
static ExtParameterInfoList getExtParameterInfosForCall(const FunctionProtoType *proto, unsigned prefixArgs, unsigned totalArgs)
static bool isInAllocaArgument(CGCXXABI &ABI, QualType type)
static uint64_t buildMultiCharMask(const SmallVectorImpl< uint64_t > &Bits, int Pos, int Size, int CharWidth, bool BigEndian)
static llvm::Value * tryRemoveRetainOfSelf(CodeGenFunction &CGF, llvm::Value *result)
If this is a +1 of the value of an immutable 'self', remove it.
static CanQualType GetReturnType(QualType RetTy)
Returns the "extra-canonicalized" return type, which discards qualifiers on the return type.
static const NonNullAttr * getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, QualType ArgType, unsigned ArgNo)
Returns the attribute (either parameter attribute, or function attribute), which declares argument Ar...
static CanQualTypeList getArgTypesForCall(ASTContext &ctx, const CallArgList &args)
static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, const ABIArgInfo &info)
static const char * abiKindToString(ABIArgInfo::Kind K)
static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, QualType Ty)
static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D, bool IsTargetDefaultMSABI)
static void setBitRange(SmallVectorImpl< uint64_t > &Bits, int BitOffset, int BitWidth, int CharWidth)
static bool isProvablyNull(llvm::Value *addr)
static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, llvm::AttrBuilder &FuncAttrs, const FunctionProtoType *FPT)
static void eraseUnusedBitCasts(llvm::Instruction *insn)
static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method)
static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, const ObjCIndirectCopyRestoreExpr *CRE)
Emit an argument that's being passed call-by-writeback.
static void overrideFunctionFeaturesWithTargetFeatures(llvm::AttrBuilder &FuncAttr, const llvm::Function &F, const TargetOptions &TargetOpts)
Merges target-features from \TargetOpts and \F, and sets the result in \FuncAttr.
static llvm::Value * CreatePFPCoercedLoad(Address Src, QualType SrcFETy, llvm::Type *Ty, CodeGenFunction &CGF)
static int getExpansionSize(QualType Ty, const ASTContext &Context)
static CanQual< FunctionProtoType > GetFormalType(const CXXMethodDecl *MD)
Returns the canonical formal type of the given C++ method.
static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types, const llvm::DataLayout &DL, const ABIArgInfo &AI, bool CheckCoerce=true)
static const Expr * maybeGetUnaryAddrOfOperand(const Expr *E)
static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, const CallArgList &CallArgs)
static bool isProvablyNonNull(Address Addr, CodeGenFunction &CGF)
static llvm::Value * emitArgumentDemotion(CodeGenFunction &CGF, const VarDecl *var, llvm::Value *value)
An argument came in as a promoted argument; demote it back to its declared type.
SmallVector< CanQualType, 16 > CanQualTypeList
static std::pair< llvm::Value *, bool > CoerceScalableToFixed(CodeGenFunction &CGF, llvm::FixedVectorType *ToTy, llvm::ScalableVectorType *FromTy, llvm::Value *V, StringRef Name="")
static const CGFunctionInfo & arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod, SmallVectorImpl< CanQualType > &prefix, CanQual< FunctionProtoType > FTP)
Arrange the LLVM function layout for a value of the given function type, on top of any implicit param...
static llvm::Value * CreateCoercedLoad(Address Src, QualType SrcFETy, llvm::Type *Ty, CodeGenFunction &CGF)
CreateCoercedLoad - Create a load from.
static void addExtParameterInfosForCall(llvm::SmallVectorImpl< FunctionProtoType::ExtParameterInfo > ¶mInfos, const FunctionProtoType *proto, unsigned prefixArgs, unsigned totalArgs)
static bool canApplyNoFPClass(const ABIArgInfo &AI, QualType ParamType, bool IsReturn)
Test if it's legal to apply nofpclass for the given parameter type and it's lowered IR type.
static void getTrivialDefaultFunctionAttributes(StringRef Name, bool HasOptnone, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, bool AttrOnCallSite, llvm::AttrBuilder &FuncAttrs)
static void forConstantArrayExpansion(CodeGenFunction &CGF, ConstantArrayExpansion *CAE, Address BaseAddr, llvm::function_ref< void(Address)> Fn)
static bool IsArgumentMaybeUndef(const Decl *TargetDecl, unsigned NumRequiredArgs, unsigned ArgNo)
Check if the argument of a function has maybe_undef attribute.
static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC, ArrayRef< QualType > ArgTypes)
static std::unique_ptr< TypeExpansion > getTypeExpansion(QualType Ty, const ASTContext &Context)
SmallVector< FunctionProtoType::ExtParameterInfo, 16 > ExtParameterInfoList
static RawAddress CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty, CharUnits MinAlign, const Twine &Name="tmp")
Create a temporary allocation for the purposes of coercion.
static void setUsedBits(CodeGenModule &, QualType, int, SmallVectorImpl< uint64_t > &)
static llvm::StoreInst * findDominatingStoreToReturnValue(CodeGenFunction &CGF)
Heuristically search for a dominating store to the return-value slot.
static llvm::Value * tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, llvm::Value *result)
Try to emit a fused autorelease of a return result.
static Address EnterStructPointerForCoercedAccess(Address SrcPtr, llvm::StructType *SrcSTy, uint64_t DstSize, CodeGenFunction &CGF)
EnterStructPointerForCoercedAccess - Given a struct pointer that we are accessing some number of byte...
static llvm::Value * emitAutoreleaseOfResult(CodeGenFunction &CGF, llvm::Value *result)
Emit an ARC autorelease of the result of a function.
static void emitWriteback(CodeGenFunction &CGF, const CallArgList::Writeback &writeback)
Emit the actual writing-back of a writeback.
static bool HasStrictReturn(const CodeGenModule &Module, QualType RetTy, const Decl *TargetDecl)
static CanQualTypeList getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args)
static void addMergableDefaultFunctionAttributes(const CodeGenOptions &CodeGenOpts, llvm::AttrBuilder &FuncAttrs)
Add default attributes to a function, which have merge semantics under -mlink-builtin-bitcode and sho...
static bool CreatePFPCoercedStore(llvm::Value *Src, QualType SrcFETy, Address Dst, CodeGenFunction &CGF)
static llvm::Value * CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, llvm::Type *Ty, CodeGenFunction &CGF)
CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both are either integers or p...
static void AddAttributesFromOMPAssumes(llvm::AttrBuilder &FuncAttrs, const Decl *Callee)
static unsigned getMaxVectorWidth(const llvm::Type *Ty)
CodeGenFunction::ComplexPairTy ComplexPairTy
static void setCUDAKernelCallingConvention(CanQualType &funcTy, CIRGenModule &cgm, const FunctionDecl *fd)
Set calling convention for CUDA/HIP kernel.
static void addNoBuiltinAttributes(mlir::MLIRContext &ctx, mlir::NamedAttrList &attrs, const LangOptions &langOpts, const NoBuiltinAttr *nba=nullptr)
static void addDenormalModeAttrs(llvm::DenormalMode fpDenormalMode, llvm::DenormalMode fp32DenormalMode, mlir::NamedAttrList &attrs)
Add denormal-fp-math and denormal-fp-math-f32 as appropriate for the requested denormal behavior,...
static unsigned getNoFPClassTestMask(const LangOptions &langOpts)
Compute the nofpclass mask for FP types based on language options.
static void appendParameterTypes(const CIRGenTypes &cgt, SmallVectorImpl< CanQualType > &prefix, CanQual< FunctionProtoType > fpt)
Adds the formal parameters in FPT to the given prefix.
static const CIRGenFunctionInfo & arrangeFreeFunctionLikeCall(CIRGenTypes &cgt, CIRGenModule &cgm, const CallArgList &args, const FunctionType *fnType)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Result
Implement __builtin_bit_cast and related operations.
#define CC_VLS_CASE(ABI_VLEN)
static bool hasFeature(StringRef Feature, const LangOptions &LangOpts, const TargetInfo &Target)
Determine whether a translation unit built using the current language options has the given feature.
static StringRef getTriple(const Command &Job)
Maps Clang QualType instances to corresponding LLVM ABI type representations.
static QualType getPointeeType(const MemRegion *R)
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
CanQualType getCanonicalParamType(QualType T) const
Return the canonical parameter type corresponding to the specific potentially non-canonical one.
CanQualType getCanonicalSizeType() const
const TargetInfo & getTargetInfo() const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
std::vector< PFPField > findPFPFields(QualType Ty) const
Returns a list of PFP fields for the given type, including subfields in bases or other fields,...
uint64_t getCharWidth() const
Return the size of the character type, in bits.
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
uint64_t getFieldOffset(unsigned FieldNo) const
getFieldOffset - Get the offset of the given field index, in bits.
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Attr - This represents one attribute.
This class is used for builtin types like 'int'.
QualType getType() const
Retrieves the type of the base class.
Represents a C++ constructor within a class.
Represents a C++ destructor within a class.
Represents a static or instance method of a struct/union/class.
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Qualifiers getMethodQualifiers() const
Represents a C++ struct/union/class.
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
unsigned getNumVBases() const
Retrieves the number of virtual base classes of this class.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
SourceLocation getBeginLoc() const
ConstExprIterator const_arg_iterator
Represents a canonical, potentially-qualified type.
static CanQual< Type > CreateUnsafe(QualType Other)
CanProxy< U > castAs() const
CanQual< T > getUnqualifiedType() const
Retrieve the unqualified form of this type.
CanProxy< U > getAs() const
Retrieve a canonical type pointer with a different static type, upcasting or downcasting as needed.
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
CharUnits - This is an opaque type for sizes expressed in character units.
bool isZero() const
isZero - Test whether the quantity equals zero.
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
CodeGenOptions - Track various options which control how the code is optimized and passed to the back...
llvm::DenormalMode FPDenormalMode
The floating-point denormal mode to use.
static StringRef getFramePointerKindName(FramePointerKind Kind)
std::vector< std::string > Reciprocals
llvm::DenormalMode FP32DenormalMode
The floating-point denormal mode to use, for float.
std::string TrapFuncName
If not an empty string, trap intrinsics are lowered to calls to this function instead of to trap inst...
std::vector< std::string > DefaultFunctionAttrs
std::string PreferVectorWidth
The preferred width for auto-vectorization transforms.
ABIArgInfo - Helper class to encapsulate information about how a specific C type should be passed to ...
static ABIArgInfo getZeroExtend(QualType Ty, llvm::Type *T=nullptr, llvm::Type *Padding=nullptr)
unsigned getInAllocaFieldIndex() const
static ABIArgInfo getSignExtend(QualType Ty, llvm::Type *T=nullptr, llvm::Type *Padding=nullptr)
bool getIndirectByVal() const
llvm::StructType * getCoerceAndExpandType() const
bool getIndirectRealign() const
static ABIArgInfo getIgnore()
void setCoerceToType(llvm::Type *T)
llvm::Type * getUnpaddedCoerceAndExpandType() const
bool getCanBeFlattened() const
unsigned getDirectOffset() const
static bool isPaddingForCoerceAndExpand(llvm::Type *eltType)
bool getInAllocaSRet() const
Return true if this field of an inalloca struct should be returned to implement a struct return calli...
llvm::Type * getPaddingType() const
bool getPaddingInReg() const
unsigned getDirectAlign() const
unsigned getIndirectAddrSpace() const
static ABIArgInfo getDirect(llvm::Type *T=nullptr, unsigned Offset=0, llvm::Type *Padding=nullptr, bool CanBeFlattened=true, unsigned Align=0)
@ Extend
Extend - Valid only for integer argument types.
@ Ignore
Ignore - Ignore the argument (treat as void).
@ IndirectAliased
IndirectAliased - Similar to Indirect, but the pointer may be to an object that is otherwise referenc...
@ Expand
Expand - Only valid for aggregate argument types.
@ TargetSpecific
TargetSpecific - Some argument types are passed as target specific types such as RISC-V's tuple type,...
@ InAlloca
InAlloca - Pass the argument directly using the LLVM inalloca attribute.
@ Indirect
Indirect - Pass the argument indirectly via a hidden pointer with the specified alignment (0 indicate...
@ CoerceAndExpand
CoerceAndExpand - Only valid for aggregate argument types.
@ Direct
Direct - Pass the argument directly using the normal converted LLVM type, or by coercing to another s...
static ABIArgInfo getExtend(QualType Ty, llvm::Type *T=nullptr, llvm::Type *Padding=nullptr)
static ABIArgInfo getIndirect(CharUnits Alignment, unsigned AddrSpace, bool ByVal=true, bool Realign=false, llvm::Type *Padding=nullptr)
ArrayRef< llvm::Type * > getCoerceAndExpandTypeSequence() const
bool isCoerceAndExpand() const
unsigned getInAllocaIndirect() const
llvm::Type * getCoerceToType() const
bool isIndirectAliased() const
bool isSRetAfterThis() const
bool canHaveCoerceToType() const
CharUnits getIndirectAlign() const
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
llvm::Value * getBasePointer() const
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
CharUnits getAlignment() const
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Address withPointer(llvm::Value *NewPointer, KnownNonNull_t IsKnownNonNull) const
Return address with different pointer, but same element type and alignment.
Address withElementType(llvm::Type *ElemTy) const
Return address with different element type, but same pointer and alignment.
unsigned getAddressSpace() const
Return the address space that this address resides in.
KnownNonNull_t isKnownNonNull() const
Whether the pointer is known not to be null.
llvm::StringRef getName() const
Return the IR name of the pointer value.
Address getAddress() const
void setExternallyDestructed(bool destructed=true)
static AggValueSlot forAddr(Address addr, Qualifiers quals, IsDestructed_t isDestructed, NeedsGCBarriers_t needsGC, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed, IsSanitizerChecked_t isChecked=IsNotSanitizerChecked)
forAddr - Make a slot for an aggregate value.
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Address CreateConstInBoundsByteGEP(Address Addr, CharUnits Offset, const llvm::Twine &Name="")
Given a pointer to i8, adjust it by a given constant offset.
llvm::Value * CreateIsNull(Address Addr, const Twine &Name="")
Address CreateConstGEP2_32(Address Addr, unsigned Idx0, unsigned Idx1, const llvm::Twine &Name="")
Address CreateStructGEP(Address Addr, unsigned Index, const llvm::Twine &Name="")
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
llvm::CallInst * CreateMemCpy(Address Dest, Address Src, llvm::Value *Size, bool IsVolatile=false)
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Implements C++ ABI-specific code generation functions.
virtual bool hasMostDerivedReturn(GlobalDecl GD) const
virtual bool HasThisReturn(GlobalDecl GD) const
Returns true if the given constructor or destructor is one of the kinds that the ABI says returns 'th...
@ RAA_DirectInMemory
Pass it on the stack using its defined layout.
virtual CGCallee getVirtualFunctionPointer(CodeGenFunction &CGF, GlobalDecl GD, Address This, llvm::Type *Ty, SourceLocation Loc)=0
Build a virtual function pointer in the ABI-specific way.
virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const =0
Returns how an argument of the given record type should be passed.
virtual const CXXRecordDecl * getThisArgumentTypeForMethod(GlobalDecl GD)
Get the type of the implicit "this" parameter used by a method.
virtual AddedStructorArgCounts buildStructorSignature(GlobalDecl GD, SmallVectorImpl< CanQualType > &ArgTys)=0
Build the signature of the given constructor or destructor variant by adding any required parameters.
Abstract information about a function or function prototype.
const GlobalDecl getCalleeDecl() const
const FunctionProtoType * getCalleeFunctionProtoType() const
All available information about a concrete callee.
CGCallee prepareConcreteCallee(CodeGenFunction &CGF) const
If this is a delayed callee computation of some sort, prepare a concrete callee.
Address getThisAddress() const
const CallExpr * getVirtualCallExpr() const
llvm::Value * getFunctionPointer() const
llvm::FunctionType * getVirtualFunctionType() const
const CGPointerAuthInfo & getPointerAuthInfo() const
GlobalDecl getVirtualMethodDecl() const
This class gathers all debug information during compilation and is responsible for emitting to llvm g...
CGFunctionInfo - Class to encapsulate the information about a function definition.
bool usesInAlloca() const
Return true if this function uses inalloca arguments.
FunctionType::ExtInfo getExtInfo() const
bool isInstanceMethod() const
ABIArgInfo & getReturnInfo()
bool isReturnsRetained() const
In ARC, whether this function retains its return value.
unsigned getCallingConvention() const
getCallingConvention - Return the user specified calling convention, which has been translated into a...
void Profile(llvm::FoldingSetNodeID &ID)
const_arg_iterator arg_begin() const
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
CanQualType getReturnType() const
static CGFunctionInfo * create(unsigned llvmCC, bool instanceMethod, bool chainCall, bool delegateCall, unsigned X86ABIAVXLevel, const FunctionType::ExtInfo &extInfo, ArrayRef< ExtParameterInfo > paramInfos, CanQualType resultType, ArrayRef< CanQualType > argTypes, RequiredArgs required)
const ArgInfo * const_arg_iterator
bool isCmseNSCall() const
bool isDelegateCall() const
MutableArrayRef< ArgInfo > arguments()
const_arg_iterator arg_end() const
unsigned getEffectiveCallingConvention() const
getEffectiveCallingConvention - Return the actual calling convention to use, which may depend on the ...
unsigned getX86ABIAVXLevel() const
ExtParameterInfo getExtParameterInfo(unsigned argIndex) const
CharUnits getArgStructAlignment() const
unsigned arg_size() const
RequiredArgs getRequiredArgs() const
unsigned getNumRequiredArgs() const
llvm::StructType * getArgStruct() const
Get the struct type used to represent all the arguments in memory.
CGRecordLayout - This class handles struct and union layout info while lowering AST types to LLVM typ...
const CGBitFieldInfo & getBitFieldInfo(const FieldDecl *FD) const
Return the BitFieldInfo that corresponds to the field FD.
CallArgList - Type for representing both the value and type of arguments in a call.
void addWriteback(LValue srcLV, Address temporary, llvm::Value *toUse, const Expr *writebackExpr=nullptr)
llvm::Instruction * getStackBase() const
void addUncopiedAggregate(LValue LV, QualType type)
void addArgCleanupDeactivation(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *IsActiveIP)
ArrayRef< CallArgCleanup > getCleanupsToDeactivate() const
bool hasWritebacks() const
void add(RValue rvalue, QualType type)
bool isUsingInAlloca() const
Returns if we're using an inalloca struct to pass arguments in memory.
void allocateArgumentMemory(CodeGenFunction &CGF)
void freeArgumentMemory(CodeGenFunction &CGF) const
writeback_const_range writebacks() const
An abstract representation of regular/ObjC call/message targets.
const ParmVarDecl * getParamDecl(unsigned I) const
const Decl * getDecl() const
unsigned getNumParams() const
bool hasFunctionDecl() const
An object to manage conditionally-evaluated expressions.
void begin(CodeGenFunction &CGF)
void end(CodeGenFunction &CGF)
static ParamValue forIndirect(Address addr)
static ParamValue forDirect(llvm::Value *value)
RAII object to set/unset CodeGenFunction::IsSanitizerScope.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
EHScopeStack::stable_iterator CurrentCleanupScopeDepth
GlobalDecl CurGD
CurGD - The GlobalDecl for the current function being compiled.
llvm::Value * EmitARCRetainAutoreleaseReturnValue(llvm::Value *value)
Do a fused retain/autorelease of the given object.
llvm::Value * performAddrSpaceCast(llvm::Value *Src, llvm::Type *DestTy)
SanitizerSet SanOpts
Sanitizers enabled for this function.
void checkTargetFeatures(const CallExpr *E, const FunctionDecl *TargetDecl)
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
bool isCleanupPadScope() const
Returns true while emitting a cleanuppad.
void addInstToNewSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
Add KeyInstruction and an optional Backup instruction to a new atom group (See ApplyAtomGroup for mor...
llvm::CallBase * EmitCallOrInvoke(llvm::FunctionCallee Callee, ArrayRef< llvm::Value * > Args, const Twine &Name="")
Emits a call or invoke instruction to the given function, depending on the current state of the EH st...
void EmitNoreturnRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args)
Emits a call or invoke to the given noreturn runtime function.
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
void callCStructDestructor(LValue Dst)
ComplexPairTy EmitLoadOfComplex(LValue src, SourceLocation loc)
EmitLoadOfComplex - Load a complex number from the specified l-value.
llvm::Value * EmitARCAutoreleaseReturnValue(llvm::Value *value)
Autorelease the given object.
bool shouldUseFusedARCCalls()
bool CurFuncIsThunk
In C++, whether we are code generating a thunk.
bool isSEHTryScope() const
Returns true inside SEH __try blocks.
RValue convertTempToRValue(Address addr, QualType type, SourceLocation Loc)
Given the address of a temporary variable, produce an r-value of its type.
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
void SetSqrtFPAccuracy(llvm::Value *Val)
Set the minimum required accuracy of the given sqrt operation based on CodeGenOpts.
RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr, AggValueSlot Slot=AggValueSlot::ignored())
Generate code to get an argument from the passed in pointer and update it accordingly.
void EmitReturnValueCheck(llvm::Value *RV)
Emit a test that checks if the return value RV is nonnull.
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
void EmitDelegateCallArg(CallArgList &args, const VarDecl *param, SourceLocation loc)
EmitDelegateCallArg - We are performing a delegate call; that is, the current function is delegating ...
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void addInstToCurrentSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup)
See CGDebugInfo::addInstToCurrentSourceAtom.
const LangOptions & getLangOpts() const
void addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction, llvm::Value *Backup, uint64_t Atom)
See CGDebugInfo::addInstToSpecificSourceAtom.
RValue EmitReferenceBindingToExpr(const Expr *E)
Emits a reference binding to the passed in expression.
LValue MakeNaturalAlignAddrLValue(llvm::Value *V, QualType T, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
bool InNoConvergentAttributedStmt
True if the current statement has noconvergent attribute.
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
pushDestroy - Push the standard destructor for the given type as at least a normal cleanup.
const CodeGen::CGBlockInfo * BlockInfo
void EmitKCFIOperandBundle(const CGCallee &Callee, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
Address makeNaturalAddressForPointer(llvm::Value *Ptr, QualType T, CharUnits Alignment=CharUnits::Zero(), bool ForPointeeType=false, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
Construct an address with the natural alignment of T.
void EmitCXXDestructorCall(const CXXDestructorDecl *D, CXXDtorType Type, bool ForVirtualBase, bool Delegating, Address This, QualType ThisTy)
bool InNoMergeAttributedStmt
True if the current statement has nomerge attribute.
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
llvm::BasicBlock * getUnreachableBlock()
void EmitARCRelease(llvm::Value *value, ARCPreciseLifetime_t precise)
Release the given object.
bool currentFunctionUsesSEHTry() const
JumpDest ReturnBlock
ReturnBlock - Unified return block.
void CreateCoercedStore(llvm::Value *Src, QualType SrcFETy, Address Dst, llvm::TypeSize DstSize, bool DstIsVolatile)
Create a store to.
@ ForceLeftToRight
! Language semantics require left-to-right evaluation.
@ ForceRightToLeft
! Language semantics require right-to-left evaluation.
void EmitNonNullArgCheck(RValue RV, QualType ArgType, SourceLocation ArgLoc, AbstractCallee AC, unsigned ParmNum)
Create a check for a function parameter that may potentially be declared as non-null.
void EmitAggregateCopy(LValue Dest, LValue Src, QualType EltTy, AggValueSlot::Overlap_t MayOverlap, bool isVolatile=false)
EmitAggregateCopy - Emit an aggregate copy.
const TargetInfo & getTarget() const
LValue EmitHLSLOutArgExpr(const HLSLOutArgExpr *E, CallArgList &Args, QualType Ty)
void EmitWritebacks(const CallArgList &Args)
EmitWriteback - Emit callbacks for function.
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
void DeactivateCleanupBlock(EHScopeStack::stable_iterator Cleanup, llvm::Instruction *DominatingIP)
DeactivateCleanupBlock - Deactivates the given cleanup block.
void pushFullExprCleanup(CleanupKind kind, As... A)
pushFullExprCleanup - Push a cleanup to be run at the end of the current full-expression.
llvm::BasicBlock * getInvokeDest()
void EmitCallArg(CallArgList &args, const Expr *E, QualType ArgType)
EmitCallArg - Emit a single call argument.
void EmitPointerAuthOperandBundle(const CGPointerAuthInfo &Info, SmallVectorImpl< llvm::OperandBundleDef > &Bundles)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
AggValueSlot CreateAggTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateAggTemp - Create a temporary memory object for the given aggregate type.
llvm::CallInst * EmitIntrinsicCall(llvm::Intrinsic::ID ID, const Twine &Name="")
bool HaveInsertPoint() const
HaveInsertPoint - True if an insertion point is defined.
CGDebugInfo * getDebugInfo()
bool EmitLifetimeStart(llvm::Value *Addr)
Emit a lifetime.begin marker if some criteria are satisfied.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **CallOrInvoke, bool IsMustTail, SourceLocation Loc, bool IsVirtualFunctionPointerThunk=false)
EmitCall - Generate a call of the given function, expecting the given result type,...
void EmitLifetimeEnd(llvm::Value *Addr)
RawAddress CreateMemTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen without...
bool InNoInlineAttributedStmt
True if the current statement has noinline attribute.
SmallVector< llvm::OperandBundleDef, 1 > getBundlesForFunclet(llvm::Value *Callee)
RValue EmitAnyExprToTemp(const Expr *E)
EmitAnyExprToTemp - Similarly to EmitAnyExpr(), however, the result will always be accessible even if...
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
ASTContext & getContext() const
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
void EmitStoreOfComplex(ComplexPairTy V, LValue dest, bool isInit)
EmitStoreOfComplex - Store a complex number into the specified l-value.
const Decl * CurFuncDecl
CurFuncDecl - Holds the Decl for the current outermost non-closure context.
void EmitFunctionProlog(const CGFunctionInfo &FI, llvm::Function *Fn, const FunctionArgList &Args)
EmitFunctionProlog - Emit the target specific LLVM code to load the arguments for the given function.
Address EmitAddressOfPFPField(Address RecordPtr, const PFPField &Field)
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Address EmitVAListRef(const Expr *E)
RValue GetUndefRValue(QualType Ty)
GetUndefRValue - Get an appropriate 'undef' rvalue for the given type.
void EmitParmDecl(const VarDecl &D, ParamValue Arg, unsigned ArgNo)
EmitParmDecl - Emit a ParmVarDecl or an ImplicitParamDecl.
bool AutoreleaseResult
In ARC, whether we should autorelease the return value.
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitARCRetainNonBlock(llvm::Value *value)
Retain the given object, with normal retain semantics.
llvm::Type * ConvertTypeForMem(QualType T)
Address EmitZOSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_zos_va_list; this is always the address of the expression,...
CodeGenTypes & getTypes() const
static TypeEvaluationKind getEvaluationKind(QualType T)
getEvaluationKind - Return the TypeEvaluationKind of QualType T.
bool InAlwaysInlineAttributedStmt
True if the current statement has always_inline attribute.
void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc, SourceLocation EndLoc, uint64_t RetKeyInstructionsSourceAtom)
EmitFunctionEpilog - Emit the target specific LLVM code to return the given temporary.
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
void EmitAggExpr(const Expr *E, AggValueSlot AS)
EmitAggExpr - Emit the computation of the specified expression of aggregate type.
Address EmitMSVAListRef(const Expr *E)
Emit a "reference" to a __builtin_ms_va_list; this is always the value of the expression,...
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
static bool hasAggregateEvaluationKind(QualType T)
void EmitCallArgs(CallArgList &Args, PrototypeWrapper Prototype, llvm::iterator_range< CallExpr::const_arg_iterator > ArgRange, AbstractCallee AC=AbstractCallee(), unsigned ParamsToSkip=0, EvaluationOrder Order=EvaluationOrder::Default)
EmitCallArgs - Emit call arguments for a function.
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
const CallExpr * MustTailCall
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
void EmitUnreachable(SourceLocation Loc)
Emit a reached-unreachable diagnostic if Loc is valid and runtime checking is enabled.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
llvm::Instruction * CurrentFuncletPad
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
llvm::LLVMContext & getLLVMContext()
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
llvm::Value * EmitNonNullRValueCheck(RValue RV, QualType T)
Create a check that a scalar RValue is non-null.
void EmitARCIntrinsicUse(ArrayRef< llvm::Value * > values)
Given a number of pointers, inform the optimizer that they're being intrinsically used up until this ...
llvm::Value * EmitCMSEClearRecord(llvm::Value *V, llvm::IntegerType *ITy, QualType RTy)
void PopCleanupBlock(bool FallThroughIsBranchThrough=false, bool ForDeactivation=false)
PopCleanupBlock - Will pop the cleanup entry on the stack and process all branch fixups.
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
QualType BuildFunctionArgList(GlobalDecl GD, FunctionArgList &Args)
This class organizes the cross-function state that is used while generating LLVM code.
const ABIInfo & getABIInfo()
bool ReturnTypeUsesFPRet(QualType ResultType)
Return true iff the given type uses 'fpret' when used as a return type.
const LangOptions & getLangOpts() const
CharUnits getNaturalTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, bool forPointeeType=false)
CodeGenTypes & getTypes()
const TargetInfo & getTarget() const
void computeABIInfoUsingLib(CGFunctionInfo &FI)
Drive the experimental LLVMABI-based lowering path: map argument and return types into the LLVMABI li...
const llvm::DataLayout & getDataLayout() const
ObjCEntrypoints & getObjCEntrypoints() const
CGCXXABI & getCXXABI() const
bool ReturnTypeUsesFP2Ret(QualType ResultType)
Return true iff the given type uses 'fp2ret' when used as a return type.
bool ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI)
Return true iff the given type uses an argument slot when 'sret' is used as a return type.
bool ReturnTypeHasInReg(const CGFunctionInfo &FI)
Return true iff the given type has inreg set.
void AdjustMemoryAttribute(StringRef Name, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs)
Adjust Memory attribute to ensure that the BE gets the right attribute.
void ConstructAttributeList(StringRef Name, const CGFunctionInfo &Info, CGCalleeInfo CalleeInfo, llvm::AttributeList &Attrs, unsigned &CallingConv, bool AttrOnCallSite, bool IsThunk)
Get the LLVM attributes and calling convention to use for a particular function type.
const llvm::abi::TargetInfo & getLLVMABITargetInfo(llvm::abi::TypeBuilder &TB)
Lazily build and return the LLVMABI library's TargetInfo for the current target.
ASTContext & getContext() const
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses 'sret' when used as a return type.
const TargetCodeGenInfo & getTargetCodeGenInfo()
const CodeGenOptions & getCodeGenOpts() const
void addDefaultFunctionDefinitionAttributes(llvm::AttrBuilder &attrs)
Like the overload taking a Function &, but intended specifically for frontends that want to build on ...
CharUnits getNaturalPointeeTypeAlignment(QualType T, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
llvm::LLVMContext & getLLVMContext()
CharUnits getMinimumObjectSize(QualType Ty)
Returns the minimum object size for an object of the given type.
bool MayDropFunctionReturn(const ASTContext &Context, QualType ReturnType) const
Whether this function's return type has no side effects, and thus may be trivially discarded if it is...
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
const CGFunctionInfo & arrangeLLVMFunctionInfo(CanQualType returnType, FnInfoOpts opts, ArrayRef< CanQualType > argTypes, FunctionType::ExtInfo info, ArrayRef< FunctionProtoType::ExtParameterInfo > paramInfos, RequiredArgs args, const FunctionDecl *ABIInfoFD)
"Arrange" the LLVM information for a call or type with the given signature.
const CGFunctionInfo & arrangeFreeFunctionCall(const CallArgList &Args, const FunctionType *Ty, bool ChainCall, const FunctionDecl *ABIInfoFD)
Figure out the rules for calling a function with the given formal type using the given arguments.
const CGFunctionInfo & arrangeCXXMethodType(const CXXRecordDecl *RD, const FunctionProtoType *FTP, const CXXMethodDecl *MD)
Arrange the argument and result information for a call to an unknown C++ non-static member function o...
const CGFunctionInfo & arrangeCXXConstructorCall(const CallArgList &Args, const CXXConstructorDecl *D, CXXCtorType CtorKind, unsigned ExtraPrefixArgs, unsigned ExtraSuffixArgs, const FunctionDecl *ABIInfoFD, bool PassProtoArgs=true)
Arrange a call to a C++ method, passing the given arguments.
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
CGCXXABI & getCXXABI() const
const CGFunctionInfo & arrangeCXXMethodCall(const CallArgList &args, const FunctionProtoType *type, RequiredArgs required, unsigned numPrefixArgs, const FunctionDecl *ABIInfoFD)
Arrange a call to a C++ method, passing the given arguments.
const CGFunctionInfo & arrangeCXXMethodDeclaration(const CXXMethodDecl *MD)
C++ methods have some special rules and also have implicit parameters.
ASTContext & getContext() const
const CGFunctionInfo & arrangeFreeFunctionType(CanQual< FunctionProtoType > Ty)
Arrange the argument and result information for a value of the given freestanding function type.
CanQualType DeriveThisType(const CXXRecordDecl *RD, const CXXMethodDecl *MD)
Derives the 'this' type for codegen purposes, i.e.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
bool inheritingCtorHasParams(const InheritedConstructor &Inherited, CXXCtorType Type)
Determine if a C++ inheriting constructor should have parameters matching those of its inherited cons...
bool isFuncTypeConvertible(const FunctionType *FT)
isFuncTypeConvertible - Utility to check whether a function type can be converted to an LLVM type (i....
const CGFunctionInfo & arrangeBlockFunctionCall(const CallArgList &args, const FunctionType *type)
A block function is essentially a free function with an extra implicit argument.
const CGFunctionInfo & arrangeBuiltinFunctionDeclaration(QualType resultType, const FunctionArgList &args)
A builtin function is a freestanding function using the default C conventions.
const CGFunctionInfo & arrangeUnprototypedObjCMessageSend(QualType returnType, const CallArgList &args)
const CGRecordLayout & getCGRecordLayout(const RecordDecl *)
getCGRecordLayout - Return record layout info for the given record decl.
void getExpandedTypes(QualType Ty, SmallVectorImpl< llvm::Type * >::iterator &TI)
getExpandedTypes - Expand the type
llvm::Type * ConvertTypeForMem(QualType T)
ConvertTypeForMem - Convert type T into a llvm::Type.
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
llvm::LLVMContext & getLLVMContext()
const CGFunctionInfo & arrangeDeviceKernelCallerDeclaration(QualType resultType, const FunctionArgList &args)
A device kernel caller function is an offload device entry point function with a target device depend...
const CGFunctionInfo & arrangeGlobalDeclaration(GlobalDecl GD)
const CGFunctionInfo & arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD)
Arrange a thunk that takes 'this' as the first parameter followed by varargs.
const CGFunctionInfo & arrangeBuiltinFunctionCall(QualType resultType, const CallArgList &args)
const CGFunctionInfo & arrangeBlockFunctionDeclaration(const FunctionProtoType *type, const FunctionArgList &args)
Block invocation functions are C functions with an implicit parameter.
unsigned ClangCallConvToLLVMCallConv(CallingConv CC)
Convert clang calling convention to LLVM callilng convention.
llvm::Type * GetFunctionTypeForVTable(GlobalDecl GD)
GetFunctionTypeForVTable - Get the LLVM function type for use in a vtable, given a CXXMethodDecl.
const CGFunctionInfo & arrangeCall(const CGFunctionInfo &declFI, const CallArgList &args, const FunctionDecl *ABIInfoFD)
Given a function info for a declaration, return the function info for a call with the given arguments...
const CGFunctionInfo & arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, QualType receiverType)
Arrange the argument and result information for the function type through which to perform a send to ...
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
const CGFunctionInfo & arrangeFunctionDeclaration(const GlobalDecl GD)
Free functions are functions that are compatible with an ordinary C function pointer type.
const CGFunctionInfo & arrangeMSCtorClosure(const CXXConstructorDecl *CD, CXXCtorType CT)
const CGFunctionInfo & arrangeNullaryFunction()
A nullary function is a freestanding function of type 'void ()'.
A cleanup scope which generates the cleanup blocks lazily.
A saved depth on the scope stack.
FunctionArgList - Type for representing both the decl and type of parameters to a function.
LValue - This represents an lvalue references.
static LValue MakeAddr(Address Addr, QualType type, ASTContext &Context, LValueBaseInfo BaseInfo, TBAAAccessInfo TBAAInfo)
Address getAddress() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
static RValue get(llvm::Value *V)
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
static RValue getComplex(llvm::Value *V1, llvm::Value *V2)
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
An abstract representation of an aligned address.
CharUnits getAlignment() const
Return the alignment of this pointer.
llvm::Value * getPointer() const
static RawAddress invalid()
A class for recording the number of arguments that a function signature requires.
bool allowsOptionalArgs() const
unsigned getNumRequiredArgs() const
static RequiredArgs forPrototypePlus(const FunctionProtoType *prototype, unsigned additional)
Compute the arguments required by the given formal prototype, given that there may be some additional...
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
virtual void setCUDAKernelCallingConvention(const FunctionType *&FT) const
static void initPointerAuthFnAttributes(const PointerAuthOptions &Opts, llvm::AttrBuilder &FuncAttrs)
static void initBranchProtectionFnAttributes(const TargetInfo::BranchProtectionInfo &BPI, llvm::AttrBuilder &FuncAttrs)
virtual bool isNoProtoCallVariadic(const CodeGen::CallArgList &args, const FunctionNoProtoType *fnType) const
Determine whether a call to an unprototyped functions under the given calling convention should use t...
Complex values, per C99 6.2.5p11.
Represents the canonical version of C arrays with a specified constant size.
bool constructsVirtualBase() const
Returns true if the constructed base class is a virtual base class subobject of this declaration's cl...
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Decl - This represents one declaration (or definition), e.g.
const FunctionType * getFunctionType(bool BlocksToo=true) const
Looks through the Decl's underlying type to extract a FunctionType when possible.
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
DeclContext * getDeclContext()
SourceLocation getBeginLoc() const LLVM_READONLY
This represents one expression.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
@ NPC_ValueDependentIsNotNull
Specifies that a value-dependent expression should be considered to never be a null pointer constant.
ExprObjectKind getObjectKind() const
getObjectKind - The object kind that this expression produces.
NullPointerConstantKind isNullPointerConstant(ASTContext &Ctx, NullPointerConstantValueDependence NPC) const
isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to a Null pointer constant.
Represents a member of a struct/union/class.
bool isBitField() const
Determines whether this field is a bitfield.
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
bool isZeroLengthBitField() const
Is this a zero-length bit-field?
Represents a function declaration or definition.
Represents a K&R-style 'int foo()' function, which has no information available about its arguments.
Represents a prototype with parameter type info, e.g.
ExceptionSpecificationType getExceptionSpecType() const
Get the kind of exception specification on this function.
unsigned getNumParams() const
unsigned getAArch64SMEAttributes() const
Return a bitmask describing the SME attributes on the function type, see AArch64SMETypeAttributes for...
bool isNothrow(bool ResultIfDependent=false) const
Determine whether this function type has a non-throwing exception specification.
ArrayRef< ExtParameterInfo > getExtParameterInfos() const
bool hasExtParameterInfos() const
Is there any interesting extra information for any of the parameters of this function type?
Wrapper for source info for functions.
A class which abstracts out some details necessary for making a call.
ExtInfo withCallingConv(CallingConv cc) const
ExtInfo withProducesResult(bool producesResult) const
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
ParameterABI getABI() const
Return the ABI treatment of this parameter.
ExtParameterInfo withIsNoEscape(bool NoEscape) const
FunctionType - C99 6.7.5.3 - Function Declarators.
ExtInfo getExtInfo() const
@ SME_PStateSMEnabledMask
@ SME_PStateSMCompatibleMask
@ SME_AgnosticZAStateMask
static ArmStateValue getArmZT0State(unsigned AttrBits)
static ArmStateValue getArmZAState(unsigned AttrBits)
QualType getReturnType() const
GlobalDecl - represents a global declaration.
CXXCtorType getCtorType() const
KernelReferenceKind getKernelReferenceKind() const
CXXDtorType getDtorType() const
const Decl * getDecl() const
This class represents temporary values used to represent inout and out arguments in HLSL.
Description of a constructor that was inherited from a base class.
ConstructorUsingShadowDecl * getShadowDecl() const
@ FPE_Ignore
Assume that floating-point exceptions are masked.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
std::vector< std::string > NoBuiltinFuncs
A list of all -fno-builtin-* function names (e.g., memset).
FPExceptionModeKind getDefaultExceptionMode() const
bool isNoBuiltinFunc(StringRef Name) const
Is this a libc/libm function that is no longer recognized as a builtin because a -fno-builtin-* optio...
bool assumeFunctionsAreConvergent() const
Represents a point when the lifetime of an automatic object ends.
Represents a matrix type, as defined in the Matrix Types clang extensions.
Describes a module or submodule.
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
ObjCCategoryDecl - Represents a category declaration.
ObjCIndirectCopyRestoreExpr - Represents the passing of a function argument by indirect copy-restore ...
bool shouldCopy() const
shouldCopy - True if we should do the 'copy' part of the copy-restore.
Represents an ObjC class declaration.
ObjCMethodDecl - Represents an instance or class method declaration.
ImplicitParamDecl * getSelfDecl() const
ArrayRef< ParmVarDecl * > parameters() const
bool isDirectMethod() const
True if the method is tagged as objc_direct.
QualType getReturnType() const
Represents a parameter to a function.
PointerType - C99 6.7.5.1 - Pointer Declarators.
A (possibly-)qualified type.
bool isRestrictQualified() const
Determine whether this type is restrict-qualified.
bool isTriviallyCopyableType(const ASTContext &Context) const
Return true if this is a trivially copyable type (C++0x [basic.types]p9)
bool isNull() const
Return true if this QualType doesn't point to a type yet.
LangAS getAddressSpace() const
Return the address space of this type.
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
QualType getCanonicalType() const
bool isConstQualified() const
Determine whether this type is const-qualified.
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
LangAS getAddressSpace() const
Represents a struct/union/class.
field_iterator field_end() const
bool isParamDestroyedInCallee() const
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
field_iterator field_begin() const
Base for LValueReferenceType and RValueReferenceType.
Encodes a location in the source.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Options for controlling the target.
std::vector< std::string > Features
The list of target specific features to enable or disable – this should be a list of strings starting...
std::string TuneCPU
If given, the name of the target CPU to tune code for.
std::string CPU
If given, the name of the target CPU to generate code for.
llvm::StringMap< bool > FeatureMap
The map of which features have been enabled disabled based on the command line.
The base class of the type hierarchy.
bool isIncompleteArrayType() const
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
bool isPointerType() const
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
const T * castAs() const
Member-template castAs<specific type>.
bool isReferenceType() const
bool isScalarType() const
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
bool isBitIntType() const
RecordDecl * castAsRecordDecl() const
bool isMemberPointerType() const
bool isFunctionProtoType() const
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
bool isObjectType() const
Determine whether this type is an object type.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
bool hasFloatingRepresentation() const
Determine whether this type has a floating-point representation of some sort, e.g....
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
const T * castAsCanonical() const
Return this type's canonical type cast to the specified type.
const T * getAs() const
Member-template getAs<specific type>'.
bool isNullPtrType() const
bool isRecordType() const
bool isObjCRetainableType() const
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Represents a call to the builtin function __builtin_va_arg.
Represents a variable declaration or definition.
QualType::DestructionKind needsDestruction(const ASTContext &Ctx) const
Would the destruction of this variable have any effect, and if so, what kind?
Represents a GCC generic vector type.
Defines the clang::TargetInfo interface.
void computeABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
Compute the ABI information of a swiftcall function.
@ Type
The l-value was considered opaque, so the alignment was determined from a type.
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI)
@ NormalCleanup
Denotes a cleanup that should run when a scope is exited using normal control flow (falling off the e...
void mergeDefaultFunctionDefinitionAttributes(llvm::Function &F, const CodeGenOptions &CodeGenOpts, const LangOptions &LangOpts, const TargetOptions &TargetOpts, bool WillInternalize)
Adds attributes to F according to our CodeGenOpts and LangOpts, as though we had emitted it ourselves...
QualType useFirstFieldIfTransparentUnion(QualType Ty)
Pass transparent unions as if they were the type of the first element.
bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays, bool AsIfNoUniqueAddr=false)
isEmptyRecord - Return true iff a structure contains only empty fields.
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
PRESERVE_NONE bool Ret(InterpState &S)
bool This(InterpState &S, CodePtr OpPC)
@ Address
A pointer to a ValueDecl.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
CXXCtorType
C++ constructor types.
@ Ctor_DefaultClosure
Default closure variant of a ctor.
@ Ctor_CopyingClosure
Copying closure variant of a ctor.
@ Ctor_Complete
Complete object ctor.
bool isa(CodeGen::Address addr)
static bool classof(const OMPClause *T)
bool isUnresolvedExceptionSpec(ExceptionSpecificationType ESpecType)
bool isInstanceMethod(const Decl *D)
@ NonNull
Values of this type can never be null.
@ OK_Ordinary
An ordinary object is located at an address in memory.
@ Vector
'vector' clause, allowed on 'loop', Combined, and 'routine' directives.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
@ SwiftAsyncContext
This parameter (which must have pointer type) uses the special Swift asynchronous context-pointer ABI...
@ SwiftErrorResult
This parameter (which must have pointer-to-pointer type) uses the special Swift error-result ABI trea...
@ Ordinary
This parameter uses ordinary ABI rules for its type.
@ SwiftIndirectResult
This parameter (which must have pointer type) is a Swift indirect result parameter.
@ SwiftContext
This parameter (which must have pointer type) uses the special Swift context-pointer ABI treatment.
const FunctionProtoType * T
@ Dtor_VectorDeleting
Vector deleting dtor.
@ Dtor_Complete
Complete object dtor.
@ Dtor_Deleting
Deleting dtor.
@ CanPassInRegs
The argument of this type can be passed directly in registers.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
U cast(CodeGen::Address addr)
@ Struct
The "struct" keyword introduces the elaborated-type-specifier.
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Structure with information about how a bitfield should be accessed.
CharUnits StorageOffset
The offset of the bitfield storage from the start of the struct.
unsigned Offset
The offset within a contiguous run of bitfields that are represented as a single "field" within the L...
unsigned Size
The total size of the bit-field, in bits.
unsigned StorageSize
The storage size in bits which should be used when accessing this bitfield.
Similar to AddedStructorArgs, but only notes the number of additional arguments.
llvm::Value * ToUse
A value to "use" after the writeback, or null.
LValue Source
The original argument.
Address Temporary
The temporary alloca.
const Expr * WritebackExpr
An Expression (optional) that performs the writeback with any required casting.
LValue getKnownLValue() const
RValue getKnownRValue() const
void copyInto(CodeGenFunction &CGF, Address A) const
RValue getRValue(CodeGenFunction &CGF) const
llvm::PointerType * VoidPtrTy
llvm::IntegerType * Int64Ty
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::CallingConv::ID getRuntimeCC() const
llvm::IntegerType * SizeTy
llvm::IntegerType * Int32Ty
llvm::IntegerType * IntPtrTy
llvm::PointerType * Int8PtrTy
CharUnits getPointerAlign() const
~DisableDebugLocationUpdates()
DisableDebugLocationUpdates(CodeGenFunction &CGF)
static const EHPersonality & get(CodeGenModule &CGM, const FunctionDecl *FD)
llvm::Function * objc_retainAutoreleasedReturnValue
id objc_retainAutoreleasedReturnValue(id);
llvm::Function * objc_retain
id objc_retain(id);
llvm::InlineAsm * retainAutoreleasedReturnValueMarker
A void(void) inline asm to use to mark that the return value of a call will be immediately retain.
Extra information about a function prototype.
bool has(SanitizerMask K) const
Check if a certain (single) sanitizer is enabled.