1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // These classes wrap the information about a call or function 10 // definition used to handle ABI compliancy. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGCall.h" 15 #include "ABIInfo.h" 16 #include "CGBlocks.h" 17 #include "CGCXXABI.h" 18 #include "CGCleanup.h" 19 #include "CGRecordLayout.h" 20 #include "CodeGenFunction.h" 21 #include "CodeGenModule.h" 22 #include "TargetInfo.h" 23 #include "clang/AST/Attr.h" 24 #include "clang/AST/Decl.h" 25 #include "clang/AST/DeclCXX.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/Basic/CodeGenOptions.h" 28 #include "clang/Basic/TargetBuiltins.h" 29 #include "clang/Basic/TargetInfo.h" 30 #include "clang/CodeGen/CGFunctionInfo.h" 31 #include "clang/CodeGen/SwiftCallingConv.h" 32 #include "llvm/ADT/StringExtras.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/IR/Assumptions.h" 35 #include "llvm/IR/Attributes.h" 36 #include "llvm/IR/CallingConv.h" 37 #include "llvm/IR/DataLayout.h" 38 #include "llvm/IR/InlineAsm.h" 39 #include "llvm/IR/IntrinsicInst.h" 40 #include "llvm/IR/Intrinsics.h" 41 #include "llvm/Transforms/Utils/Local.h" 42 using namespace clang; 43 using namespace CodeGen; 44 45 /***/ 46 47 unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) { 48 switch (CC) { 49 default: return llvm::CallingConv::C; 50 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall; 51 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall; 52 case CC_X86RegCall: return llvm::CallingConv::X86_RegCall; 53 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall; 54 case CC_Win64: return llvm::CallingConv::Win64; 55 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV; 56 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS; 57 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 58 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI; 59 // TODO: Add support for __pascal to LLVM. 60 case CC_X86Pascal: return llvm::CallingConv::C; 61 // TODO: Add support for __vectorcall to LLVM. 62 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall; 63 case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall; 64 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC; 65 case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv(); 66 case CC_PreserveMost: return llvm::CallingConv::PreserveMost; 67 case CC_PreserveAll: return llvm::CallingConv::PreserveAll; 68 case CC_Swift: return llvm::CallingConv::Swift; 69 } 70 } 71 72 /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR 73 /// qualification. Either or both of RD and MD may be null. A null RD indicates 74 /// that there is no meaningful 'this' type, and a null MD can occur when 75 /// calling a method pointer. 76 CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD, 77 const CXXMethodDecl *MD) { 78 QualType RecTy; 79 if (RD) 80 RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal(); 81 else 82 RecTy = Context.VoidTy; 83 84 if (MD) 85 RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace()); 86 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy)); 87 } 88 89 /// Returns the canonical formal type of the given C++ method. 90 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) { 91 return MD->getType()->getCanonicalTypeUnqualified() 92 .getAs<FunctionProtoType>(); 93 } 94 95 /// Returns the "extra-canonicalized" return type, which discards 96 /// qualifiers on the return type. Codegen doesn't care about them, 97 /// and it makes ABI code a little easier to be able to assume that 98 /// all parameter and return types are top-level unqualified. 99 static CanQualType GetReturnType(QualType RetTy) { 100 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType(); 101 } 102 103 /// Arrange the argument and result information for a value of the given 104 /// unprototyped freestanding function type. 105 const CGFunctionInfo & 106 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) { 107 // When translating an unprototyped function type, always use a 108 // variadic type. 109 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(), 110 /*instanceMethod=*/false, 111 /*chainCall=*/false, None, 112 FTNP->getExtInfo(), {}, RequiredArgs(0)); 113 } 114 115 static void addExtParameterInfosForCall( 116 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos, 117 const FunctionProtoType *proto, 118 unsigned prefixArgs, 119 unsigned totalArgs) { 120 assert(proto->hasExtParameterInfos()); 121 assert(paramInfos.size() <= prefixArgs); 122 assert(proto->getNumParams() + prefixArgs <= totalArgs); 123 124 paramInfos.reserve(totalArgs); 125 126 // Add default infos for any prefix args that don't already have infos. 127 paramInfos.resize(prefixArgs); 128 129 // Add infos for the prototype. 130 for (const auto &ParamInfo : proto->getExtParameterInfos()) { 131 paramInfos.push_back(ParamInfo); 132 // pass_object_size params have no parameter info. 133 if (ParamInfo.hasPassObjectSize()) 134 paramInfos.emplace_back(); 135 } 136 137 assert(paramInfos.size() <= totalArgs && 138 "Did we forget to insert pass_object_size args?"); 139 // Add default infos for the variadic and/or suffix arguments. 140 paramInfos.resize(totalArgs); 141 } 142 143 /// Adds the formal parameters in FPT to the given prefix. If any parameter in 144 /// FPT has pass_object_size attrs, then we'll add parameters for those, too. 145 static void appendParameterTypes(const CodeGenTypes &CGT, 146 SmallVectorImpl<CanQualType> &prefix, 147 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos, 148 CanQual<FunctionProtoType> FPT) { 149 // Fast path: don't touch param info if we don't need to. 150 if (!FPT->hasExtParameterInfos()) { 151 assert(paramInfos.empty() && 152 "We have paramInfos, but the prototype doesn't?"); 153 prefix.append(FPT->param_type_begin(), FPT->param_type_end()); 154 return; 155 } 156 157 unsigned PrefixSize = prefix.size(); 158 // In the vast majority of cases, we'll have precisely FPT->getNumParams() 159 // parameters; the only thing that can change this is the presence of 160 // pass_object_size. So, we preallocate for the common case. 161 prefix.reserve(prefix.size() + FPT->getNumParams()); 162 163 auto ExtInfos = FPT->getExtParameterInfos(); 164 assert(ExtInfos.size() == FPT->getNumParams()); 165 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) { 166 prefix.push_back(FPT->getParamType(I)); 167 if (ExtInfos[I].hasPassObjectSize()) 168 prefix.push_back(CGT.getContext().getSizeType()); 169 } 170 171 addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize, 172 prefix.size()); 173 } 174 175 /// Arrange the LLVM function layout for a value of the given function 176 /// type, on top of any implicit parameters already stored. 177 static const CGFunctionInfo & 178 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod, 179 SmallVectorImpl<CanQualType> &prefix, 180 CanQual<FunctionProtoType> FTP) { 181 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 182 RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size()); 183 // FIXME: Kill copy. 184 appendParameterTypes(CGT, prefix, paramInfos, FTP); 185 CanQualType resultType = FTP->getReturnType().getUnqualifiedType(); 186 187 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod, 188 /*chainCall=*/false, prefix, 189 FTP->getExtInfo(), paramInfos, 190 Required); 191 } 192 193 /// Arrange the argument and result information for a value of the 194 /// given freestanding function type. 195 const CGFunctionInfo & 196 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) { 197 SmallVector<CanQualType, 16> argTypes; 198 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes, 199 FTP); 200 } 201 202 static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D, 203 bool IsWindows) { 204 // Set the appropriate calling convention for the Function. 205 if (D->hasAttr<StdCallAttr>()) 206 return CC_X86StdCall; 207 208 if (D->hasAttr<FastCallAttr>()) 209 return CC_X86FastCall; 210 211 if (D->hasAttr<RegCallAttr>()) 212 return CC_X86RegCall; 213 214 if (D->hasAttr<ThisCallAttr>()) 215 return CC_X86ThisCall; 216 217 if (D->hasAttr<VectorCallAttr>()) 218 return CC_X86VectorCall; 219 220 if (D->hasAttr<PascalAttr>()) 221 return CC_X86Pascal; 222 223 if (PcsAttr *PCS = D->getAttr<PcsAttr>()) 224 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP); 225 226 if (D->hasAttr<AArch64VectorPcsAttr>()) 227 return CC_AArch64VectorCall; 228 229 if (D->hasAttr<IntelOclBiccAttr>()) 230 return CC_IntelOclBicc; 231 232 if (D->hasAttr<MSABIAttr>()) 233 return IsWindows ? CC_C : CC_Win64; 234 235 if (D->hasAttr<SysVABIAttr>()) 236 return IsWindows ? CC_X86_64SysV : CC_C; 237 238 if (D->hasAttr<PreserveMostAttr>()) 239 return CC_PreserveMost; 240 241 if (D->hasAttr<PreserveAllAttr>()) 242 return CC_PreserveAll; 243 244 return CC_C; 245 } 246 247 /// Arrange the argument and result information for a call to an 248 /// unknown C++ non-static member function of the given abstract type. 249 /// (A null RD means we don't have any meaningful "this" argument type, 250 /// so fall back to a generic pointer type). 251 /// The member function must be an ordinary function, i.e. not a 252 /// constructor or destructor. 253 const CGFunctionInfo & 254 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD, 255 const FunctionProtoType *FTP, 256 const CXXMethodDecl *MD) { 257 SmallVector<CanQualType, 16> argTypes; 258 259 // Add the 'this' pointer. 260 argTypes.push_back(DeriveThisType(RD, MD)); 261 262 return ::arrangeLLVMFunctionInfo( 263 *this, true, argTypes, 264 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>()); 265 } 266 267 /// Set calling convention for CUDA/HIP kernel. 268 static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM, 269 const FunctionDecl *FD) { 270 if (FD->hasAttr<CUDAGlobalAttr>()) { 271 const FunctionType *FT = FTy->getAs<FunctionType>(); 272 CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT); 273 FTy = FT->getCanonicalTypeUnqualified(); 274 } 275 } 276 277 /// Arrange the argument and result information for a declaration or 278 /// definition of the given C++ non-static member function. The 279 /// member function must be an ordinary function, i.e. not a 280 /// constructor or destructor. 281 const CGFunctionInfo & 282 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) { 283 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!"); 284 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!"); 285 286 CanQualType FT = GetFormalType(MD).getAs<Type>(); 287 setCUDAKernelCallingConvention(FT, CGM, MD); 288 auto prototype = FT.getAs<FunctionProtoType>(); 289 290 if (MD->isInstance()) { 291 // The abstract case is perfectly fine. 292 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD); 293 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD); 294 } 295 296 return arrangeFreeFunctionType(prototype); 297 } 298 299 bool CodeGenTypes::inheritingCtorHasParams( 300 const InheritedConstructor &Inherited, CXXCtorType Type) { 301 // Parameters are unnecessary if we're constructing a base class subobject 302 // and the inherited constructor lives in a virtual base. 303 return Type == Ctor_Complete || 304 !Inherited.getShadowDecl()->constructsVirtualBase() || 305 !Target.getCXXABI().hasConstructorVariants(); 306 } 307 308 const CGFunctionInfo & 309 CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) { 310 auto *MD = cast<CXXMethodDecl>(GD.getDecl()); 311 312 SmallVector<CanQualType, 16> argTypes; 313 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 314 argTypes.push_back(DeriveThisType(MD->getParent(), MD)); 315 316 bool PassParams = true; 317 318 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 319 // A base class inheriting constructor doesn't get forwarded arguments 320 // needed to construct a virtual base (or base class thereof). 321 if (auto Inherited = CD->getInheritedConstructor()) 322 PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType()); 323 } 324 325 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 326 327 // Add the formal parameters. 328 if (PassParams) 329 appendParameterTypes(*this, argTypes, paramInfos, FTP); 330 331 CGCXXABI::AddedStructorArgCounts AddedArgs = 332 TheCXXABI.buildStructorSignature(GD, argTypes); 333 if (!paramInfos.empty()) { 334 // Note: prefix implies after the first param. 335 if (AddedArgs.Prefix) 336 paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix, 337 FunctionProtoType::ExtParameterInfo{}); 338 if (AddedArgs.Suffix) 339 paramInfos.append(AddedArgs.Suffix, 340 FunctionProtoType::ExtParameterInfo{}); 341 } 342 343 RequiredArgs required = 344 (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size()) 345 : RequiredArgs::All); 346 347 FunctionType::ExtInfo extInfo = FTP->getExtInfo(); 348 CanQualType resultType = TheCXXABI.HasThisReturn(GD) 349 ? argTypes.front() 350 : TheCXXABI.hasMostDerivedReturn(GD) 351 ? CGM.getContext().VoidPtrTy 352 : Context.VoidTy; 353 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true, 354 /*chainCall=*/false, argTypes, extInfo, 355 paramInfos, required); 356 } 357 358 static SmallVector<CanQualType, 16> 359 getArgTypesForCall(ASTContext &ctx, const CallArgList &args) { 360 SmallVector<CanQualType, 16> argTypes; 361 for (auto &arg : args) 362 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty)); 363 return argTypes; 364 } 365 366 static SmallVector<CanQualType, 16> 367 getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) { 368 SmallVector<CanQualType, 16> argTypes; 369 for (auto &arg : args) 370 argTypes.push_back(ctx.getCanonicalParamType(arg->getType())); 371 return argTypes; 372 } 373 374 static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> 375 getExtParameterInfosForCall(const FunctionProtoType *proto, 376 unsigned prefixArgs, unsigned totalArgs) { 377 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result; 378 if (proto->hasExtParameterInfos()) { 379 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs); 380 } 381 return result; 382 } 383 384 /// Arrange a call to a C++ method, passing the given arguments. 385 /// 386 /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this` 387 /// parameter. 388 /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of 389 /// args. 390 /// PassProtoArgs indicates whether `args` has args for the parameters in the 391 /// given CXXConstructorDecl. 392 const CGFunctionInfo & 393 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args, 394 const CXXConstructorDecl *D, 395 CXXCtorType CtorKind, 396 unsigned ExtraPrefixArgs, 397 unsigned ExtraSuffixArgs, 398 bool PassProtoArgs) { 399 // FIXME: Kill copy. 400 SmallVector<CanQualType, 16> ArgTypes; 401 for (const auto &Arg : args) 402 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 403 404 // +1 for implicit this, which should always be args[0]. 405 unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs; 406 407 CanQual<FunctionProtoType> FPT = GetFormalType(D); 408 RequiredArgs Required = PassProtoArgs 409 ? RequiredArgs::forPrototypePlus( 410 FPT, TotalPrefixArgs + ExtraSuffixArgs) 411 : RequiredArgs::All; 412 413 GlobalDecl GD(D, CtorKind); 414 CanQualType ResultType = TheCXXABI.HasThisReturn(GD) 415 ? ArgTypes.front() 416 : TheCXXABI.hasMostDerivedReturn(GD) 417 ? CGM.getContext().VoidPtrTy 418 : Context.VoidTy; 419 420 FunctionType::ExtInfo Info = FPT->getExtInfo(); 421 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos; 422 // If the prototype args are elided, we should only have ABI-specific args, 423 // which never have param info. 424 if (PassProtoArgs && FPT->hasExtParameterInfos()) { 425 // ABI-specific suffix arguments are treated the same as variadic arguments. 426 addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs, 427 ArgTypes.size()); 428 } 429 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true, 430 /*chainCall=*/false, ArgTypes, Info, 431 ParamInfos, Required); 432 } 433 434 /// Arrange the argument and result information for the declaration or 435 /// definition of the given function. 436 const CGFunctionInfo & 437 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) { 438 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 439 if (MD->isInstance()) 440 return arrangeCXXMethodDeclaration(MD); 441 442 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified(); 443 444 assert(isa<FunctionType>(FTy)); 445 setCUDAKernelCallingConvention(FTy, CGM, FD); 446 447 // When declaring a function without a prototype, always use a 448 // non-variadic type. 449 if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) { 450 return arrangeLLVMFunctionInfo( 451 noProto->getReturnType(), /*instanceMethod=*/false, 452 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All); 453 } 454 455 return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>()); 456 } 457 458 /// Arrange the argument and result information for the declaration or 459 /// definition of an Objective-C method. 460 const CGFunctionInfo & 461 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) { 462 // It happens that this is the same as a call with no optional 463 // arguments, except also using the formal 'self' type. 464 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType()); 465 } 466 467 /// Arrange the argument and result information for the function type 468 /// through which to perform a send to the given Objective-C method, 469 /// using the given receiver type. The receiver type is not always 470 /// the 'self' type of the method or even an Objective-C pointer type. 471 /// This is *not* the right method for actually performing such a 472 /// message send, due to the possibility of optional arguments. 473 const CGFunctionInfo & 474 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, 475 QualType receiverType) { 476 SmallVector<CanQualType, 16> argTys; 477 SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2); 478 argTys.push_back(Context.getCanonicalParamType(receiverType)); 479 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())); 480 // FIXME: Kill copy? 481 for (const auto *I : MD->parameters()) { 482 argTys.push_back(Context.getCanonicalParamType(I->getType())); 483 auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape( 484 I->hasAttr<NoEscapeAttr>()); 485 extParamInfos.push_back(extParamInfo); 486 } 487 488 FunctionType::ExtInfo einfo; 489 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows(); 490 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows)); 491 492 if (getContext().getLangOpts().ObjCAutoRefCount && 493 MD->hasAttr<NSReturnsRetainedAttr>()) 494 einfo = einfo.withProducesResult(true); 495 496 RequiredArgs required = 497 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All); 498 499 return arrangeLLVMFunctionInfo( 500 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false, 501 /*chainCall=*/false, argTys, einfo, extParamInfos, required); 502 } 503 504 const CGFunctionInfo & 505 CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType, 506 const CallArgList &args) { 507 auto argTypes = getArgTypesForCall(Context, args); 508 FunctionType::ExtInfo einfo; 509 510 return arrangeLLVMFunctionInfo( 511 GetReturnType(returnType), /*instanceMethod=*/false, 512 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All); 513 } 514 515 const CGFunctionInfo & 516 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) { 517 // FIXME: Do we need to handle ObjCMethodDecl? 518 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 519 520 if (isa<CXXConstructorDecl>(GD.getDecl()) || 521 isa<CXXDestructorDecl>(GD.getDecl())) 522 return arrangeCXXStructorDeclaration(GD); 523 524 return arrangeFunctionDeclaration(FD); 525 } 526 527 /// Arrange a thunk that takes 'this' as the first parameter followed by 528 /// varargs. Return a void pointer, regardless of the actual return type. 529 /// The body of the thunk will end in a musttail call to a function of the 530 /// correct type, and the caller will bitcast the function to the correct 531 /// prototype. 532 const CGFunctionInfo & 533 CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) { 534 assert(MD->isVirtual() && "only methods have thunks"); 535 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 536 CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)}; 537 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false, 538 /*chainCall=*/false, ArgTys, 539 FTP->getExtInfo(), {}, RequiredArgs(1)); 540 } 541 542 const CGFunctionInfo & 543 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD, 544 CXXCtorType CT) { 545 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure); 546 547 CanQual<FunctionProtoType> FTP = GetFormalType(CD); 548 SmallVector<CanQualType, 2> ArgTys; 549 const CXXRecordDecl *RD = CD->getParent(); 550 ArgTys.push_back(DeriveThisType(RD, CD)); 551 if (CT == Ctor_CopyingClosure) 552 ArgTys.push_back(*FTP->param_type_begin()); 553 if (RD->getNumVBases() > 0) 554 ArgTys.push_back(Context.IntTy); 555 CallingConv CC = Context.getDefaultCallingConvention( 556 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 557 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true, 558 /*chainCall=*/false, ArgTys, 559 FunctionType::ExtInfo(CC), {}, 560 RequiredArgs::All); 561 } 562 563 /// Arrange a call as unto a free function, except possibly with an 564 /// additional number of formal parameters considered required. 565 static const CGFunctionInfo & 566 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT, 567 CodeGenModule &CGM, 568 const CallArgList &args, 569 const FunctionType *fnType, 570 unsigned numExtraRequiredArgs, 571 bool chainCall) { 572 assert(args.size() >= numExtraRequiredArgs); 573 574 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 575 576 // In most cases, there are no optional arguments. 577 RequiredArgs required = RequiredArgs::All; 578 579 // If we have a variadic prototype, the required arguments are the 580 // extra prefix plus the arguments in the prototype. 581 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) { 582 if (proto->isVariadic()) 583 required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs); 584 585 if (proto->hasExtParameterInfos()) 586 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs, 587 args.size()); 588 589 // If we don't have a prototype at all, but we're supposed to 590 // explicitly use the variadic convention for unprototyped calls, 591 // treat all of the arguments as required but preserve the nominal 592 // possibility of variadics. 593 } else if (CGM.getTargetCodeGenInfo() 594 .isNoProtoCallVariadic(args, 595 cast<FunctionNoProtoType>(fnType))) { 596 required = RequiredArgs(args.size()); 597 } 598 599 // FIXME: Kill copy. 600 SmallVector<CanQualType, 16> argTypes; 601 for (const auto &arg : args) 602 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty)); 603 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()), 604 /*instanceMethod=*/false, chainCall, 605 argTypes, fnType->getExtInfo(), paramInfos, 606 required); 607 } 608 609 /// Figure out the rules for calling a function with the given formal 610 /// type using the given arguments. The arguments are necessary 611 /// because the function might be unprototyped, in which case it's 612 /// target-dependent in crazy ways. 613 const CGFunctionInfo & 614 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args, 615 const FunctionType *fnType, 616 bool chainCall) { 617 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 618 chainCall ? 1 : 0, chainCall); 619 } 620 621 /// A block function is essentially a free function with an 622 /// extra implicit argument. 623 const CGFunctionInfo & 624 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args, 625 const FunctionType *fnType) { 626 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1, 627 /*chainCall=*/false); 628 } 629 630 const CGFunctionInfo & 631 CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto, 632 const FunctionArgList ¶ms) { 633 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size()); 634 auto argTypes = getArgTypesForDeclaration(Context, params); 635 636 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()), 637 /*instanceMethod*/ false, /*chainCall*/ false, 638 argTypes, proto->getExtInfo(), paramInfos, 639 RequiredArgs::forPrototypePlus(proto, 1)); 640 } 641 642 const CGFunctionInfo & 643 CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType, 644 const CallArgList &args) { 645 // FIXME: Kill copy. 646 SmallVector<CanQualType, 16> argTypes; 647 for (const auto &Arg : args) 648 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 649 return arrangeLLVMFunctionInfo( 650 GetReturnType(resultType), /*instanceMethod=*/false, 651 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(), 652 /*paramInfos=*/ {}, RequiredArgs::All); 653 } 654 655 const CGFunctionInfo & 656 CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType, 657 const FunctionArgList &args) { 658 auto argTypes = getArgTypesForDeclaration(Context, args); 659 660 return arrangeLLVMFunctionInfo( 661 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false, 662 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All); 663 } 664 665 const CGFunctionInfo & 666 CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType, 667 ArrayRef<CanQualType> argTypes) { 668 return arrangeLLVMFunctionInfo( 669 resultType, /*instanceMethod=*/false, /*chainCall=*/false, 670 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All); 671 } 672 673 /// Arrange a call to a C++ method, passing the given arguments. 674 /// 675 /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It 676 /// does not count `this`. 677 const CGFunctionInfo & 678 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args, 679 const FunctionProtoType *proto, 680 RequiredArgs required, 681 unsigned numPrefixArgs) { 682 assert(numPrefixArgs + 1 <= args.size() && 683 "Emitting a call with less args than the required prefix?"); 684 // Add one to account for `this`. It's a bit awkward here, but we don't count 685 // `this` in similar places elsewhere. 686 auto paramInfos = 687 getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size()); 688 689 // FIXME: Kill copy. 690 auto argTypes = getArgTypesForCall(Context, args); 691 692 FunctionType::ExtInfo info = proto->getExtInfo(); 693 return arrangeLLVMFunctionInfo( 694 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true, 695 /*chainCall=*/false, argTypes, info, paramInfos, required); 696 } 697 698 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() { 699 return arrangeLLVMFunctionInfo( 700 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false, 701 None, FunctionType::ExtInfo(), {}, RequiredArgs::All); 702 } 703 704 const CGFunctionInfo & 705 CodeGenTypes::arrangeCall(const CGFunctionInfo &signature, 706 const CallArgList &args) { 707 assert(signature.arg_size() <= args.size()); 708 if (signature.arg_size() == args.size()) 709 return signature; 710 711 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 712 auto sigParamInfos = signature.getExtParameterInfos(); 713 if (!sigParamInfos.empty()) { 714 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end()); 715 paramInfos.resize(args.size()); 716 } 717 718 auto argTypes = getArgTypesForCall(Context, args); 719 720 assert(signature.getRequiredArgs().allowsOptionalArgs()); 721 return arrangeLLVMFunctionInfo(signature.getReturnType(), 722 signature.isInstanceMethod(), 723 signature.isChainCall(), 724 argTypes, 725 signature.getExtInfo(), 726 paramInfos, 727 signature.getRequiredArgs()); 728 } 729 730 namespace clang { 731 namespace CodeGen { 732 void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI); 733 } 734 } 735 736 /// Arrange the argument and result information for an abstract value 737 /// of a given function type. This is the method which all of the 738 /// above functions ultimately defer to. 739 const CGFunctionInfo & 740 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType, 741 bool instanceMethod, 742 bool chainCall, 743 ArrayRef<CanQualType> argTypes, 744 FunctionType::ExtInfo info, 745 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos, 746 RequiredArgs required) { 747 assert(llvm::all_of(argTypes, 748 [](CanQualType T) { return T.isCanonicalAsParam(); })); 749 750 // Lookup or create unique function info. 751 llvm::FoldingSetNodeID ID; 752 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos, 753 required, resultType, argTypes); 754 755 void *insertPos = nullptr; 756 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos); 757 if (FI) 758 return *FI; 759 760 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC()); 761 762 // Construct the function info. We co-allocate the ArgInfos. 763 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info, 764 paramInfos, resultType, argTypes, required); 765 FunctionInfos.InsertNode(FI, insertPos); 766 767 bool inserted = FunctionsBeingProcessed.insert(FI).second; 768 (void)inserted; 769 assert(inserted && "Recursively being processed?"); 770 771 // Compute ABI information. 772 if (CC == llvm::CallingConv::SPIR_KERNEL) { 773 // Force target independent argument handling for the host visible 774 // kernel functions. 775 computeSPIRKernelABIInfo(CGM, *FI); 776 } else if (info.getCC() == CC_Swift) { 777 swiftcall::computeABIInfo(CGM, *FI); 778 } else { 779 getABIInfo().computeInfo(*FI); 780 } 781 782 // Loop over all of the computed argument and return value info. If any of 783 // them are direct or extend without a specified coerce type, specify the 784 // default now. 785 ABIArgInfo &retInfo = FI->getReturnInfo(); 786 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr) 787 retInfo.setCoerceToType(ConvertType(FI->getReturnType())); 788 789 for (auto &I : FI->arguments()) 790 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr) 791 I.info.setCoerceToType(ConvertType(I.type)); 792 793 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased; 794 assert(erased && "Not in set?"); 795 796 return *FI; 797 } 798 799 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, 800 bool instanceMethod, 801 bool chainCall, 802 const FunctionType::ExtInfo &info, 803 ArrayRef<ExtParameterInfo> paramInfos, 804 CanQualType resultType, 805 ArrayRef<CanQualType> argTypes, 806 RequiredArgs required) { 807 assert(paramInfos.empty() || paramInfos.size() == argTypes.size()); 808 assert(!required.allowsOptionalArgs() || 809 required.getNumRequiredArgs() <= argTypes.size()); 810 811 void *buffer = 812 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>( 813 argTypes.size() + 1, paramInfos.size())); 814 815 CGFunctionInfo *FI = new(buffer) CGFunctionInfo(); 816 FI->CallingConvention = llvmCC; 817 FI->EffectiveCallingConvention = llvmCC; 818 FI->ASTCallingConvention = info.getCC(); 819 FI->InstanceMethod = instanceMethod; 820 FI->ChainCall = chainCall; 821 FI->CmseNSCall = info.getCmseNSCall(); 822 FI->NoReturn = info.getNoReturn(); 823 FI->ReturnsRetained = info.getProducesResult(); 824 FI->NoCallerSavedRegs = info.getNoCallerSavedRegs(); 825 FI->NoCfCheck = info.getNoCfCheck(); 826 FI->Required = required; 827 FI->HasRegParm = info.getHasRegParm(); 828 FI->RegParm = info.getRegParm(); 829 FI->ArgStruct = nullptr; 830 FI->ArgStructAlign = 0; 831 FI->NumArgs = argTypes.size(); 832 FI->HasExtParameterInfos = !paramInfos.empty(); 833 FI->getArgsBuffer()[0].type = resultType; 834 for (unsigned i = 0, e = argTypes.size(); i != e; ++i) 835 FI->getArgsBuffer()[i + 1].type = argTypes[i]; 836 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i) 837 FI->getExtParameterInfosBuffer()[i] = paramInfos[i]; 838 return FI; 839 } 840 841 /***/ 842 843 namespace { 844 // ABIArgInfo::Expand implementation. 845 846 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded. 847 struct TypeExpansion { 848 enum TypeExpansionKind { 849 // Elements of constant arrays are expanded recursively. 850 TEK_ConstantArray, 851 // Record fields are expanded recursively (but if record is a union, only 852 // the field with the largest size is expanded). 853 TEK_Record, 854 // For complex types, real and imaginary parts are expanded recursively. 855 TEK_Complex, 856 // All other types are not expandable. 857 TEK_None 858 }; 859 860 const TypeExpansionKind Kind; 861 862 TypeExpansion(TypeExpansionKind K) : Kind(K) {} 863 virtual ~TypeExpansion() {} 864 }; 865 866 struct ConstantArrayExpansion : TypeExpansion { 867 QualType EltTy; 868 uint64_t NumElts; 869 870 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts) 871 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {} 872 static bool classof(const TypeExpansion *TE) { 873 return TE->Kind == TEK_ConstantArray; 874 } 875 }; 876 877 struct RecordExpansion : TypeExpansion { 878 SmallVector<const CXXBaseSpecifier *, 1> Bases; 879 880 SmallVector<const FieldDecl *, 1> Fields; 881 882 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases, 883 SmallVector<const FieldDecl *, 1> &&Fields) 884 : TypeExpansion(TEK_Record), Bases(std::move(Bases)), 885 Fields(std::move(Fields)) {} 886 static bool classof(const TypeExpansion *TE) { 887 return TE->Kind == TEK_Record; 888 } 889 }; 890 891 struct ComplexExpansion : TypeExpansion { 892 QualType EltTy; 893 894 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {} 895 static bool classof(const TypeExpansion *TE) { 896 return TE->Kind == TEK_Complex; 897 } 898 }; 899 900 struct NoExpansion : TypeExpansion { 901 NoExpansion() : TypeExpansion(TEK_None) {} 902 static bool classof(const TypeExpansion *TE) { 903 return TE->Kind == TEK_None; 904 } 905 }; 906 } // namespace 907 908 static std::unique_ptr<TypeExpansion> 909 getTypeExpansion(QualType Ty, const ASTContext &Context) { 910 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 911 return std::make_unique<ConstantArrayExpansion>( 912 AT->getElementType(), AT->getSize().getZExtValue()); 913 } 914 if (const RecordType *RT = Ty->getAs<RecordType>()) { 915 SmallVector<const CXXBaseSpecifier *, 1> Bases; 916 SmallVector<const FieldDecl *, 1> Fields; 917 const RecordDecl *RD = RT->getDecl(); 918 assert(!RD->hasFlexibleArrayMember() && 919 "Cannot expand structure with flexible array."); 920 if (RD->isUnion()) { 921 // Unions can be here only in degenerative cases - all the fields are same 922 // after flattening. Thus we have to use the "largest" field. 923 const FieldDecl *LargestFD = nullptr; 924 CharUnits UnionSize = CharUnits::Zero(); 925 926 for (const auto *FD : RD->fields()) { 927 if (FD->isZeroLengthBitField(Context)) 928 continue; 929 assert(!FD->isBitField() && 930 "Cannot expand structure with bit-field members."); 931 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType()); 932 if (UnionSize < FieldSize) { 933 UnionSize = FieldSize; 934 LargestFD = FD; 935 } 936 } 937 if (LargestFD) 938 Fields.push_back(LargestFD); 939 } else { 940 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 941 assert(!CXXRD->isDynamicClass() && 942 "cannot expand vtable pointers in dynamic classes"); 943 for (const CXXBaseSpecifier &BS : CXXRD->bases()) 944 Bases.push_back(&BS); 945 } 946 947 for (const auto *FD : RD->fields()) { 948 if (FD->isZeroLengthBitField(Context)) 949 continue; 950 assert(!FD->isBitField() && 951 "Cannot expand structure with bit-field members."); 952 Fields.push_back(FD); 953 } 954 } 955 return std::make_unique<RecordExpansion>(std::move(Bases), 956 std::move(Fields)); 957 } 958 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 959 return std::make_unique<ComplexExpansion>(CT->getElementType()); 960 } 961 return std::make_unique<NoExpansion>(); 962 } 963 964 static int getExpansionSize(QualType Ty, const ASTContext &Context) { 965 auto Exp = getTypeExpansion(Ty, Context); 966 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 967 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context); 968 } 969 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 970 int Res = 0; 971 for (auto BS : RExp->Bases) 972 Res += getExpansionSize(BS->getType(), Context); 973 for (auto FD : RExp->Fields) 974 Res += getExpansionSize(FD->getType(), Context); 975 return Res; 976 } 977 if (isa<ComplexExpansion>(Exp.get())) 978 return 2; 979 assert(isa<NoExpansion>(Exp.get())); 980 return 1; 981 } 982 983 void 984 CodeGenTypes::getExpandedTypes(QualType Ty, 985 SmallVectorImpl<llvm::Type *>::iterator &TI) { 986 auto Exp = getTypeExpansion(Ty, Context); 987 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 988 for (int i = 0, n = CAExp->NumElts; i < n; i++) { 989 getExpandedTypes(CAExp->EltTy, TI); 990 } 991 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 992 for (auto BS : RExp->Bases) 993 getExpandedTypes(BS->getType(), TI); 994 for (auto FD : RExp->Fields) 995 getExpandedTypes(FD->getType(), TI); 996 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) { 997 llvm::Type *EltTy = ConvertType(CExp->EltTy); 998 *TI++ = EltTy; 999 *TI++ = EltTy; 1000 } else { 1001 assert(isa<NoExpansion>(Exp.get())); 1002 *TI++ = ConvertType(Ty); 1003 } 1004 } 1005 1006 static void forConstantArrayExpansion(CodeGenFunction &CGF, 1007 ConstantArrayExpansion *CAE, 1008 Address BaseAddr, 1009 llvm::function_ref<void(Address)> Fn) { 1010 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy); 1011 CharUnits EltAlign = 1012 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize); 1013 1014 for (int i = 0, n = CAE->NumElts; i < n; i++) { 1015 llvm::Value *EltAddr = 1016 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i); 1017 Fn(Address(EltAddr, EltAlign)); 1018 } 1019 } 1020 1021 void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV, 1022 llvm::Function::arg_iterator &AI) { 1023 assert(LV.isSimple() && 1024 "Unexpected non-simple lvalue during struct expansion."); 1025 1026 auto Exp = getTypeExpansion(Ty, getContext()); 1027 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 1028 forConstantArrayExpansion( 1029 *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) { 1030 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy); 1031 ExpandTypeFromArgs(CAExp->EltTy, LV, AI); 1032 }); 1033 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 1034 Address This = LV.getAddress(*this); 1035 for (const CXXBaseSpecifier *BS : RExp->Bases) { 1036 // Perform a single step derived-to-base conversion. 1037 Address Base = 1038 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 1039 /*NullCheckValue=*/false, SourceLocation()); 1040 LValue SubLV = MakeAddrLValue(Base, BS->getType()); 1041 1042 // Recurse onto bases. 1043 ExpandTypeFromArgs(BS->getType(), SubLV, AI); 1044 } 1045 for (auto FD : RExp->Fields) { 1046 // FIXME: What are the right qualifiers here? 1047 LValue SubLV = EmitLValueForFieldInitialization(LV, FD); 1048 ExpandTypeFromArgs(FD->getType(), SubLV, AI); 1049 } 1050 } else if (isa<ComplexExpansion>(Exp.get())) { 1051 auto realValue = &*AI++; 1052 auto imagValue = &*AI++; 1053 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true); 1054 } else { 1055 // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a 1056 // primitive store. 1057 assert(isa<NoExpansion>(Exp.get())); 1058 if (LV.isBitField()) 1059 EmitStoreThroughLValue(RValue::get(&*AI++), LV); 1060 else 1061 EmitStoreOfScalar(&*AI++, LV); 1062 } 1063 } 1064 1065 void CodeGenFunction::ExpandTypeToArgs( 1066 QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy, 1067 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) { 1068 auto Exp = getTypeExpansion(Ty, getContext()); 1069 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 1070 Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this) 1071 : Arg.getKnownRValue().getAggregateAddress(); 1072 forConstantArrayExpansion( 1073 *this, CAExp, Addr, [&](Address EltAddr) { 1074 CallArg EltArg = CallArg( 1075 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()), 1076 CAExp->EltTy); 1077 ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs, 1078 IRCallArgPos); 1079 }); 1080 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 1081 Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this) 1082 : Arg.getKnownRValue().getAggregateAddress(); 1083 for (const CXXBaseSpecifier *BS : RExp->Bases) { 1084 // Perform a single step derived-to-base conversion. 1085 Address Base = 1086 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 1087 /*NullCheckValue=*/false, SourceLocation()); 1088 CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType()); 1089 1090 // Recurse onto bases. 1091 ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs, 1092 IRCallArgPos); 1093 } 1094 1095 LValue LV = MakeAddrLValue(This, Ty); 1096 for (auto FD : RExp->Fields) { 1097 CallArg FldArg = 1098 CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType()); 1099 ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs, 1100 IRCallArgPos); 1101 } 1102 } else if (isa<ComplexExpansion>(Exp.get())) { 1103 ComplexPairTy CV = Arg.getKnownRValue().getComplexVal(); 1104 IRCallArgs[IRCallArgPos++] = CV.first; 1105 IRCallArgs[IRCallArgPos++] = CV.second; 1106 } else { 1107 assert(isa<NoExpansion>(Exp.get())); 1108 auto RV = Arg.getKnownRValue(); 1109 assert(RV.isScalar() && 1110 "Unexpected non-scalar rvalue during struct expansion."); 1111 1112 // Insert a bitcast as needed. 1113 llvm::Value *V = RV.getScalarVal(); 1114 if (IRCallArgPos < IRFuncTy->getNumParams() && 1115 V->getType() != IRFuncTy->getParamType(IRCallArgPos)) 1116 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos)); 1117 1118 IRCallArgs[IRCallArgPos++] = V; 1119 } 1120 } 1121 1122 /// Create a temporary allocation for the purposes of coercion. 1123 static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty, 1124 CharUnits MinAlign, 1125 const Twine &Name = "tmp") { 1126 // Don't use an alignment that's worse than what LLVM would prefer. 1127 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty); 1128 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign)); 1129 1130 return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce"); 1131 } 1132 1133 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are 1134 /// accessing some number of bytes out of it, try to gep into the struct to get 1135 /// at its inner goodness. Dive as deep as possible without entering an element 1136 /// with an in-memory size smaller than DstSize. 1137 static Address 1138 EnterStructPointerForCoercedAccess(Address SrcPtr, 1139 llvm::StructType *SrcSTy, 1140 uint64_t DstSize, CodeGenFunction &CGF) { 1141 // We can't dive into a zero-element struct. 1142 if (SrcSTy->getNumElements() == 0) return SrcPtr; 1143 1144 llvm::Type *FirstElt = SrcSTy->getElementType(0); 1145 1146 // If the first elt is at least as large as what we're looking for, or if the 1147 // first element is the same size as the whole struct, we can enter it. The 1148 // comparison must be made on the store size and not the alloca size. Using 1149 // the alloca size may overstate the size of the load. 1150 uint64_t FirstEltSize = 1151 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt); 1152 if (FirstEltSize < DstSize && 1153 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy)) 1154 return SrcPtr; 1155 1156 // GEP into the first element. 1157 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive"); 1158 1159 // If the first element is a struct, recurse. 1160 llvm::Type *SrcTy = SrcPtr.getElementType(); 1161 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) 1162 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF); 1163 1164 return SrcPtr; 1165 } 1166 1167 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both 1168 /// are either integers or pointers. This does a truncation of the value if it 1169 /// is too large or a zero extension if it is too small. 1170 /// 1171 /// This behaves as if the value were coerced through memory, so on big-endian 1172 /// targets the high bits are preserved in a truncation, while little-endian 1173 /// targets preserve the low bits. 1174 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, 1175 llvm::Type *Ty, 1176 CodeGenFunction &CGF) { 1177 if (Val->getType() == Ty) 1178 return Val; 1179 1180 if (isa<llvm::PointerType>(Val->getType())) { 1181 // If this is Pointer->Pointer avoid conversion to and from int. 1182 if (isa<llvm::PointerType>(Ty)) 1183 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val"); 1184 1185 // Convert the pointer to an integer so we can play with its width. 1186 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi"); 1187 } 1188 1189 llvm::Type *DestIntTy = Ty; 1190 if (isa<llvm::PointerType>(DestIntTy)) 1191 DestIntTy = CGF.IntPtrTy; 1192 1193 if (Val->getType() != DestIntTy) { 1194 const llvm::DataLayout &DL = CGF.CGM.getDataLayout(); 1195 if (DL.isBigEndian()) { 1196 // Preserve the high bits on big-endian targets. 1197 // That is what memory coercion does. 1198 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType()); 1199 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy); 1200 1201 if (SrcSize > DstSize) { 1202 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits"); 1203 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii"); 1204 } else { 1205 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii"); 1206 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits"); 1207 } 1208 } else { 1209 // Little-endian targets preserve the low bits. No shifts required. 1210 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii"); 1211 } 1212 } 1213 1214 if (isa<llvm::PointerType>(Ty)) 1215 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip"); 1216 return Val; 1217 } 1218 1219 1220 1221 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as 1222 /// a pointer to an object of type \arg Ty, known to be aligned to 1223 /// \arg SrcAlign bytes. 1224 /// 1225 /// This safely handles the case when the src type is smaller than the 1226 /// destination type; in this situation the values of bits which not 1227 /// present in the src are undefined. 1228 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty, 1229 CodeGenFunction &CGF) { 1230 llvm::Type *SrcTy = Src.getElementType(); 1231 1232 // If SrcTy and Ty are the same, just do a load. 1233 if (SrcTy == Ty) 1234 return CGF.Builder.CreateLoad(Src); 1235 1236 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty); 1237 1238 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) { 1239 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, 1240 DstSize.getFixedSize(), CGF); 1241 SrcTy = Src.getElementType(); 1242 } 1243 1244 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1245 1246 // If the source and destination are integer or pointer types, just do an 1247 // extension or truncation to the desired type. 1248 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) && 1249 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) { 1250 llvm::Value *Load = CGF.Builder.CreateLoad(Src); 1251 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF); 1252 } 1253 1254 // If load is legal, just bitcast the src pointer. 1255 if (!SrcSize.isScalable() && !DstSize.isScalable() && 1256 SrcSize.getFixedSize() >= DstSize.getFixedSize()) { 1257 // Generally SrcSize is never greater than DstSize, since this means we are 1258 // losing bits. However, this can happen in cases where the structure has 1259 // additional padding, for example due to a user specified alignment. 1260 // 1261 // FIXME: Assert that we aren't truncating non-padding bits when have access 1262 // to that information. 1263 Src = CGF.Builder.CreateBitCast(Src, 1264 Ty->getPointerTo(Src.getAddressSpace())); 1265 return CGF.Builder.CreateLoad(Src); 1266 } 1267 1268 // Otherwise do coercion through memory. This is stupid, but simple. 1269 Address Tmp = 1270 CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName()); 1271 CGF.Builder.CreateMemCpy( 1272 Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(), 1273 Src.getAlignment().getAsAlign(), 1274 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinSize())); 1275 return CGF.Builder.CreateLoad(Tmp); 1276 } 1277 1278 // Function to store a first-class aggregate into memory. We prefer to 1279 // store the elements rather than the aggregate to be more friendly to 1280 // fast-isel. 1281 // FIXME: Do we need to recurse here? 1282 void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest, 1283 bool DestIsVolatile) { 1284 // Prefer scalar stores to first-class aggregate stores. 1285 if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) { 1286 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1287 Address EltPtr = Builder.CreateStructGEP(Dest, i); 1288 llvm::Value *Elt = Builder.CreateExtractValue(Val, i); 1289 Builder.CreateStore(Elt, EltPtr, DestIsVolatile); 1290 } 1291 } else { 1292 Builder.CreateStore(Val, Dest, DestIsVolatile); 1293 } 1294 } 1295 1296 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 1297 /// where the source and destination may have different types. The 1298 /// destination is known to be aligned to \arg DstAlign bytes. 1299 /// 1300 /// This safely handles the case when the src type is larger than the 1301 /// destination type; the upper bits of the src will be lost. 1302 static void CreateCoercedStore(llvm::Value *Src, 1303 Address Dst, 1304 bool DstIsVolatile, 1305 CodeGenFunction &CGF) { 1306 llvm::Type *SrcTy = Src->getType(); 1307 llvm::Type *DstTy = Dst.getElementType(); 1308 if (SrcTy == DstTy) { 1309 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1310 return; 1311 } 1312 1313 llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1314 1315 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) { 1316 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, 1317 SrcSize.getFixedSize(), CGF); 1318 DstTy = Dst.getElementType(); 1319 } 1320 1321 llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy); 1322 llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy); 1323 if (SrcPtrTy && DstPtrTy && 1324 SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) { 1325 Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy); 1326 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1327 return; 1328 } 1329 1330 // If the source and destination are integer or pointer types, just do an 1331 // extension or truncation to the desired type. 1332 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) && 1333 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) { 1334 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF); 1335 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1336 return; 1337 } 1338 1339 llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy); 1340 1341 // If store is legal, just bitcast the src pointer. 1342 if (isa<llvm::ScalableVectorType>(SrcTy) || 1343 isa<llvm::ScalableVectorType>(DstTy) || 1344 SrcSize.getFixedSize() <= DstSize.getFixedSize()) { 1345 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy); 1346 CGF.EmitAggregateStore(Src, Dst, DstIsVolatile); 1347 } else { 1348 // Otherwise do coercion through memory. This is stupid, but 1349 // simple. 1350 1351 // Generally SrcSize is never greater than DstSize, since this means we are 1352 // losing bits. However, this can happen in cases where the structure has 1353 // additional padding, for example due to a user specified alignment. 1354 // 1355 // FIXME: Assert that we aren't truncating non-padding bits when have access 1356 // to that information. 1357 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment()); 1358 CGF.Builder.CreateStore(Src, Tmp); 1359 CGF.Builder.CreateMemCpy( 1360 Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(), 1361 Tmp.getAlignment().getAsAlign(), 1362 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedSize())); 1363 } 1364 } 1365 1366 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, 1367 const ABIArgInfo &info) { 1368 if (unsigned offset = info.getDirectOffset()) { 1369 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty); 1370 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr, 1371 CharUnits::fromQuantity(offset)); 1372 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType()); 1373 } 1374 return addr; 1375 } 1376 1377 namespace { 1378 1379 /// Encapsulates information about the way function arguments from 1380 /// CGFunctionInfo should be passed to actual LLVM IR function. 1381 class ClangToLLVMArgMapping { 1382 static const unsigned InvalidIndex = ~0U; 1383 unsigned InallocaArgNo; 1384 unsigned SRetArgNo; 1385 unsigned TotalIRArgs; 1386 1387 /// Arguments of LLVM IR function corresponding to single Clang argument. 1388 struct IRArgs { 1389 unsigned PaddingArgIndex; 1390 // Argument is expanded to IR arguments at positions 1391 // [FirstArgIndex, FirstArgIndex + NumberOfArgs). 1392 unsigned FirstArgIndex; 1393 unsigned NumberOfArgs; 1394 1395 IRArgs() 1396 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex), 1397 NumberOfArgs(0) {} 1398 }; 1399 1400 SmallVector<IRArgs, 8> ArgInfo; 1401 1402 public: 1403 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI, 1404 bool OnlyRequiredArgs = false) 1405 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0), 1406 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) { 1407 construct(Context, FI, OnlyRequiredArgs); 1408 } 1409 1410 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; } 1411 unsigned getInallocaArgNo() const { 1412 assert(hasInallocaArg()); 1413 return InallocaArgNo; 1414 } 1415 1416 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; } 1417 unsigned getSRetArgNo() const { 1418 assert(hasSRetArg()); 1419 return SRetArgNo; 1420 } 1421 1422 unsigned totalIRArgs() const { return TotalIRArgs; } 1423 1424 bool hasPaddingArg(unsigned ArgNo) const { 1425 assert(ArgNo < ArgInfo.size()); 1426 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex; 1427 } 1428 unsigned getPaddingArgNo(unsigned ArgNo) const { 1429 assert(hasPaddingArg(ArgNo)); 1430 return ArgInfo[ArgNo].PaddingArgIndex; 1431 } 1432 1433 /// Returns index of first IR argument corresponding to ArgNo, and their 1434 /// quantity. 1435 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const { 1436 assert(ArgNo < ArgInfo.size()); 1437 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex, 1438 ArgInfo[ArgNo].NumberOfArgs); 1439 } 1440 1441 private: 1442 void construct(const ASTContext &Context, const CGFunctionInfo &FI, 1443 bool OnlyRequiredArgs); 1444 }; 1445 1446 void ClangToLLVMArgMapping::construct(const ASTContext &Context, 1447 const CGFunctionInfo &FI, 1448 bool OnlyRequiredArgs) { 1449 unsigned IRArgNo = 0; 1450 bool SwapThisWithSRet = false; 1451 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1452 1453 if (RetAI.getKind() == ABIArgInfo::Indirect) { 1454 SwapThisWithSRet = RetAI.isSRetAfterThis(); 1455 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++; 1456 } 1457 1458 unsigned ArgNo = 0; 1459 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size(); 1460 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs; 1461 ++I, ++ArgNo) { 1462 assert(I != FI.arg_end()); 1463 QualType ArgType = I->type; 1464 const ABIArgInfo &AI = I->info; 1465 // Collect data about IR arguments corresponding to Clang argument ArgNo. 1466 auto &IRArgs = ArgInfo[ArgNo]; 1467 1468 if (AI.getPaddingType()) 1469 IRArgs.PaddingArgIndex = IRArgNo++; 1470 1471 switch (AI.getKind()) { 1472 case ABIArgInfo::Extend: 1473 case ABIArgInfo::Direct: { 1474 // FIXME: handle sseregparm someday... 1475 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType()); 1476 if (AI.isDirect() && AI.getCanBeFlattened() && STy) { 1477 IRArgs.NumberOfArgs = STy->getNumElements(); 1478 } else { 1479 IRArgs.NumberOfArgs = 1; 1480 } 1481 break; 1482 } 1483 case ABIArgInfo::Indirect: 1484 case ABIArgInfo::IndirectAliased: 1485 IRArgs.NumberOfArgs = 1; 1486 break; 1487 case ABIArgInfo::Ignore: 1488 case ABIArgInfo::InAlloca: 1489 // ignore and inalloca doesn't have matching LLVM parameters. 1490 IRArgs.NumberOfArgs = 0; 1491 break; 1492 case ABIArgInfo::CoerceAndExpand: 1493 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size(); 1494 break; 1495 case ABIArgInfo::Expand: 1496 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context); 1497 break; 1498 } 1499 1500 if (IRArgs.NumberOfArgs > 0) { 1501 IRArgs.FirstArgIndex = IRArgNo; 1502 IRArgNo += IRArgs.NumberOfArgs; 1503 } 1504 1505 // Skip over the sret parameter when it comes second. We already handled it 1506 // above. 1507 if (IRArgNo == 1 && SwapThisWithSRet) 1508 IRArgNo++; 1509 } 1510 assert(ArgNo == ArgInfo.size()); 1511 1512 if (FI.usesInAlloca()) 1513 InallocaArgNo = IRArgNo++; 1514 1515 TotalIRArgs = IRArgNo; 1516 } 1517 } // namespace 1518 1519 /***/ 1520 1521 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) { 1522 const auto &RI = FI.getReturnInfo(); 1523 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet()); 1524 } 1525 1526 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) { 1527 return ReturnTypeUsesSRet(FI) && 1528 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs(); 1529 } 1530 1531 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) { 1532 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) { 1533 switch (BT->getKind()) { 1534 default: 1535 return false; 1536 case BuiltinType::Float: 1537 return getTarget().useObjCFPRetForRealType(TargetInfo::Float); 1538 case BuiltinType::Double: 1539 return getTarget().useObjCFPRetForRealType(TargetInfo::Double); 1540 case BuiltinType::LongDouble: 1541 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble); 1542 } 1543 } 1544 1545 return false; 1546 } 1547 1548 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) { 1549 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) { 1550 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) { 1551 if (BT->getKind() == BuiltinType::LongDouble) 1552 return getTarget().useObjCFP2RetForComplexLongDouble(); 1553 } 1554 } 1555 1556 return false; 1557 } 1558 1559 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) { 1560 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD); 1561 return GetFunctionType(FI); 1562 } 1563 1564 llvm::FunctionType * 1565 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) { 1566 1567 bool Inserted = FunctionsBeingProcessed.insert(&FI).second; 1568 (void)Inserted; 1569 assert(Inserted && "Recursively being processed?"); 1570 1571 llvm::Type *resultType = nullptr; 1572 const ABIArgInfo &retAI = FI.getReturnInfo(); 1573 switch (retAI.getKind()) { 1574 case ABIArgInfo::Expand: 1575 case ABIArgInfo::IndirectAliased: 1576 llvm_unreachable("Invalid ABI kind for return argument"); 1577 1578 case ABIArgInfo::Extend: 1579 case ABIArgInfo::Direct: 1580 resultType = retAI.getCoerceToType(); 1581 break; 1582 1583 case ABIArgInfo::InAlloca: 1584 if (retAI.getInAllocaSRet()) { 1585 // sret things on win32 aren't void, they return the sret pointer. 1586 QualType ret = FI.getReturnType(); 1587 llvm::Type *ty = ConvertType(ret); 1588 unsigned addressSpace = Context.getTargetAddressSpace(ret); 1589 resultType = llvm::PointerType::get(ty, addressSpace); 1590 } else { 1591 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1592 } 1593 break; 1594 1595 case ABIArgInfo::Indirect: 1596 case ABIArgInfo::Ignore: 1597 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1598 break; 1599 1600 case ABIArgInfo::CoerceAndExpand: 1601 resultType = retAI.getUnpaddedCoerceAndExpandType(); 1602 break; 1603 } 1604 1605 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true); 1606 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs()); 1607 1608 // Add type for sret argument. 1609 if (IRFunctionArgs.hasSRetArg()) { 1610 QualType Ret = FI.getReturnType(); 1611 llvm::Type *Ty = ConvertType(Ret); 1612 unsigned AddressSpace = Context.getTargetAddressSpace(Ret); 1613 ArgTypes[IRFunctionArgs.getSRetArgNo()] = 1614 llvm::PointerType::get(Ty, AddressSpace); 1615 } 1616 1617 // Add type for inalloca argument. 1618 if (IRFunctionArgs.hasInallocaArg()) { 1619 auto ArgStruct = FI.getArgStruct(); 1620 assert(ArgStruct); 1621 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo(); 1622 } 1623 1624 // Add in all of the required arguments. 1625 unsigned ArgNo = 0; 1626 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 1627 ie = it + FI.getNumRequiredArgs(); 1628 for (; it != ie; ++it, ++ArgNo) { 1629 const ABIArgInfo &ArgInfo = it->info; 1630 1631 // Insert a padding type to ensure proper alignment. 1632 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 1633 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 1634 ArgInfo.getPaddingType(); 1635 1636 unsigned FirstIRArg, NumIRArgs; 1637 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1638 1639 switch (ArgInfo.getKind()) { 1640 case ABIArgInfo::Ignore: 1641 case ABIArgInfo::InAlloca: 1642 assert(NumIRArgs == 0); 1643 break; 1644 1645 case ABIArgInfo::Indirect: { 1646 assert(NumIRArgs == 1); 1647 // indirect arguments are always on the stack, which is alloca addr space. 1648 llvm::Type *LTy = ConvertTypeForMem(it->type); 1649 ArgTypes[FirstIRArg] = LTy->getPointerTo( 1650 CGM.getDataLayout().getAllocaAddrSpace()); 1651 break; 1652 } 1653 case ABIArgInfo::IndirectAliased: { 1654 assert(NumIRArgs == 1); 1655 llvm::Type *LTy = ConvertTypeForMem(it->type); 1656 ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace()); 1657 break; 1658 } 1659 case ABIArgInfo::Extend: 1660 case ABIArgInfo::Direct: { 1661 // Fast-isel and the optimizer generally like scalar values better than 1662 // FCAs, so we flatten them if this is safe to do for this argument. 1663 llvm::Type *argType = ArgInfo.getCoerceToType(); 1664 llvm::StructType *st = dyn_cast<llvm::StructType>(argType); 1665 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 1666 assert(NumIRArgs == st->getNumElements()); 1667 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i) 1668 ArgTypes[FirstIRArg + i] = st->getElementType(i); 1669 } else { 1670 assert(NumIRArgs == 1); 1671 ArgTypes[FirstIRArg] = argType; 1672 } 1673 break; 1674 } 1675 1676 case ABIArgInfo::CoerceAndExpand: { 1677 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1678 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) { 1679 *ArgTypesIter++ = EltTy; 1680 } 1681 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1682 break; 1683 } 1684 1685 case ABIArgInfo::Expand: 1686 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1687 getExpandedTypes(it->type, ArgTypesIter); 1688 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1689 break; 1690 } 1691 } 1692 1693 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased; 1694 assert(Erased && "Not in set?"); 1695 1696 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic()); 1697 } 1698 1699 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { 1700 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1701 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1702 1703 if (!isFuncTypeConvertible(FPT)) 1704 return llvm::StructType::get(getLLVMContext()); 1705 1706 return GetFunctionType(GD); 1707 } 1708 1709 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, 1710 llvm::AttrBuilder &FuncAttrs, 1711 const FunctionProtoType *FPT) { 1712 if (!FPT) 1713 return; 1714 1715 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 1716 FPT->isNothrow()) 1717 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1718 } 1719 1720 void CodeGenModule::getDefaultFunctionAttributes(StringRef Name, 1721 bool HasOptnone, 1722 bool AttrOnCallSite, 1723 llvm::AttrBuilder &FuncAttrs) { 1724 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed. 1725 if (!HasOptnone) { 1726 if (CodeGenOpts.OptimizeSize) 1727 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize); 1728 if (CodeGenOpts.OptimizeSize == 2) 1729 FuncAttrs.addAttribute(llvm::Attribute::MinSize); 1730 } 1731 1732 if (CodeGenOpts.DisableRedZone) 1733 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone); 1734 if (CodeGenOpts.IndirectTlsSegRefs) 1735 FuncAttrs.addAttribute("indirect-tls-seg-refs"); 1736 if (CodeGenOpts.NoImplicitFloat) 1737 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat); 1738 1739 if (AttrOnCallSite) { 1740 // Attributes that should go on the call site only. 1741 if (!CodeGenOpts.SimplifyLibCalls || 1742 CodeGenOpts.isNoBuiltinFunc(Name.data())) 1743 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin); 1744 if (!CodeGenOpts.TrapFuncName.empty()) 1745 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName); 1746 } else { 1747 StringRef FpKind; 1748 switch (CodeGenOpts.getFramePointer()) { 1749 case CodeGenOptions::FramePointerKind::None: 1750 FpKind = "none"; 1751 break; 1752 case CodeGenOptions::FramePointerKind::NonLeaf: 1753 FpKind = "non-leaf"; 1754 break; 1755 case CodeGenOptions::FramePointerKind::All: 1756 FpKind = "all"; 1757 break; 1758 } 1759 FuncAttrs.addAttribute("frame-pointer", FpKind); 1760 1761 FuncAttrs.addAttribute("less-precise-fpmad", 1762 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD)); 1763 1764 if (CodeGenOpts.NullPointerIsValid) 1765 FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid); 1766 1767 if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE()) 1768 FuncAttrs.addAttribute("denormal-fp-math", 1769 CodeGenOpts.FPDenormalMode.str()); 1770 if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) { 1771 FuncAttrs.addAttribute( 1772 "denormal-fp-math-f32", 1773 CodeGenOpts.FP32DenormalMode.str()); 1774 } 1775 1776 FuncAttrs.addAttribute("no-trapping-math", 1777 llvm::toStringRef(LangOpts.getFPExceptionMode() == 1778 LangOptions::FPE_Ignore)); 1779 1780 // Strict (compliant) code is the default, so only add this attribute to 1781 // indicate that we are trying to workaround a problem case. 1782 if (!CodeGenOpts.StrictFloatCastOverflow) 1783 FuncAttrs.addAttribute("strict-float-cast-overflow", "false"); 1784 1785 // TODO: Are these all needed? 1786 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags. 1787 FuncAttrs.addAttribute("no-infs-fp-math", 1788 llvm::toStringRef(LangOpts.NoHonorInfs)); 1789 FuncAttrs.addAttribute("no-nans-fp-math", 1790 llvm::toStringRef(LangOpts.NoHonorNaNs)); 1791 FuncAttrs.addAttribute("unsafe-fp-math", 1792 llvm::toStringRef(LangOpts.UnsafeFPMath)); 1793 FuncAttrs.addAttribute("use-soft-float", 1794 llvm::toStringRef(CodeGenOpts.SoftFloat)); 1795 FuncAttrs.addAttribute("stack-protector-buffer-size", 1796 llvm::utostr(CodeGenOpts.SSPBufferSize)); 1797 FuncAttrs.addAttribute("no-signed-zeros-fp-math", 1798 llvm::toStringRef(LangOpts.NoSignedZero)); 1799 1800 // TODO: Reciprocal estimate codegen options should apply to instructions? 1801 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals; 1802 if (!Recips.empty()) 1803 FuncAttrs.addAttribute("reciprocal-estimates", 1804 llvm::join(Recips, ",")); 1805 1806 if (!CodeGenOpts.PreferVectorWidth.empty() && 1807 CodeGenOpts.PreferVectorWidth != "none") 1808 FuncAttrs.addAttribute("prefer-vector-width", 1809 CodeGenOpts.PreferVectorWidth); 1810 1811 if (CodeGenOpts.StackRealignment) 1812 FuncAttrs.addAttribute("stackrealign"); 1813 if (CodeGenOpts.Backchain) 1814 FuncAttrs.addAttribute("backchain"); 1815 if (CodeGenOpts.EnableSegmentedStacks) 1816 FuncAttrs.addAttribute("split-stack"); 1817 1818 if (CodeGenOpts.SpeculativeLoadHardening) 1819 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening); 1820 } 1821 1822 if (getLangOpts().assumeFunctionsAreConvergent()) { 1823 // Conservatively, mark all functions and calls in CUDA and OpenCL as 1824 // convergent (meaning, they may call an intrinsically convergent op, such 1825 // as __syncthreads() / barrier(), and so can't have certain optimizations 1826 // applied around them). LLVM will remove this attribute where it safely 1827 // can. 1828 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1829 } 1830 1831 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 1832 // Exceptions aren't supported in CUDA device code. 1833 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1834 } 1835 1836 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) { 1837 StringRef Var, Value; 1838 std::tie(Var, Value) = Attr.split('='); 1839 FuncAttrs.addAttribute(Var, Value); 1840 } 1841 } 1842 1843 void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) { 1844 llvm::AttrBuilder FuncAttrs; 1845 getDefaultFunctionAttributes(F.getName(), F.hasOptNone(), 1846 /* AttrOnCallSite = */ false, FuncAttrs); 1847 // TODO: call GetCPUAndFeaturesAttributes? 1848 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs); 1849 } 1850 1851 void CodeGenModule::addDefaultFunctionDefinitionAttributes( 1852 llvm::AttrBuilder &attrs) { 1853 getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false, 1854 /*for call*/ false, attrs); 1855 GetCPUAndFeaturesAttributes(GlobalDecl(), attrs); 1856 } 1857 1858 static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs, 1859 const LangOptions &LangOpts, 1860 const NoBuiltinAttr *NBA = nullptr) { 1861 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) { 1862 SmallString<32> AttributeName; 1863 AttributeName += "no-builtin-"; 1864 AttributeName += BuiltinName; 1865 FuncAttrs.addAttribute(AttributeName); 1866 }; 1867 1868 // First, handle the language options passed through -fno-builtin. 1869 if (LangOpts.NoBuiltin) { 1870 // -fno-builtin disables them all. 1871 FuncAttrs.addAttribute("no-builtins"); 1872 return; 1873 } 1874 1875 // Then, add attributes for builtins specified through -fno-builtin-<name>. 1876 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr); 1877 1878 // Now, let's check the __attribute__((no_builtin("...")) attribute added to 1879 // the source. 1880 if (!NBA) 1881 return; 1882 1883 // If there is a wildcard in the builtin names specified through the 1884 // attribute, disable them all. 1885 if (llvm::is_contained(NBA->builtinNames(), "*")) { 1886 FuncAttrs.addAttribute("no-builtins"); 1887 return; 1888 } 1889 1890 // And last, add the rest of the builtin names. 1891 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr); 1892 } 1893 1894 /// Construct the IR attribute list of a function or call. 1895 /// 1896 /// When adding an attribute, please consider where it should be handled: 1897 /// 1898 /// - getDefaultFunctionAttributes is for attributes that are essentially 1899 /// part of the global target configuration (but perhaps can be 1900 /// overridden on a per-function basis). Adding attributes there 1901 /// will cause them to also be set in frontends that build on Clang's 1902 /// target-configuration logic, as well as for code defined in library 1903 /// modules such as CUDA's libdevice. 1904 /// 1905 /// - ConstructAttributeList builds on top of getDefaultFunctionAttributes 1906 /// and adds declaration-specific, convention-specific, and 1907 /// frontend-specific logic. The last is of particular importance: 1908 /// attributes that restrict how the frontend generates code must be 1909 /// added here rather than getDefaultFunctionAttributes. 1910 /// 1911 void CodeGenModule::ConstructAttributeList( 1912 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo, 1913 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) { 1914 llvm::AttrBuilder FuncAttrs; 1915 llvm::AttrBuilder RetAttrs; 1916 1917 // Collect function IR attributes from the CC lowering. 1918 // We'll collect the paramete and result attributes later. 1919 CallingConv = FI.getEffectiveCallingConvention(); 1920 if (FI.isNoReturn()) 1921 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1922 if (FI.isCmseNSCall()) 1923 FuncAttrs.addAttribute("cmse_nonsecure_call"); 1924 1925 // Collect function IR attributes from the callee prototype if we have one. 1926 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs, 1927 CalleeInfo.getCalleeFunctionProtoType()); 1928 1929 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl(); 1930 1931 bool HasOptnone = false; 1932 // The NoBuiltinAttr attached to the target FunctionDecl. 1933 const NoBuiltinAttr *NBA = nullptr; 1934 1935 // Collect function IR attributes based on declaration-specific 1936 // information. 1937 // FIXME: handle sseregparm someday... 1938 if (TargetDecl) { 1939 if (TargetDecl->hasAttr<ReturnsTwiceAttr>()) 1940 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice); 1941 if (TargetDecl->hasAttr<NoThrowAttr>()) 1942 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1943 if (TargetDecl->hasAttr<NoReturnAttr>()) 1944 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1945 if (TargetDecl->hasAttr<ColdAttr>()) 1946 FuncAttrs.addAttribute(llvm::Attribute::Cold); 1947 if (TargetDecl->hasAttr<NoDuplicateAttr>()) 1948 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate); 1949 if (TargetDecl->hasAttr<ConvergentAttr>()) 1950 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1951 1952 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 1953 AddAttributesFromFunctionProtoType( 1954 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>()); 1955 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) { 1956 // A sane operator new returns a non-aliasing pointer. 1957 auto Kind = Fn->getDeclName().getCXXOverloadedOperator(); 1958 if (getCodeGenOpts().AssumeSaneOperatorNew && 1959 (Kind == OO_New || Kind == OO_Array_New)) 1960 RetAttrs.addAttribute(llvm::Attribute::NoAlias); 1961 } 1962 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn); 1963 const bool IsVirtualCall = MD && MD->isVirtual(); 1964 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a 1965 // virtual function. These attributes are not inherited by overloads. 1966 if (!(AttrOnCallSite && IsVirtualCall)) { 1967 if (Fn->isNoReturn()) 1968 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1969 NBA = Fn->getAttr<NoBuiltinAttr>(); 1970 } 1971 if (!AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>()) 1972 FuncAttrs.addAttribute(llvm::Attribute::NoMerge); 1973 } 1974 1975 // 'const', 'pure' and 'noalias' attributed functions are also nounwind. 1976 if (TargetDecl->hasAttr<ConstAttr>()) { 1977 FuncAttrs.addAttribute(llvm::Attribute::ReadNone); 1978 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1979 } else if (TargetDecl->hasAttr<PureAttr>()) { 1980 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly); 1981 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1982 } else if (TargetDecl->hasAttr<NoAliasAttr>()) { 1983 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly); 1984 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1985 } 1986 if (TargetDecl->hasAttr<RestrictAttr>()) 1987 RetAttrs.addAttribute(llvm::Attribute::NoAlias); 1988 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() && 1989 !CodeGenOpts.NullPointerIsValid) 1990 RetAttrs.addAttribute(llvm::Attribute::NonNull); 1991 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) 1992 FuncAttrs.addAttribute("no_caller_saved_registers"); 1993 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>()) 1994 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck); 1995 if (TargetDecl->hasAttr<LeafAttr>()) 1996 FuncAttrs.addAttribute(llvm::Attribute::NoCallback); 1997 1998 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>(); 1999 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) { 2000 Optional<unsigned> NumElemsParam; 2001 if (AllocSize->getNumElemsParam().isValid()) 2002 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex(); 2003 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(), 2004 NumElemsParam); 2005 } 2006 2007 if (TargetDecl->hasAttr<OpenCLKernelAttr>()) { 2008 if (getLangOpts().OpenCLVersion <= 120) { 2009 // OpenCL v1.2 Work groups are always uniform 2010 FuncAttrs.addAttribute("uniform-work-group-size", "true"); 2011 } else { 2012 // OpenCL v2.0 Work groups may be whether uniform or not. 2013 // '-cl-uniform-work-group-size' compile option gets a hint 2014 // to the compiler that the global work-size be a multiple of 2015 // the work-group size specified to clEnqueueNDRangeKernel 2016 // (i.e. work groups are uniform). 2017 FuncAttrs.addAttribute("uniform-work-group-size", 2018 llvm::toStringRef(CodeGenOpts.UniformWGSize)); 2019 } 2020 } 2021 2022 std::string AssumptionValueStr; 2023 for (AssumptionAttr *AssumptionA : 2024 TargetDecl->specific_attrs<AssumptionAttr>()) { 2025 std::string AS = AssumptionA->getAssumption().str(); 2026 if (!AS.empty() && !AssumptionValueStr.empty()) 2027 AssumptionValueStr += ","; 2028 AssumptionValueStr += AS; 2029 } 2030 2031 if (!AssumptionValueStr.empty()) 2032 FuncAttrs.addAttribute(llvm::AssumptionAttrKey, AssumptionValueStr); 2033 } 2034 2035 // Attach "no-builtins" attributes to: 2036 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>". 2037 // * definitions: "no-builtins" or "no-builtin-<name>" only. 2038 // The attributes can come from: 2039 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name> 2040 // * FunctionDecl attributes: __attribute__((no_builtin(...))) 2041 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA); 2042 2043 // Collect function IR attributes based on global settiings. 2044 getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs); 2045 2046 // Override some default IR attributes based on declaration-specific 2047 // information. 2048 if (TargetDecl) { 2049 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>()) 2050 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening); 2051 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>()) 2052 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening); 2053 if (TargetDecl->hasAttr<NoSplitStackAttr>()) 2054 FuncAttrs.removeAttribute("split-stack"); 2055 2056 // Add NonLazyBind attribute to function declarations when -fno-plt 2057 // is used. 2058 // FIXME: what if we just haven't processed the function definition 2059 // yet, or if it's an external definition like C99 inline? 2060 if (CodeGenOpts.NoPLT) { 2061 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 2062 if (!Fn->isDefined() && !AttrOnCallSite) { 2063 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind); 2064 } 2065 } 2066 } 2067 } 2068 2069 // Collect non-call-site function IR attributes from declaration-specific 2070 // information. 2071 if (!AttrOnCallSite) { 2072 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>()) 2073 FuncAttrs.addAttribute("cmse_nonsecure_entry"); 2074 2075 // Whether tail calls are enabled. 2076 auto shouldDisableTailCalls = [&] { 2077 // Should this be honored in getDefaultFunctionAttributes? 2078 if (CodeGenOpts.DisableTailCalls) 2079 return true; 2080 2081 if (!TargetDecl) 2082 return false; 2083 2084 if (TargetDecl->hasAttr<DisableTailCallsAttr>() || 2085 TargetDecl->hasAttr<AnyX86InterruptAttr>()) 2086 return true; 2087 2088 if (CodeGenOpts.NoEscapingBlockTailCalls) { 2089 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl)) 2090 if (!BD->doesNotEscape()) 2091 return true; 2092 } 2093 2094 return false; 2095 }; 2096 FuncAttrs.addAttribute("disable-tail-calls", 2097 llvm::toStringRef(shouldDisableTailCalls())); 2098 2099 // CPU/feature overrides. addDefaultFunctionDefinitionAttributes 2100 // handles these separately to set them based on the global defaults. 2101 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs); 2102 } 2103 2104 // Collect attributes from arguments and return values. 2105 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI); 2106 2107 QualType RetTy = FI.getReturnType(); 2108 const ABIArgInfo &RetAI = FI.getReturnInfo(); 2109 switch (RetAI.getKind()) { 2110 case ABIArgInfo::Extend: 2111 if (RetAI.isSignExt()) 2112 RetAttrs.addAttribute(llvm::Attribute::SExt); 2113 else 2114 RetAttrs.addAttribute(llvm::Attribute::ZExt); 2115 LLVM_FALLTHROUGH; 2116 case ABIArgInfo::Direct: 2117 if (RetAI.getInReg()) 2118 RetAttrs.addAttribute(llvm::Attribute::InReg); 2119 break; 2120 case ABIArgInfo::Ignore: 2121 break; 2122 2123 case ABIArgInfo::InAlloca: 2124 case ABIArgInfo::Indirect: { 2125 // inalloca and sret disable readnone and readonly 2126 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2127 .removeAttribute(llvm::Attribute::ReadNone); 2128 break; 2129 } 2130 2131 case ABIArgInfo::CoerceAndExpand: 2132 break; 2133 2134 case ABIArgInfo::Expand: 2135 case ABIArgInfo::IndirectAliased: 2136 llvm_unreachable("Invalid ABI kind for return argument"); 2137 } 2138 2139 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) { 2140 QualType PTy = RefTy->getPointeeType(); 2141 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 2142 RetAttrs.addDereferenceableAttr( 2143 getMinimumObjectSize(PTy).getQuantity()); 2144 if (getContext().getTargetAddressSpace(PTy) == 0 && 2145 !CodeGenOpts.NullPointerIsValid) 2146 RetAttrs.addAttribute(llvm::Attribute::NonNull); 2147 if (PTy->isObjectType()) { 2148 llvm::Align Alignment = 2149 getNaturalPointeeTypeAlignment(RetTy).getAsAlign(); 2150 RetAttrs.addAlignmentAttr(Alignment); 2151 } 2152 } 2153 2154 bool hasUsedSRet = false; 2155 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs()); 2156 2157 // Attach attributes to sret. 2158 if (IRFunctionArgs.hasSRetArg()) { 2159 llvm::AttrBuilder SRETAttrs; 2160 SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy)); 2161 hasUsedSRet = true; 2162 if (RetAI.getInReg()) 2163 SRETAttrs.addAttribute(llvm::Attribute::InReg); 2164 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity()); 2165 ArgAttrs[IRFunctionArgs.getSRetArgNo()] = 2166 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs); 2167 } 2168 2169 // Attach attributes to inalloca argument. 2170 if (IRFunctionArgs.hasInallocaArg()) { 2171 llvm::AttrBuilder Attrs; 2172 Attrs.addAttribute(llvm::Attribute::InAlloca); 2173 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] = 2174 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2175 } 2176 2177 // Apply `nonnull` and `dereferencable(N)` to the `this` argument. 2178 if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() && 2179 !FI.arg_begin()->type->isVoidPointerType()) { 2180 auto IRArgs = IRFunctionArgs.getIRArgs(0); 2181 2182 assert(IRArgs.second == 1 && "Expected only a single `this` pointer."); 2183 2184 llvm::AttrBuilder Attrs; 2185 2186 if (!CodeGenOpts.NullPointerIsValid && 2187 getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) { 2188 Attrs.addAttribute(llvm::Attribute::NonNull); 2189 Attrs.addDereferenceableAttr( 2190 getMinimumObjectSize( 2191 FI.arg_begin()->type.castAs<PointerType>()->getPointeeType()) 2192 .getQuantity()); 2193 } else { 2194 // FIXME dereferenceable should be correct here, regardless of 2195 // NullPointerIsValid. However, dereferenceable currently does not always 2196 // respect NullPointerIsValid and may imply nonnull and break the program. 2197 // See https://reviews.llvm.org/D66618 for discussions. 2198 Attrs.addDereferenceableOrNullAttr( 2199 getMinimumObjectSize( 2200 FI.arg_begin()->type.castAs<PointerType>()->getPointeeType()) 2201 .getQuantity()); 2202 } 2203 2204 ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs); 2205 } 2206 2207 unsigned ArgNo = 0; 2208 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(), 2209 E = FI.arg_end(); 2210 I != E; ++I, ++ArgNo) { 2211 QualType ParamType = I->type; 2212 const ABIArgInfo &AI = I->info; 2213 llvm::AttrBuilder Attrs; 2214 2215 // Add attribute for padding argument, if necessary. 2216 if (IRFunctionArgs.hasPaddingArg(ArgNo)) { 2217 if (AI.getPaddingInReg()) { 2218 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 2219 llvm::AttributeSet::get( 2220 getLLVMContext(), 2221 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg)); 2222 } 2223 } 2224 2225 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 2226 // have the corresponding parameter variable. It doesn't make 2227 // sense to do it here because parameters are so messed up. 2228 switch (AI.getKind()) { 2229 case ABIArgInfo::Extend: 2230 if (AI.isSignExt()) 2231 Attrs.addAttribute(llvm::Attribute::SExt); 2232 else 2233 Attrs.addAttribute(llvm::Attribute::ZExt); 2234 LLVM_FALLTHROUGH; 2235 case ABIArgInfo::Direct: 2236 if (ArgNo == 0 && FI.isChainCall()) 2237 Attrs.addAttribute(llvm::Attribute::Nest); 2238 else if (AI.getInReg()) 2239 Attrs.addAttribute(llvm::Attribute::InReg); 2240 break; 2241 2242 case ABIArgInfo::Indirect: { 2243 if (AI.getInReg()) 2244 Attrs.addAttribute(llvm::Attribute::InReg); 2245 2246 if (AI.getIndirectByVal()) 2247 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType)); 2248 2249 auto *Decl = ParamType->getAsRecordDecl(); 2250 if (CodeGenOpts.PassByValueIsNoAlias && Decl && 2251 Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs) 2252 // When calling the function, the pointer passed in will be the only 2253 // reference to the underlying object. Mark it accordingly. 2254 Attrs.addAttribute(llvm::Attribute::NoAlias); 2255 2256 // TODO: We could add the byref attribute if not byval, but it would 2257 // require updating many testcases. 2258 2259 CharUnits Align = AI.getIndirectAlign(); 2260 2261 // In a byval argument, it is important that the required 2262 // alignment of the type is honored, as LLVM might be creating a 2263 // *new* stack object, and needs to know what alignment to give 2264 // it. (Sometimes it can deduce a sensible alignment on its own, 2265 // but not if clang decides it must emit a packed struct, or the 2266 // user specifies increased alignment requirements.) 2267 // 2268 // This is different from indirect *not* byval, where the object 2269 // exists already, and the align attribute is purely 2270 // informative. 2271 assert(!Align.isZero()); 2272 2273 // For now, only add this when we have a byval argument. 2274 // TODO: be less lazy about updating test cases. 2275 if (AI.getIndirectByVal()) 2276 Attrs.addAlignmentAttr(Align.getQuantity()); 2277 2278 // byval disables readnone and readonly. 2279 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2280 .removeAttribute(llvm::Attribute::ReadNone); 2281 2282 break; 2283 } 2284 case ABIArgInfo::IndirectAliased: { 2285 CharUnits Align = AI.getIndirectAlign(); 2286 Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType)); 2287 Attrs.addAlignmentAttr(Align.getQuantity()); 2288 break; 2289 } 2290 case ABIArgInfo::Ignore: 2291 case ABIArgInfo::Expand: 2292 case ABIArgInfo::CoerceAndExpand: 2293 break; 2294 2295 case ABIArgInfo::InAlloca: 2296 // inalloca disables readnone and readonly. 2297 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2298 .removeAttribute(llvm::Attribute::ReadNone); 2299 continue; 2300 } 2301 2302 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) { 2303 QualType PTy = RefTy->getPointeeType(); 2304 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 2305 Attrs.addDereferenceableAttr( 2306 getMinimumObjectSize(PTy).getQuantity()); 2307 if (getContext().getTargetAddressSpace(PTy) == 0 && 2308 !CodeGenOpts.NullPointerIsValid) 2309 Attrs.addAttribute(llvm::Attribute::NonNull); 2310 if (PTy->isObjectType()) { 2311 llvm::Align Alignment = 2312 getNaturalPointeeTypeAlignment(ParamType).getAsAlign(); 2313 Attrs.addAlignmentAttr(Alignment); 2314 } 2315 } 2316 2317 switch (FI.getExtParameterInfo(ArgNo).getABI()) { 2318 case ParameterABI::Ordinary: 2319 break; 2320 2321 case ParameterABI::SwiftIndirectResult: { 2322 // Add 'sret' if we haven't already used it for something, but 2323 // only if the result is void. 2324 if (!hasUsedSRet && RetTy->isVoidType()) { 2325 Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType)); 2326 hasUsedSRet = true; 2327 } 2328 2329 // Add 'noalias' in either case. 2330 Attrs.addAttribute(llvm::Attribute::NoAlias); 2331 2332 // Add 'dereferenceable' and 'alignment'. 2333 auto PTy = ParamType->getPointeeType(); 2334 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) { 2335 auto info = getContext().getTypeInfoInChars(PTy); 2336 Attrs.addDereferenceableAttr(info.Width.getQuantity()); 2337 Attrs.addAlignmentAttr(info.Align.getAsAlign()); 2338 } 2339 break; 2340 } 2341 2342 case ParameterABI::SwiftErrorResult: 2343 Attrs.addAttribute(llvm::Attribute::SwiftError); 2344 break; 2345 2346 case ParameterABI::SwiftContext: 2347 Attrs.addAttribute(llvm::Attribute::SwiftSelf); 2348 break; 2349 } 2350 2351 if (FI.getExtParameterInfo(ArgNo).isNoEscape()) 2352 Attrs.addAttribute(llvm::Attribute::NoCapture); 2353 2354 if (Attrs.hasAttributes()) { 2355 unsigned FirstIRArg, NumIRArgs; 2356 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2357 for (unsigned i = 0; i < NumIRArgs; i++) 2358 ArgAttrs[FirstIRArg + i] = 2359 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2360 } 2361 } 2362 assert(ArgNo == FI.arg_size()); 2363 2364 AttrList = llvm::AttributeList::get( 2365 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs), 2366 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs); 2367 } 2368 2369 /// An argument came in as a promoted argument; demote it back to its 2370 /// declared type. 2371 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF, 2372 const VarDecl *var, 2373 llvm::Value *value) { 2374 llvm::Type *varType = CGF.ConvertType(var->getType()); 2375 2376 // This can happen with promotions that actually don't change the 2377 // underlying type, like the enum promotions. 2378 if (value->getType() == varType) return value; 2379 2380 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) 2381 && "unexpected promotion type"); 2382 2383 if (isa<llvm::IntegerType>(varType)) 2384 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote"); 2385 2386 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote"); 2387 } 2388 2389 /// Returns the attribute (either parameter attribute, or function 2390 /// attribute), which declares argument ArgNo to be non-null. 2391 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, 2392 QualType ArgType, unsigned ArgNo) { 2393 // FIXME: __attribute__((nonnull)) can also be applied to: 2394 // - references to pointers, where the pointee is known to be 2395 // nonnull (apparently a Clang extension) 2396 // - transparent unions containing pointers 2397 // In the former case, LLVM IR cannot represent the constraint. In 2398 // the latter case, we have no guarantee that the transparent union 2399 // is in fact passed as a pointer. 2400 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType()) 2401 return nullptr; 2402 // First, check attribute on parameter itself. 2403 if (PVD) { 2404 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>()) 2405 return ParmNNAttr; 2406 } 2407 // Check function attributes. 2408 if (!FD) 2409 return nullptr; 2410 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) { 2411 if (NNAttr->isNonNull(ArgNo)) 2412 return NNAttr; 2413 } 2414 return nullptr; 2415 } 2416 2417 namespace { 2418 struct CopyBackSwiftError final : EHScopeStack::Cleanup { 2419 Address Temp; 2420 Address Arg; 2421 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {} 2422 void Emit(CodeGenFunction &CGF, Flags flags) override { 2423 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp); 2424 CGF.Builder.CreateStore(errorValue, Arg); 2425 } 2426 }; 2427 } 2428 2429 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 2430 llvm::Function *Fn, 2431 const FunctionArgList &Args) { 2432 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) 2433 // Naked functions don't have prologues. 2434 return; 2435 2436 // If this is an implicit-return-zero function, go ahead and 2437 // initialize the return value. TODO: it might be nice to have 2438 // a more general mechanism for this that didn't require synthesized 2439 // return statements. 2440 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) { 2441 if (FD->hasImplicitReturnZero()) { 2442 QualType RetTy = FD->getReturnType().getUnqualifiedType(); 2443 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 2444 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 2445 Builder.CreateStore(Zero, ReturnValue); 2446 } 2447 } 2448 2449 // FIXME: We no longer need the types from FunctionArgList; lift up and 2450 // simplify. 2451 2452 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI); 2453 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs()); 2454 2455 // If we're using inalloca, all the memory arguments are GEPs off of the last 2456 // parameter, which is a pointer to the complete memory area. 2457 Address ArgStruct = Address::invalid(); 2458 if (IRFunctionArgs.hasInallocaArg()) { 2459 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()), 2460 FI.getArgStructAlignment()); 2461 2462 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo()); 2463 } 2464 2465 // Name the struct return parameter. 2466 if (IRFunctionArgs.hasSRetArg()) { 2467 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo()); 2468 AI->setName("agg.result"); 2469 AI->addAttr(llvm::Attribute::NoAlias); 2470 } 2471 2472 // Track if we received the parameter as a pointer (indirect, byval, or 2473 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it 2474 // into a local alloca for us. 2475 SmallVector<ParamValue, 16> ArgVals; 2476 ArgVals.reserve(Args.size()); 2477 2478 // Create a pointer value for every parameter declaration. This usually 2479 // entails copying one or more LLVM IR arguments into an alloca. Don't push 2480 // any cleanups or do anything that might unwind. We do that separately, so 2481 // we can push the cleanups in the correct order for the ABI. 2482 assert(FI.arg_size() == Args.size() && 2483 "Mismatch between function signature & arguments."); 2484 unsigned ArgNo = 0; 2485 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 2486 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 2487 i != e; ++i, ++info_it, ++ArgNo) { 2488 const VarDecl *Arg = *i; 2489 const ABIArgInfo &ArgI = info_it->info; 2490 2491 bool isPromoted = 2492 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted(); 2493 // We are converting from ABIArgInfo type to VarDecl type directly, unless 2494 // the parameter is promoted. In this case we convert to 2495 // CGFunctionInfo::ArgInfo type with subsequent argument demotion. 2496 QualType Ty = isPromoted ? info_it->type : Arg->getType(); 2497 assert(hasScalarEvaluationKind(Ty) == 2498 hasScalarEvaluationKind(Arg->getType())); 2499 2500 unsigned FirstIRArg, NumIRArgs; 2501 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2502 2503 switch (ArgI.getKind()) { 2504 case ABIArgInfo::InAlloca: { 2505 assert(NumIRArgs == 0); 2506 auto FieldIndex = ArgI.getInAllocaFieldIndex(); 2507 Address V = 2508 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName()); 2509 if (ArgI.getInAllocaIndirect()) 2510 V = Address(Builder.CreateLoad(V), 2511 getContext().getTypeAlignInChars(Ty)); 2512 ArgVals.push_back(ParamValue::forIndirect(V)); 2513 break; 2514 } 2515 2516 case ABIArgInfo::Indirect: 2517 case ABIArgInfo::IndirectAliased: { 2518 assert(NumIRArgs == 1); 2519 Address ParamAddr = 2520 Address(Fn->getArg(FirstIRArg), ArgI.getIndirectAlign()); 2521 2522 if (!hasScalarEvaluationKind(Ty)) { 2523 // Aggregates and complex variables are accessed by reference. All we 2524 // need to do is realign the value, if requested. Also, if the address 2525 // may be aliased, copy it to ensure that the parameter variable is 2526 // mutable and has a unique adress, as C requires. 2527 Address V = ParamAddr; 2528 if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) { 2529 Address AlignedTemp = CreateMemTemp(Ty, "coerce"); 2530 2531 // Copy from the incoming argument pointer to the temporary with the 2532 // appropriate alignment. 2533 // 2534 // FIXME: We should have a common utility for generating an aggregate 2535 // copy. 2536 CharUnits Size = getContext().getTypeSizeInChars(Ty); 2537 Builder.CreateMemCpy( 2538 AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(), 2539 ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(), 2540 llvm::ConstantInt::get(IntPtrTy, Size.getQuantity())); 2541 V = AlignedTemp; 2542 } 2543 ArgVals.push_back(ParamValue::forIndirect(V)); 2544 } else { 2545 // Load scalar value from indirect argument. 2546 llvm::Value *V = 2547 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc()); 2548 2549 if (isPromoted) 2550 V = emitArgumentDemotion(*this, Arg, V); 2551 ArgVals.push_back(ParamValue::forDirect(V)); 2552 } 2553 break; 2554 } 2555 2556 case ABIArgInfo::Extend: 2557 case ABIArgInfo::Direct: { 2558 auto AI = Fn->getArg(FirstIRArg); 2559 llvm::Type *LTy = ConvertType(Arg->getType()); 2560 2561 // Prepare parameter attributes. So far, only attributes for pointer 2562 // parameters are prepared. See 2563 // http://llvm.org/docs/LangRef.html#paramattrs. 2564 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() && 2565 ArgI.getCoerceToType()->isPointerTy()) { 2566 assert(NumIRArgs == 1); 2567 2568 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) { 2569 // Set `nonnull` attribute if any. 2570 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(), 2571 PVD->getFunctionScopeIndex()) && 2572 !CGM.getCodeGenOpts().NullPointerIsValid) 2573 AI->addAttr(llvm::Attribute::NonNull); 2574 2575 QualType OTy = PVD->getOriginalType(); 2576 if (const auto *ArrTy = 2577 getContext().getAsConstantArrayType(OTy)) { 2578 // A C99 array parameter declaration with the static keyword also 2579 // indicates dereferenceability, and if the size is constant we can 2580 // use the dereferenceable attribute (which requires the size in 2581 // bytes). 2582 if (ArrTy->getSizeModifier() == ArrayType::Static) { 2583 QualType ETy = ArrTy->getElementType(); 2584 llvm::Align Alignment = 2585 CGM.getNaturalTypeAlignment(ETy).getAsAlign(); 2586 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment)); 2587 uint64_t ArrSize = ArrTy->getSize().getZExtValue(); 2588 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() && 2589 ArrSize) { 2590 llvm::AttrBuilder Attrs; 2591 Attrs.addDereferenceableAttr( 2592 getContext().getTypeSizeInChars(ETy).getQuantity() * 2593 ArrSize); 2594 AI->addAttrs(Attrs); 2595 } else if (getContext().getTargetInfo().getNullPointerValue( 2596 ETy.getAddressSpace()) == 0 && 2597 !CGM.getCodeGenOpts().NullPointerIsValid) { 2598 AI->addAttr(llvm::Attribute::NonNull); 2599 } 2600 } 2601 } else if (const auto *ArrTy = 2602 getContext().getAsVariableArrayType(OTy)) { 2603 // For C99 VLAs with the static keyword, we don't know the size so 2604 // we can't use the dereferenceable attribute, but in addrspace(0) 2605 // we know that it must be nonnull. 2606 if (ArrTy->getSizeModifier() == VariableArrayType::Static) { 2607 QualType ETy = ArrTy->getElementType(); 2608 llvm::Align Alignment = 2609 CGM.getNaturalTypeAlignment(ETy).getAsAlign(); 2610 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(Alignment)); 2611 if (!getContext().getTargetAddressSpace(ETy) && 2612 !CGM.getCodeGenOpts().NullPointerIsValid) 2613 AI->addAttr(llvm::Attribute::NonNull); 2614 } 2615 } 2616 2617 // Set `align` attribute if any. 2618 const auto *AVAttr = PVD->getAttr<AlignValueAttr>(); 2619 if (!AVAttr) 2620 if (const auto *TOTy = dyn_cast<TypedefType>(OTy)) 2621 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>(); 2622 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) { 2623 // If alignment-assumption sanitizer is enabled, we do *not* add 2624 // alignment attribute here, but emit normal alignment assumption, 2625 // so the UBSAN check could function. 2626 llvm::ConstantInt *AlignmentCI = 2627 cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment())); 2628 unsigned AlignmentInt = 2629 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment); 2630 if (AI->getParamAlign().valueOrOne() < AlignmentInt) { 2631 AI->removeAttr(llvm::Attribute::AttrKind::Alignment); 2632 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr( 2633 llvm::Align(AlignmentInt))); 2634 } 2635 } 2636 } 2637 2638 // Set 'noalias' if an argument type has the `restrict` qualifier. 2639 if (Arg->getType().isRestrictQualified()) 2640 AI->addAttr(llvm::Attribute::NoAlias); 2641 } 2642 2643 // Prepare the argument value. If we have the trivial case, handle it 2644 // with no muss and fuss. 2645 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) && 2646 ArgI.getCoerceToType() == ConvertType(Ty) && 2647 ArgI.getDirectOffset() == 0) { 2648 assert(NumIRArgs == 1); 2649 2650 // LLVM expects swifterror parameters to be used in very restricted 2651 // ways. Copy the value into a less-restricted temporary. 2652 llvm::Value *V = AI; 2653 if (FI.getExtParameterInfo(ArgNo).getABI() 2654 == ParameterABI::SwiftErrorResult) { 2655 QualType pointeeTy = Ty->getPointeeType(); 2656 assert(pointeeTy->isPointerType()); 2657 Address temp = 2658 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 2659 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy)); 2660 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg); 2661 Builder.CreateStore(incomingErrorValue, temp); 2662 V = temp.getPointer(); 2663 2664 // Push a cleanup to copy the value back at the end of the function. 2665 // The convention does not guarantee that the value will be written 2666 // back if the function exits with an unwind exception. 2667 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg); 2668 } 2669 2670 // Ensure the argument is the correct type. 2671 if (V->getType() != ArgI.getCoerceToType()) 2672 V = Builder.CreateBitCast(V, ArgI.getCoerceToType()); 2673 2674 if (isPromoted) 2675 V = emitArgumentDemotion(*this, Arg, V); 2676 2677 // Because of merging of function types from multiple decls it is 2678 // possible for the type of an argument to not match the corresponding 2679 // type in the function type. Since we are codegening the callee 2680 // in here, add a cast to the argument type. 2681 llvm::Type *LTy = ConvertType(Arg->getType()); 2682 if (V->getType() != LTy) 2683 V = Builder.CreateBitCast(V, LTy); 2684 2685 ArgVals.push_back(ParamValue::forDirect(V)); 2686 break; 2687 } 2688 2689 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg), 2690 Arg->getName()); 2691 2692 // Pointer to store into. 2693 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI); 2694 2695 // Fast-isel and the optimizer generally like scalar values better than 2696 // FCAs, so we flatten them if this is safe to do for this argument. 2697 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType()); 2698 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy && 2699 STy->getNumElements() > 1) { 2700 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy); 2701 llvm::Type *DstTy = Ptr.getElementType(); 2702 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy); 2703 2704 Address AddrToStoreInto = Address::invalid(); 2705 if (SrcSize <= DstSize) { 2706 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy); 2707 } else { 2708 AddrToStoreInto = 2709 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce"); 2710 } 2711 2712 assert(STy->getNumElements() == NumIRArgs); 2713 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2714 auto AI = Fn->getArg(FirstIRArg + i); 2715 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 2716 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i); 2717 Builder.CreateStore(AI, EltPtr); 2718 } 2719 2720 if (SrcSize > DstSize) { 2721 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize); 2722 } 2723 2724 } else { 2725 // Simple case, just do a coerced store of the argument into the alloca. 2726 assert(NumIRArgs == 1); 2727 auto AI = Fn->getArg(FirstIRArg); 2728 AI->setName(Arg->getName() + ".coerce"); 2729 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this); 2730 } 2731 2732 // Match to what EmitParmDecl is expecting for this type. 2733 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) { 2734 llvm::Value *V = 2735 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc()); 2736 if (isPromoted) 2737 V = emitArgumentDemotion(*this, Arg, V); 2738 ArgVals.push_back(ParamValue::forDirect(V)); 2739 } else { 2740 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2741 } 2742 break; 2743 } 2744 2745 case ABIArgInfo::CoerceAndExpand: { 2746 // Reconstruct into a temporary. 2747 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2748 ArgVals.push_back(ParamValue::forIndirect(alloca)); 2749 2750 auto coercionType = ArgI.getCoerceAndExpandType(); 2751 alloca = Builder.CreateElementBitCast(alloca, coercionType); 2752 2753 unsigned argIndex = FirstIRArg; 2754 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 2755 llvm::Type *eltType = coercionType->getElementType(i); 2756 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) 2757 continue; 2758 2759 auto eltAddr = Builder.CreateStructGEP(alloca, i); 2760 auto elt = Fn->getArg(argIndex++); 2761 Builder.CreateStore(elt, eltAddr); 2762 } 2763 assert(argIndex == FirstIRArg + NumIRArgs); 2764 break; 2765 } 2766 2767 case ABIArgInfo::Expand: { 2768 // If this structure was expanded into multiple arguments then 2769 // we need to create a temporary and reconstruct it from the 2770 // arguments. 2771 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2772 LValue LV = MakeAddrLValue(Alloca, Ty); 2773 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2774 2775 auto FnArgIter = Fn->arg_begin() + FirstIRArg; 2776 ExpandTypeFromArgs(Ty, LV, FnArgIter); 2777 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs); 2778 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) { 2779 auto AI = Fn->getArg(FirstIRArg + i); 2780 AI->setName(Arg->getName() + "." + Twine(i)); 2781 } 2782 break; 2783 } 2784 2785 case ABIArgInfo::Ignore: 2786 assert(NumIRArgs == 0); 2787 // Initialize the local variable appropriately. 2788 if (!hasScalarEvaluationKind(Ty)) { 2789 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty))); 2790 } else { 2791 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType())); 2792 ArgVals.push_back(ParamValue::forDirect(U)); 2793 } 2794 break; 2795 } 2796 } 2797 2798 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2799 for (int I = Args.size() - 1; I >= 0; --I) 2800 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2801 } else { 2802 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2803 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2804 } 2805 } 2806 2807 static void eraseUnusedBitCasts(llvm::Instruction *insn) { 2808 while (insn->use_empty()) { 2809 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn); 2810 if (!bitcast) return; 2811 2812 // This is "safe" because we would have used a ConstantExpr otherwise. 2813 insn = cast<llvm::Instruction>(bitcast->getOperand(0)); 2814 bitcast->eraseFromParent(); 2815 } 2816 } 2817 2818 /// Try to emit a fused autorelease of a return result. 2819 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, 2820 llvm::Value *result) { 2821 // We must be immediately followed the cast. 2822 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock(); 2823 if (BB->empty()) return nullptr; 2824 if (&BB->back() != result) return nullptr; 2825 2826 llvm::Type *resultType = result->getType(); 2827 2828 // result is in a BasicBlock and is therefore an Instruction. 2829 llvm::Instruction *generator = cast<llvm::Instruction>(result); 2830 2831 SmallVector<llvm::Instruction *, 4> InstsToKill; 2832 2833 // Look for: 2834 // %generator = bitcast %type1* %generator2 to %type2* 2835 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) { 2836 // We would have emitted this as a constant if the operand weren't 2837 // an Instruction. 2838 generator = cast<llvm::Instruction>(bitcast->getOperand(0)); 2839 2840 // Require the generator to be immediately followed by the cast. 2841 if (generator->getNextNode() != bitcast) 2842 return nullptr; 2843 2844 InstsToKill.push_back(bitcast); 2845 } 2846 2847 // Look for: 2848 // %generator = call i8* @objc_retain(i8* %originalResult) 2849 // or 2850 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult) 2851 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator); 2852 if (!call) return nullptr; 2853 2854 bool doRetainAutorelease; 2855 2856 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) { 2857 doRetainAutorelease = true; 2858 } else if (call->getCalledOperand() == 2859 CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) { 2860 doRetainAutorelease = false; 2861 2862 // If we emitted an assembly marker for this call (and the 2863 // ARCEntrypoints field should have been set if so), go looking 2864 // for that call. If we can't find it, we can't do this 2865 // optimization. But it should always be the immediately previous 2866 // instruction, unless we needed bitcasts around the call. 2867 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) { 2868 llvm::Instruction *prev = call->getPrevNode(); 2869 assert(prev); 2870 if (isa<llvm::BitCastInst>(prev)) { 2871 prev = prev->getPrevNode(); 2872 assert(prev); 2873 } 2874 assert(isa<llvm::CallInst>(prev)); 2875 assert(cast<llvm::CallInst>(prev)->getCalledOperand() == 2876 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker); 2877 InstsToKill.push_back(prev); 2878 } 2879 } else { 2880 return nullptr; 2881 } 2882 2883 result = call->getArgOperand(0); 2884 InstsToKill.push_back(call); 2885 2886 // Keep killing bitcasts, for sanity. Note that we no longer care 2887 // about precise ordering as long as there's exactly one use. 2888 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) { 2889 if (!bitcast->hasOneUse()) break; 2890 InstsToKill.push_back(bitcast); 2891 result = bitcast->getOperand(0); 2892 } 2893 2894 // Delete all the unnecessary instructions, from latest to earliest. 2895 for (auto *I : InstsToKill) 2896 I->eraseFromParent(); 2897 2898 // Do the fused retain/autorelease if we were asked to. 2899 if (doRetainAutorelease) 2900 result = CGF.EmitARCRetainAutoreleaseReturnValue(result); 2901 2902 // Cast back to the result type. 2903 return CGF.Builder.CreateBitCast(result, resultType); 2904 } 2905 2906 /// If this is a +1 of the value of an immutable 'self', remove it. 2907 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, 2908 llvm::Value *result) { 2909 // This is only applicable to a method with an immutable 'self'. 2910 const ObjCMethodDecl *method = 2911 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl); 2912 if (!method) return nullptr; 2913 const VarDecl *self = method->getSelfDecl(); 2914 if (!self->getType().isConstQualified()) return nullptr; 2915 2916 // Look for a retain call. 2917 llvm::CallInst *retainCall = 2918 dyn_cast<llvm::CallInst>(result->stripPointerCasts()); 2919 if (!retainCall || retainCall->getCalledOperand() != 2920 CGF.CGM.getObjCEntrypoints().objc_retain) 2921 return nullptr; 2922 2923 // Look for an ordinary load of 'self'. 2924 llvm::Value *retainedValue = retainCall->getArgOperand(0); 2925 llvm::LoadInst *load = 2926 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); 2927 if (!load || load->isAtomic() || load->isVolatile() || 2928 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) 2929 return nullptr; 2930 2931 // Okay! Burn it all down. This relies for correctness on the 2932 // assumption that the retain is emitted as part of the return and 2933 // that thereafter everything is used "linearly". 2934 llvm::Type *resultType = result->getType(); 2935 eraseUnusedBitCasts(cast<llvm::Instruction>(result)); 2936 assert(retainCall->use_empty()); 2937 retainCall->eraseFromParent(); 2938 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue)); 2939 2940 return CGF.Builder.CreateBitCast(load, resultType); 2941 } 2942 2943 /// Emit an ARC autorelease of the result of a function. 2944 /// 2945 /// \return the value to actually return from the function 2946 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF, 2947 llvm::Value *result) { 2948 // If we're returning 'self', kill the initial retain. This is a 2949 // heuristic attempt to "encourage correctness" in the really unfortunate 2950 // case where we have a return of self during a dealloc and we desperately 2951 // need to avoid the possible autorelease. 2952 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result)) 2953 return self; 2954 2955 // At -O0, try to emit a fused retain/autorelease. 2956 if (CGF.shouldUseFusedARCCalls()) 2957 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result)) 2958 return fused; 2959 2960 return CGF.EmitARCAutoreleaseReturnValue(result); 2961 } 2962 2963 /// Heuristically search for a dominating store to the return-value slot. 2964 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) { 2965 // Check if a User is a store which pointerOperand is the ReturnValue. 2966 // We are looking for stores to the ReturnValue, not for stores of the 2967 // ReturnValue to some other location. 2968 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * { 2969 auto *SI = dyn_cast<llvm::StoreInst>(U); 2970 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer()) 2971 return nullptr; 2972 // These aren't actually possible for non-coerced returns, and we 2973 // only care about non-coerced returns on this code path. 2974 assert(!SI->isAtomic() && !SI->isVolatile()); 2975 return SI; 2976 }; 2977 // If there are multiple uses of the return-value slot, just check 2978 // for something immediately preceding the IP. Sometimes this can 2979 // happen with how we generate implicit-returns; it can also happen 2980 // with noreturn cleanups. 2981 if (!CGF.ReturnValue.getPointer()->hasOneUse()) { 2982 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2983 if (IP->empty()) return nullptr; 2984 llvm::Instruction *I = &IP->back(); 2985 2986 // Skip lifetime markers 2987 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(), 2988 IE = IP->rend(); 2989 II != IE; ++II) { 2990 if (llvm::IntrinsicInst *Intrinsic = 2991 dyn_cast<llvm::IntrinsicInst>(&*II)) { 2992 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) { 2993 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1); 2994 ++II; 2995 if (II == IE) 2996 break; 2997 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II)) 2998 continue; 2999 } 3000 } 3001 I = &*II; 3002 break; 3003 } 3004 3005 return GetStoreIfValid(I); 3006 } 3007 3008 llvm::StoreInst *store = 3009 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back()); 3010 if (!store) return nullptr; 3011 3012 // Now do a first-and-dirty dominance check: just walk up the 3013 // single-predecessors chain from the current insertion point. 3014 llvm::BasicBlock *StoreBB = store->getParent(); 3015 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 3016 while (IP != StoreBB) { 3017 if (!(IP = IP->getSinglePredecessor())) 3018 return nullptr; 3019 } 3020 3021 // Okay, the store's basic block dominates the insertion point; we 3022 // can do our thing. 3023 return store; 3024 } 3025 3026 // Helper functions for EmitCMSEClearRecord 3027 3028 // Set the bits corresponding to a field having width `BitWidth` and located at 3029 // offset `BitOffset` (from the least significant bit) within a storage unit of 3030 // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte. 3031 // Use little-endian layout, i.e.`Bits[0]` is the LSB. 3032 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset, 3033 int BitWidth, int CharWidth) { 3034 assert(CharWidth <= 64); 3035 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth); 3036 3037 int Pos = 0; 3038 if (BitOffset >= CharWidth) { 3039 Pos += BitOffset / CharWidth; 3040 BitOffset = BitOffset % CharWidth; 3041 } 3042 3043 const uint64_t Used = (uint64_t(1) << CharWidth) - 1; 3044 if (BitOffset + BitWidth >= CharWidth) { 3045 Bits[Pos++] |= (Used << BitOffset) & Used; 3046 BitWidth -= CharWidth - BitOffset; 3047 BitOffset = 0; 3048 } 3049 3050 while (BitWidth >= CharWidth) { 3051 Bits[Pos++] = Used; 3052 BitWidth -= CharWidth; 3053 } 3054 3055 if (BitWidth > 0) 3056 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset; 3057 } 3058 3059 // Set the bits corresponding to a field having width `BitWidth` and located at 3060 // offset `BitOffset` (from the least significant bit) within a storage unit of 3061 // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of 3062 // `Bits` corresponds to one target byte. Use target endian layout. 3063 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset, 3064 int StorageSize, int BitOffset, int BitWidth, 3065 int CharWidth, bool BigEndian) { 3066 3067 SmallVector<uint64_t, 8> TmpBits(StorageSize); 3068 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth); 3069 3070 if (BigEndian) 3071 std::reverse(TmpBits.begin(), TmpBits.end()); 3072 3073 for (uint64_t V : TmpBits) 3074 Bits[StorageOffset++] |= V; 3075 } 3076 3077 static void setUsedBits(CodeGenModule &, QualType, int, 3078 SmallVectorImpl<uint64_t> &); 3079 3080 // Set the bits in `Bits`, which correspond to the value representations of 3081 // the actual members of the record type `RTy`. Note that this function does 3082 // not handle base classes, virtual tables, etc, since they cannot happen in 3083 // CMSE function arguments or return. The bit mask corresponds to the target 3084 // memory layout, i.e. it's endian dependent. 3085 static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset, 3086 SmallVectorImpl<uint64_t> &Bits) { 3087 ASTContext &Context = CGM.getContext(); 3088 int CharWidth = Context.getCharWidth(); 3089 const RecordDecl *RD = RTy->getDecl()->getDefinition(); 3090 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD); 3091 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD); 3092 3093 int Idx = 0; 3094 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) { 3095 const FieldDecl *F = *I; 3096 3097 if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) || 3098 F->getType()->isIncompleteArrayType()) 3099 continue; 3100 3101 if (F->isBitField()) { 3102 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F); 3103 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(), 3104 BFI.StorageSize / CharWidth, BFI.Offset, 3105 BFI.Size, CharWidth, 3106 CGM.getDataLayout().isBigEndian()); 3107 continue; 3108 } 3109 3110 setUsedBits(CGM, F->getType(), 3111 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits); 3112 } 3113 } 3114 3115 // Set the bits in `Bits`, which correspond to the value representations of 3116 // the elements of an array type `ATy`. 3117 static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy, 3118 int Offset, SmallVectorImpl<uint64_t> &Bits) { 3119 const ASTContext &Context = CGM.getContext(); 3120 3121 QualType ETy = Context.getBaseElementType(ATy); 3122 int Size = Context.getTypeSizeInChars(ETy).getQuantity(); 3123 SmallVector<uint64_t, 4> TmpBits(Size); 3124 setUsedBits(CGM, ETy, 0, TmpBits); 3125 3126 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) { 3127 auto Src = TmpBits.begin(); 3128 auto Dst = Bits.begin() + Offset + I * Size; 3129 for (int J = 0; J < Size; ++J) 3130 *Dst++ |= *Src++; 3131 } 3132 } 3133 3134 // Set the bits in `Bits`, which correspond to the value representations of 3135 // the type `QTy`. 3136 static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset, 3137 SmallVectorImpl<uint64_t> &Bits) { 3138 if (const auto *RTy = QTy->getAs<RecordType>()) 3139 return setUsedBits(CGM, RTy, Offset, Bits); 3140 3141 ASTContext &Context = CGM.getContext(); 3142 if (const auto *ATy = Context.getAsConstantArrayType(QTy)) 3143 return setUsedBits(CGM, ATy, Offset, Bits); 3144 3145 int Size = Context.getTypeSizeInChars(QTy).getQuantity(); 3146 if (Size <= 0) 3147 return; 3148 3149 std::fill_n(Bits.begin() + Offset, Size, 3150 (uint64_t(1) << Context.getCharWidth()) - 1); 3151 } 3152 3153 static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits, 3154 int Pos, int Size, int CharWidth, 3155 bool BigEndian) { 3156 assert(Size > 0); 3157 uint64_t Mask = 0; 3158 if (BigEndian) { 3159 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E; 3160 ++P) 3161 Mask = (Mask << CharWidth) | *P; 3162 } else { 3163 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos; 3164 do 3165 Mask = (Mask << CharWidth) | *--P; 3166 while (P != End); 3167 } 3168 return Mask; 3169 } 3170 3171 // Emit code to clear the bits in a record, which aren't a part of any user 3172 // declared member, when the record is a function return. 3173 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src, 3174 llvm::IntegerType *ITy, 3175 QualType QTy) { 3176 assert(Src->getType() == ITy); 3177 assert(ITy->getScalarSizeInBits() <= 64); 3178 3179 const llvm::DataLayout &DataLayout = CGM.getDataLayout(); 3180 int Size = DataLayout.getTypeStoreSize(ITy); 3181 SmallVector<uint64_t, 4> Bits(Size); 3182 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits); 3183 3184 int CharWidth = CGM.getContext().getCharWidth(); 3185 uint64_t Mask = 3186 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian()); 3187 3188 return Builder.CreateAnd(Src, Mask, "cmse.clear"); 3189 } 3190 3191 // Emit code to clear the bits in a record, which aren't a part of any user 3192 // declared member, when the record is a function argument. 3193 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src, 3194 llvm::ArrayType *ATy, 3195 QualType QTy) { 3196 const llvm::DataLayout &DataLayout = CGM.getDataLayout(); 3197 int Size = DataLayout.getTypeStoreSize(ATy); 3198 SmallVector<uint64_t, 16> Bits(Size); 3199 setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits); 3200 3201 // Clear each element of the LLVM array. 3202 int CharWidth = CGM.getContext().getCharWidth(); 3203 int CharsPerElt = 3204 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth; 3205 int MaskIndex = 0; 3206 llvm::Value *R = llvm::UndefValue::get(ATy); 3207 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) { 3208 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth, 3209 DataLayout.isBigEndian()); 3210 MaskIndex += CharsPerElt; 3211 llvm::Value *T0 = Builder.CreateExtractValue(Src, I); 3212 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear"); 3213 R = Builder.CreateInsertValue(R, T1, I); 3214 } 3215 3216 return R; 3217 } 3218 3219 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 3220 bool EmitRetDbgLoc, 3221 SourceLocation EndLoc) { 3222 if (FI.isNoReturn()) { 3223 // Noreturn functions don't return. 3224 EmitUnreachable(EndLoc); 3225 return; 3226 } 3227 3228 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) { 3229 // Naked functions don't have epilogues. 3230 Builder.CreateUnreachable(); 3231 return; 3232 } 3233 3234 // Functions with no result always return void. 3235 if (!ReturnValue.isValid()) { 3236 Builder.CreateRetVoid(); 3237 return; 3238 } 3239 3240 llvm::DebugLoc RetDbgLoc; 3241 llvm::Value *RV = nullptr; 3242 QualType RetTy = FI.getReturnType(); 3243 const ABIArgInfo &RetAI = FI.getReturnInfo(); 3244 3245 switch (RetAI.getKind()) { 3246 case ABIArgInfo::InAlloca: 3247 // Aggregrates get evaluated directly into the destination. Sometimes we 3248 // need to return the sret value in a register, though. 3249 assert(hasAggregateEvaluationKind(RetTy)); 3250 if (RetAI.getInAllocaSRet()) { 3251 llvm::Function::arg_iterator EI = CurFn->arg_end(); 3252 --EI; 3253 llvm::Value *ArgStruct = &*EI; 3254 llvm::Value *SRet = Builder.CreateStructGEP( 3255 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex()); 3256 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret"); 3257 } 3258 break; 3259 3260 case ABIArgInfo::Indirect: { 3261 auto AI = CurFn->arg_begin(); 3262 if (RetAI.isSRetAfterThis()) 3263 ++AI; 3264 switch (getEvaluationKind(RetTy)) { 3265 case TEK_Complex: { 3266 ComplexPairTy RT = 3267 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc); 3268 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy), 3269 /*isInit*/ true); 3270 break; 3271 } 3272 case TEK_Aggregate: 3273 // Do nothing; aggregrates get evaluated directly into the destination. 3274 break; 3275 case TEK_Scalar: 3276 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), 3277 MakeNaturalAlignAddrLValue(&*AI, RetTy), 3278 /*isInit*/ true); 3279 break; 3280 } 3281 break; 3282 } 3283 3284 case ABIArgInfo::Extend: 3285 case ABIArgInfo::Direct: 3286 if (RetAI.getCoerceToType() == ConvertType(RetTy) && 3287 RetAI.getDirectOffset() == 0) { 3288 // The internal return value temp always will have pointer-to-return-type 3289 // type, just do a load. 3290 3291 // If there is a dominating store to ReturnValue, we can elide 3292 // the load, zap the store, and usually zap the alloca. 3293 if (llvm::StoreInst *SI = 3294 findDominatingStoreToReturnValue(*this)) { 3295 // Reuse the debug location from the store unless there is 3296 // cleanup code to be emitted between the store and return 3297 // instruction. 3298 if (EmitRetDbgLoc && !AutoreleaseResult) 3299 RetDbgLoc = SI->getDebugLoc(); 3300 // Get the stored value and nuke the now-dead store. 3301 RV = SI->getValueOperand(); 3302 SI->eraseFromParent(); 3303 3304 // Otherwise, we have to do a simple load. 3305 } else { 3306 RV = Builder.CreateLoad(ReturnValue); 3307 } 3308 } else { 3309 // If the value is offset in memory, apply the offset now. 3310 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI); 3311 3312 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this); 3313 } 3314 3315 // In ARC, end functions that return a retainable type with a call 3316 // to objc_autoreleaseReturnValue. 3317 if (AutoreleaseResult) { 3318 #ifndef NDEBUG 3319 // Type::isObjCRetainabletype has to be called on a QualType that hasn't 3320 // been stripped of the typedefs, so we cannot use RetTy here. Get the 3321 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from 3322 // CurCodeDecl or BlockInfo. 3323 QualType RT; 3324 3325 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl)) 3326 RT = FD->getReturnType(); 3327 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl)) 3328 RT = MD->getReturnType(); 3329 else if (isa<BlockDecl>(CurCodeDecl)) 3330 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType(); 3331 else 3332 llvm_unreachable("Unexpected function/method type"); 3333 3334 assert(getLangOpts().ObjCAutoRefCount && 3335 !FI.isReturnsRetained() && 3336 RT->isObjCRetainableType()); 3337 #endif 3338 RV = emitAutoreleaseOfResult(*this, RV); 3339 } 3340 3341 break; 3342 3343 case ABIArgInfo::Ignore: 3344 break; 3345 3346 case ABIArgInfo::CoerceAndExpand: { 3347 auto coercionType = RetAI.getCoerceAndExpandType(); 3348 3349 // Load all of the coerced elements out into results. 3350 llvm::SmallVector<llvm::Value*, 4> results; 3351 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType); 3352 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 3353 auto coercedEltType = coercionType->getElementType(i); 3354 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType)) 3355 continue; 3356 3357 auto eltAddr = Builder.CreateStructGEP(addr, i); 3358 auto elt = Builder.CreateLoad(eltAddr); 3359 results.push_back(elt); 3360 } 3361 3362 // If we have one result, it's the single direct result type. 3363 if (results.size() == 1) { 3364 RV = results[0]; 3365 3366 // Otherwise, we need to make a first-class aggregate. 3367 } else { 3368 // Construct a return type that lacks padding elements. 3369 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType(); 3370 3371 RV = llvm::UndefValue::get(returnType); 3372 for (unsigned i = 0, e = results.size(); i != e; ++i) { 3373 RV = Builder.CreateInsertValue(RV, results[i], i); 3374 } 3375 } 3376 break; 3377 } 3378 case ABIArgInfo::Expand: 3379 case ABIArgInfo::IndirectAliased: 3380 llvm_unreachable("Invalid ABI kind for return argument"); 3381 } 3382 3383 llvm::Instruction *Ret; 3384 if (RV) { 3385 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) { 3386 // For certain return types, clear padding bits, as they may reveal 3387 // sensitive information. 3388 // Small struct/union types are passed as integers. 3389 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType()); 3390 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType())) 3391 RV = EmitCMSEClearRecord(RV, ITy, RetTy); 3392 } 3393 EmitReturnValueCheck(RV); 3394 Ret = Builder.CreateRet(RV); 3395 } else { 3396 Ret = Builder.CreateRetVoid(); 3397 } 3398 3399 if (RetDbgLoc) 3400 Ret->setDebugLoc(std::move(RetDbgLoc)); 3401 } 3402 3403 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) { 3404 // A current decl may not be available when emitting vtable thunks. 3405 if (!CurCodeDecl) 3406 return; 3407 3408 // If the return block isn't reachable, neither is this check, so don't emit 3409 // it. 3410 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) 3411 return; 3412 3413 ReturnsNonNullAttr *RetNNAttr = nullptr; 3414 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) 3415 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>(); 3416 3417 if (!RetNNAttr && !requiresReturnValueNullabilityCheck()) 3418 return; 3419 3420 // Prefer the returns_nonnull attribute if it's present. 3421 SourceLocation AttrLoc; 3422 SanitizerMask CheckKind; 3423 SanitizerHandler Handler; 3424 if (RetNNAttr) { 3425 assert(!requiresReturnValueNullabilityCheck() && 3426 "Cannot check nullability and the nonnull attribute"); 3427 AttrLoc = RetNNAttr->getLocation(); 3428 CheckKind = SanitizerKind::ReturnsNonnullAttribute; 3429 Handler = SanitizerHandler::NonnullReturn; 3430 } else { 3431 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl)) 3432 if (auto *TSI = DD->getTypeSourceInfo()) 3433 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>()) 3434 AttrLoc = FTL.getReturnLoc().findNullabilityLoc(); 3435 CheckKind = SanitizerKind::NullabilityReturn; 3436 Handler = SanitizerHandler::NullabilityReturn; 3437 } 3438 3439 SanitizerScope SanScope(this); 3440 3441 // Make sure the "return" source location is valid. If we're checking a 3442 // nullability annotation, make sure the preconditions for the check are met. 3443 llvm::BasicBlock *Check = createBasicBlock("nullcheck"); 3444 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck"); 3445 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load"); 3446 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr); 3447 if (requiresReturnValueNullabilityCheck()) 3448 CanNullCheck = 3449 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition); 3450 Builder.CreateCondBr(CanNullCheck, Check, NoCheck); 3451 EmitBlock(Check); 3452 3453 // Now do the null check. 3454 llvm::Value *Cond = Builder.CreateIsNotNull(RV); 3455 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)}; 3456 llvm::Value *DynamicData[] = {SLocPtr}; 3457 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData); 3458 3459 EmitBlock(NoCheck); 3460 3461 #ifndef NDEBUG 3462 // The return location should not be used after the check has been emitted. 3463 ReturnLocation = Address::invalid(); 3464 #endif 3465 } 3466 3467 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) { 3468 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 3469 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory; 3470 } 3471 3472 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, 3473 QualType Ty) { 3474 // FIXME: Generate IR in one pass, rather than going back and fixing up these 3475 // placeholders. 3476 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty); 3477 llvm::Type *IRPtrTy = IRTy->getPointerTo(); 3478 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo()); 3479 3480 // FIXME: When we generate this IR in one pass, we shouldn't need 3481 // this win32-specific alignment hack. 3482 CharUnits Align = CharUnits::fromQuantity(4); 3483 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align); 3484 3485 return AggValueSlot::forAddr(Address(Placeholder, Align), 3486 Ty.getQualifiers(), 3487 AggValueSlot::IsNotDestructed, 3488 AggValueSlot::DoesNotNeedGCBarriers, 3489 AggValueSlot::IsNotAliased, 3490 AggValueSlot::DoesNotOverlap); 3491 } 3492 3493 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args, 3494 const VarDecl *param, 3495 SourceLocation loc) { 3496 // StartFunction converted the ABI-lowered parameter(s) into a 3497 // local alloca. We need to turn that into an r-value suitable 3498 // for EmitCall. 3499 Address local = GetAddrOfLocalVar(param); 3500 3501 QualType type = param->getType(); 3502 3503 if (isInAllocaArgument(CGM.getCXXABI(), type)) { 3504 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter"); 3505 } 3506 3507 // GetAddrOfLocalVar returns a pointer-to-pointer for references, 3508 // but the argument needs to be the original pointer. 3509 if (type->isReferenceType()) { 3510 args.add(RValue::get(Builder.CreateLoad(local)), type); 3511 3512 // In ARC, move out of consumed arguments so that the release cleanup 3513 // entered by StartFunction doesn't cause an over-release. This isn't 3514 // optimal -O0 code generation, but it should get cleaned up when 3515 // optimization is enabled. This also assumes that delegate calls are 3516 // performed exactly once for a set of arguments, but that should be safe. 3517 } else if (getLangOpts().ObjCAutoRefCount && 3518 param->hasAttr<NSConsumedAttr>() && 3519 type->isObjCRetainableType()) { 3520 llvm::Value *ptr = Builder.CreateLoad(local); 3521 auto null = 3522 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType())); 3523 Builder.CreateStore(null, local); 3524 args.add(RValue::get(ptr), type); 3525 3526 // For the most part, we just need to load the alloca, except that 3527 // aggregate r-values are actually pointers to temporaries. 3528 } else { 3529 args.add(convertTempToRValue(local, type, loc), type); 3530 } 3531 3532 // Deactivate the cleanup for the callee-destructed param that was pushed. 3533 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk && 3534 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() && 3535 param->needsDestruction(getContext())) { 3536 EHScopeStack::stable_iterator cleanup = 3537 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param)); 3538 assert(cleanup.isValid() && 3539 "cleanup for callee-destructed param not recorded"); 3540 // This unreachable is a temporary marker which will be removed later. 3541 llvm::Instruction *isActive = Builder.CreateUnreachable(); 3542 args.addArgCleanupDeactivation(cleanup, isActive); 3543 } 3544 } 3545 3546 static bool isProvablyNull(llvm::Value *addr) { 3547 return isa<llvm::ConstantPointerNull>(addr); 3548 } 3549 3550 /// Emit the actual writing-back of a writeback. 3551 static void emitWriteback(CodeGenFunction &CGF, 3552 const CallArgList::Writeback &writeback) { 3553 const LValue &srcLV = writeback.Source; 3554 Address srcAddr = srcLV.getAddress(CGF); 3555 assert(!isProvablyNull(srcAddr.getPointer()) && 3556 "shouldn't have writeback for provably null argument"); 3557 3558 llvm::BasicBlock *contBB = nullptr; 3559 3560 // If the argument wasn't provably non-null, we need to null check 3561 // before doing the store. 3562 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3563 CGF.CGM.getDataLayout()); 3564 if (!provablyNonNull) { 3565 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback"); 3566 contBB = CGF.createBasicBlock("icr.done"); 3567 3568 llvm::Value *isNull = 3569 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3570 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB); 3571 CGF.EmitBlock(writebackBB); 3572 } 3573 3574 // Load the value to writeback. 3575 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary); 3576 3577 // Cast it back, in case we're writing an id to a Foo* or something. 3578 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), 3579 "icr.writeback-cast"); 3580 3581 // Perform the writeback. 3582 3583 // If we have a "to use" value, it's something we need to emit a use 3584 // of. This has to be carefully threaded in: if it's done after the 3585 // release it's potentially undefined behavior (and the optimizer 3586 // will ignore it), and if it happens before the retain then the 3587 // optimizer could move the release there. 3588 if (writeback.ToUse) { 3589 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong); 3590 3591 // Retain the new value. No need to block-copy here: the block's 3592 // being passed up the stack. 3593 value = CGF.EmitARCRetainNonBlock(value); 3594 3595 // Emit the intrinsic use here. 3596 CGF.EmitARCIntrinsicUse(writeback.ToUse); 3597 3598 // Load the old value (primitively). 3599 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation()); 3600 3601 // Put the new value in place (primitively). 3602 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false); 3603 3604 // Release the old value. 3605 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime()); 3606 3607 // Otherwise, we can just do a normal lvalue store. 3608 } else { 3609 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV); 3610 } 3611 3612 // Jump to the continuation block. 3613 if (!provablyNonNull) 3614 CGF.EmitBlock(contBB); 3615 } 3616 3617 static void emitWritebacks(CodeGenFunction &CGF, 3618 const CallArgList &args) { 3619 for (const auto &I : args.writebacks()) 3620 emitWriteback(CGF, I); 3621 } 3622 3623 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, 3624 const CallArgList &CallArgs) { 3625 ArrayRef<CallArgList::CallArgCleanup> Cleanups = 3626 CallArgs.getCleanupsToDeactivate(); 3627 // Iterate in reverse to increase the likelihood of popping the cleanup. 3628 for (const auto &I : llvm::reverse(Cleanups)) { 3629 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP); 3630 I.IsActiveIP->eraseFromParent(); 3631 } 3632 } 3633 3634 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) { 3635 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens())) 3636 if (uop->getOpcode() == UO_AddrOf) 3637 return uop->getSubExpr(); 3638 return nullptr; 3639 } 3640 3641 /// Emit an argument that's being passed call-by-writeback. That is, 3642 /// we are passing the address of an __autoreleased temporary; it 3643 /// might be copy-initialized with the current value of the given 3644 /// address, but it will definitely be copied out of after the call. 3645 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, 3646 const ObjCIndirectCopyRestoreExpr *CRE) { 3647 LValue srcLV; 3648 3649 // Make an optimistic effort to emit the address as an l-value. 3650 // This can fail if the argument expression is more complicated. 3651 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) { 3652 srcLV = CGF.EmitLValue(lvExpr); 3653 3654 // Otherwise, just emit it as a scalar. 3655 } else { 3656 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr()); 3657 3658 QualType srcAddrType = 3659 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 3660 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType); 3661 } 3662 Address srcAddr = srcLV.getAddress(CGF); 3663 3664 // The dest and src types don't necessarily match in LLVM terms 3665 // because of the crazy ObjC compatibility rules. 3666 3667 llvm::PointerType *destType = 3668 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType())); 3669 3670 // If the address is a constant null, just pass the appropriate null. 3671 if (isProvablyNull(srcAddr.getPointer())) { 3672 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)), 3673 CRE->getType()); 3674 return; 3675 } 3676 3677 // Create the temporary. 3678 Address temp = CGF.CreateTempAlloca(destType->getElementType(), 3679 CGF.getPointerAlign(), 3680 "icr.temp"); 3681 // Loading an l-value can introduce a cleanup if the l-value is __weak, 3682 // and that cleanup will be conditional if we can't prove that the l-value 3683 // isn't null, so we need to register a dominating point so that the cleanups 3684 // system will make valid IR. 3685 CodeGenFunction::ConditionalEvaluation condEval(CGF); 3686 3687 // Zero-initialize it if we're not doing a copy-initialization. 3688 bool shouldCopy = CRE->shouldCopy(); 3689 if (!shouldCopy) { 3690 llvm::Value *null = 3691 llvm::ConstantPointerNull::get( 3692 cast<llvm::PointerType>(destType->getElementType())); 3693 CGF.Builder.CreateStore(null, temp); 3694 } 3695 3696 llvm::BasicBlock *contBB = nullptr; 3697 llvm::BasicBlock *originBB = nullptr; 3698 3699 // If the address is *not* known to be non-null, we need to switch. 3700 llvm::Value *finalArgument; 3701 3702 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3703 CGF.CGM.getDataLayout()); 3704 if (provablyNonNull) { 3705 finalArgument = temp.getPointer(); 3706 } else { 3707 llvm::Value *isNull = 3708 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3709 3710 finalArgument = CGF.Builder.CreateSelect(isNull, 3711 llvm::ConstantPointerNull::get(destType), 3712 temp.getPointer(), "icr.argument"); 3713 3714 // If we need to copy, then the load has to be conditional, which 3715 // means we need control flow. 3716 if (shouldCopy) { 3717 originBB = CGF.Builder.GetInsertBlock(); 3718 contBB = CGF.createBasicBlock("icr.cont"); 3719 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy"); 3720 CGF.Builder.CreateCondBr(isNull, contBB, copyBB); 3721 CGF.EmitBlock(copyBB); 3722 condEval.begin(CGF); 3723 } 3724 } 3725 3726 llvm::Value *valueToUse = nullptr; 3727 3728 // Perform a copy if necessary. 3729 if (shouldCopy) { 3730 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation()); 3731 assert(srcRV.isScalar()); 3732 3733 llvm::Value *src = srcRV.getScalarVal(); 3734 src = CGF.Builder.CreateBitCast(src, destType->getElementType(), 3735 "icr.cast"); 3736 3737 // Use an ordinary store, not a store-to-lvalue. 3738 CGF.Builder.CreateStore(src, temp); 3739 3740 // If optimization is enabled, and the value was held in a 3741 // __strong variable, we need to tell the optimizer that this 3742 // value has to stay alive until we're doing the store back. 3743 // This is because the temporary is effectively unretained, 3744 // and so otherwise we can violate the high-level semantics. 3745 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 && 3746 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) { 3747 valueToUse = src; 3748 } 3749 } 3750 3751 // Finish the control flow if we needed it. 3752 if (shouldCopy && !provablyNonNull) { 3753 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); 3754 CGF.EmitBlock(contBB); 3755 3756 // Make a phi for the value to intrinsically use. 3757 if (valueToUse) { 3758 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2, 3759 "icr.to-use"); 3760 phiToUse->addIncoming(valueToUse, copyBB); 3761 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()), 3762 originBB); 3763 valueToUse = phiToUse; 3764 } 3765 3766 condEval.end(CGF); 3767 } 3768 3769 args.addWriteback(srcLV, temp, valueToUse); 3770 args.add(RValue::get(finalArgument), CRE->getType()); 3771 } 3772 3773 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) { 3774 assert(!StackBase); 3775 3776 // Save the stack. 3777 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave); 3778 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save"); 3779 } 3780 3781 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const { 3782 if (StackBase) { 3783 // Restore the stack after the call. 3784 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 3785 CGF.Builder.CreateCall(F, StackBase); 3786 } 3787 } 3788 3789 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, 3790 SourceLocation ArgLoc, 3791 AbstractCallee AC, 3792 unsigned ParmNum) { 3793 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) || 3794 SanOpts.has(SanitizerKind::NullabilityArg))) 3795 return; 3796 3797 // The param decl may be missing in a variadic function. 3798 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr; 3799 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; 3800 3801 // Prefer the nonnull attribute if it's present. 3802 const NonNullAttr *NNAttr = nullptr; 3803 if (SanOpts.has(SanitizerKind::NonnullAttribute)) 3804 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo); 3805 3806 bool CanCheckNullability = false; 3807 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) { 3808 auto Nullability = PVD->getType()->getNullability(getContext()); 3809 CanCheckNullability = Nullability && 3810 *Nullability == NullabilityKind::NonNull && 3811 PVD->getTypeSourceInfo(); 3812 } 3813 3814 if (!NNAttr && !CanCheckNullability) 3815 return; 3816 3817 SourceLocation AttrLoc; 3818 SanitizerMask CheckKind; 3819 SanitizerHandler Handler; 3820 if (NNAttr) { 3821 AttrLoc = NNAttr->getLocation(); 3822 CheckKind = SanitizerKind::NonnullAttribute; 3823 Handler = SanitizerHandler::NonnullArg; 3824 } else { 3825 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc(); 3826 CheckKind = SanitizerKind::NullabilityArg; 3827 Handler = SanitizerHandler::NullabilityArg; 3828 } 3829 3830 SanitizerScope SanScope(this); 3831 llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType); 3832 llvm::Constant *StaticData[] = { 3833 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc), 3834 llvm::ConstantInt::get(Int32Ty, ArgNo + 1), 3835 }; 3836 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None); 3837 } 3838 3839 // Check if the call is going to use the inalloca convention. This needs to 3840 // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged 3841 // later, so we can't check it directly. 3842 static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC, 3843 ArrayRef<QualType> ArgTypes) { 3844 // The Swift calling convention doesn't go through the target-specific 3845 // argument classification, so it never uses inalloca. 3846 // TODO: Consider limiting inalloca use to only calling conventions supported 3847 // by MSVC. 3848 if (ExplicitCC == CC_Swift) 3849 return false; 3850 if (!CGM.getTarget().getCXXABI().isMicrosoft()) 3851 return false; 3852 return llvm::any_of(ArgTypes, [&](QualType Ty) { 3853 return isInAllocaArgument(CGM.getCXXABI(), Ty); 3854 }); 3855 } 3856 3857 #ifndef NDEBUG 3858 // Determine whether the given argument is an Objective-C method 3859 // that may have type parameters in its signature. 3860 static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) { 3861 const DeclContext *dc = method->getDeclContext(); 3862 if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) { 3863 return classDecl->getTypeParamListAsWritten(); 3864 } 3865 3866 if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) { 3867 return catDecl->getTypeParamList(); 3868 } 3869 3870 return false; 3871 } 3872 #endif 3873 3874 /// EmitCallArgs - Emit call arguments for a function. 3875 void CodeGenFunction::EmitCallArgs( 3876 CallArgList &Args, PrototypeWrapper Prototype, 3877 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3878 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) { 3879 SmallVector<QualType, 16> ArgTypes; 3880 3881 assert((ParamsToSkip == 0 || Prototype.P) && 3882 "Can't skip parameters if type info is not provided"); 3883 3884 // This variable only captures *explicitly* written conventions, not those 3885 // applied by default via command line flags or target defaults, such as 3886 // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would 3887 // require knowing if this is a C++ instance method or being able to see 3888 // unprototyped FunctionTypes. 3889 CallingConv ExplicitCC = CC_C; 3890 3891 // First, if a prototype was provided, use those argument types. 3892 bool IsVariadic = false; 3893 if (Prototype.P) { 3894 const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>(); 3895 if (MD) { 3896 IsVariadic = MD->isVariadic(); 3897 ExplicitCC = getCallingConventionForDecl( 3898 MD, CGM.getTarget().getTriple().isOSWindows()); 3899 ArgTypes.assign(MD->param_type_begin() + ParamsToSkip, 3900 MD->param_type_end()); 3901 } else { 3902 const auto *FPT = Prototype.P.get<const FunctionProtoType *>(); 3903 IsVariadic = FPT->isVariadic(); 3904 ExplicitCC = FPT->getExtInfo().getCC(); 3905 ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip, 3906 FPT->param_type_end()); 3907 } 3908 3909 #ifndef NDEBUG 3910 // Check that the prototyped types match the argument expression types. 3911 bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD); 3912 CallExpr::const_arg_iterator Arg = ArgRange.begin(); 3913 for (QualType Ty : ArgTypes) { 3914 assert(Arg != ArgRange.end() && "Running over edge of argument list!"); 3915 assert( 3916 (isGenericMethod || Ty->isVariablyModifiedType() || 3917 Ty.getNonReferenceType()->isObjCRetainableType() || 3918 getContext() 3919 .getCanonicalType(Ty.getNonReferenceType()) 3920 .getTypePtr() == 3921 getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) && 3922 "type mismatch in call argument!"); 3923 ++Arg; 3924 } 3925 3926 // Either we've emitted all the call args, or we have a call to variadic 3927 // function. 3928 assert((Arg == ArgRange.end() || IsVariadic) && 3929 "Extra arguments in non-variadic function!"); 3930 #endif 3931 } 3932 3933 // If we still have any arguments, emit them using the type of the argument. 3934 for (auto *A : llvm::make_range(std::next(ArgRange.begin(), ArgTypes.size()), 3935 ArgRange.end())) 3936 ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType()); 3937 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())); 3938 3939 // We must evaluate arguments from right to left in the MS C++ ABI, 3940 // because arguments are destroyed left to right in the callee. As a special 3941 // case, there are certain language constructs that require left-to-right 3942 // evaluation, and in those cases we consider the evaluation order requirement 3943 // to trump the "destruction order is reverse construction order" guarantee. 3944 bool LeftToRight = 3945 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee() 3946 ? Order == EvaluationOrder::ForceLeftToRight 3947 : Order != EvaluationOrder::ForceRightToLeft; 3948 3949 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg, 3950 RValue EmittedArg) { 3951 if (!AC.hasFunctionDecl() || I >= AC.getNumParams()) 3952 return; 3953 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>(); 3954 if (PS == nullptr) 3955 return; 3956 3957 const auto &Context = getContext(); 3958 auto SizeTy = Context.getSizeType(); 3959 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy)); 3960 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?"); 3961 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T, 3962 EmittedArg.getScalarVal(), 3963 PS->isDynamic()); 3964 Args.add(RValue::get(V), SizeTy); 3965 // If we're emitting args in reverse, be sure to do so with 3966 // pass_object_size, as well. 3967 if (!LeftToRight) 3968 std::swap(Args.back(), *(&Args.back() - 1)); 3969 }; 3970 3971 // Insert a stack save if we're going to need any inalloca args. 3972 if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) { 3973 assert(getTarget().getTriple().getArch() == llvm::Triple::x86 && 3974 "inalloca only supported on x86"); 3975 Args.allocateArgumentMemory(*this); 3976 } 3977 3978 // Evaluate each argument in the appropriate order. 3979 size_t CallArgsStart = Args.size(); 3980 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) { 3981 unsigned Idx = LeftToRight ? I : E - I - 1; 3982 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx; 3983 unsigned InitialArgSize = Args.size(); 3984 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of 3985 // the argument and parameter match or the objc method is parameterized. 3986 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || 3987 getContext().hasSameUnqualifiedType((*Arg)->getType(), 3988 ArgTypes[Idx]) || 3989 (isa<ObjCMethodDecl>(AC.getDecl()) && 3990 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && 3991 "Argument and parameter types don't match"); 3992 EmitCallArg(Args, *Arg, ArgTypes[Idx]); 3993 // In particular, we depend on it being the last arg in Args, and the 3994 // objectsize bits depend on there only being one arg if !LeftToRight. 3995 assert(InitialArgSize + 1 == Args.size() && 3996 "The code below depends on only adding one arg per EmitCallArg"); 3997 (void)InitialArgSize; 3998 // Since pointer argument are never emitted as LValue, it is safe to emit 3999 // non-null argument check for r-value only. 4000 if (!Args.back().hasLValue()) { 4001 RValue RVArg = Args.back().getKnownRValue(); 4002 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC, 4003 ParamsToSkip + Idx); 4004 // @llvm.objectsize should never have side-effects and shouldn't need 4005 // destruction/cleanups, so we can safely "emit" it after its arg, 4006 // regardless of right-to-leftness 4007 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg); 4008 } 4009 } 4010 4011 if (!LeftToRight) { 4012 // Un-reverse the arguments we just evaluated so they match up with the LLVM 4013 // IR function. 4014 std::reverse(Args.begin() + CallArgsStart, Args.end()); 4015 } 4016 } 4017 4018 namespace { 4019 4020 struct DestroyUnpassedArg final : EHScopeStack::Cleanup { 4021 DestroyUnpassedArg(Address Addr, QualType Ty) 4022 : Addr(Addr), Ty(Ty) {} 4023 4024 Address Addr; 4025 QualType Ty; 4026 4027 void Emit(CodeGenFunction &CGF, Flags flags) override { 4028 QualType::DestructionKind DtorKind = Ty.isDestructedType(); 4029 if (DtorKind == QualType::DK_cxx_destructor) { 4030 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 4031 assert(!Dtor->isTrivial()); 4032 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false, 4033 /*Delegating=*/false, Addr, Ty); 4034 } else { 4035 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty)); 4036 } 4037 } 4038 }; 4039 4040 struct DisableDebugLocationUpdates { 4041 CodeGenFunction &CGF; 4042 bool disabledDebugInfo; 4043 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) { 4044 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo())) 4045 CGF.disableDebugInfo(); 4046 } 4047 ~DisableDebugLocationUpdates() { 4048 if (disabledDebugInfo) 4049 CGF.enableDebugInfo(); 4050 } 4051 }; 4052 4053 } // end anonymous namespace 4054 4055 RValue CallArg::getRValue(CodeGenFunction &CGF) const { 4056 if (!HasLV) 4057 return RV; 4058 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty); 4059 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap, 4060 LV.isVolatile()); 4061 IsUsed = true; 4062 return RValue::getAggregate(Copy.getAddress(CGF)); 4063 } 4064 4065 void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const { 4066 LValue Dst = CGF.MakeAddrLValue(Addr, Ty); 4067 if (!HasLV && RV.isScalar()) 4068 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true); 4069 else if (!HasLV && RV.isComplex()) 4070 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true); 4071 else { 4072 auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress(); 4073 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty); 4074 // We assume that call args are never copied into subobjects. 4075 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap, 4076 HasLV ? LV.isVolatileQualified() 4077 : RV.isVolatileQualified()); 4078 } 4079 IsUsed = true; 4080 } 4081 4082 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, 4083 QualType type) { 4084 DisableDebugLocationUpdates Dis(*this, E); 4085 if (const ObjCIndirectCopyRestoreExpr *CRE 4086 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { 4087 assert(getLangOpts().ObjCAutoRefCount); 4088 return emitWritebackArg(*this, args, CRE); 4089 } 4090 4091 assert(type->isReferenceType() == E->isGLValue() && 4092 "reference binding to unmaterialized r-value!"); 4093 4094 if (E->isGLValue()) { 4095 assert(E->getObjectKind() == OK_Ordinary); 4096 return args.add(EmitReferenceBindingToExpr(E), type); 4097 } 4098 4099 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type); 4100 4101 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee. 4102 // However, we still have to push an EH-only cleanup in case we unwind before 4103 // we make it to the call. 4104 if (HasAggregateEvalKind && 4105 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) { 4106 // If we're using inalloca, use the argument memory. Otherwise, use a 4107 // temporary. 4108 AggValueSlot Slot; 4109 if (args.isUsingInAlloca()) 4110 Slot = createPlaceholderSlot(*this, type); 4111 else 4112 Slot = CreateAggTemp(type, "agg.tmp"); 4113 4114 bool DestroyedInCallee = true, NeedsEHCleanup = true; 4115 if (const auto *RD = type->getAsCXXRecordDecl()) 4116 DestroyedInCallee = RD->hasNonTrivialDestructor(); 4117 else 4118 NeedsEHCleanup = needsEHCleanup(type.isDestructedType()); 4119 4120 if (DestroyedInCallee) 4121 Slot.setExternallyDestructed(); 4122 4123 EmitAggExpr(E, Slot); 4124 RValue RV = Slot.asRValue(); 4125 args.add(RV, type); 4126 4127 if (DestroyedInCallee && NeedsEHCleanup) { 4128 // Create a no-op GEP between the placeholder and the cleanup so we can 4129 // RAUW it successfully. It also serves as a marker of the first 4130 // instruction where the cleanup is active. 4131 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(), 4132 type); 4133 // This unreachable is a temporary marker which will be removed later. 4134 llvm::Instruction *IsActive = Builder.CreateUnreachable(); 4135 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive); 4136 } 4137 return; 4138 } 4139 4140 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) && 4141 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 4142 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 4143 assert(L.isSimple()); 4144 args.addUncopiedAggregate(L, type); 4145 return; 4146 } 4147 4148 args.add(EmitAnyExprToTemp(E), type); 4149 } 4150 4151 QualType CodeGenFunction::getVarArgType(const Expr *Arg) { 4152 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC 4153 // implicitly widens null pointer constants that are arguments to varargs 4154 // functions to pointer-sized ints. 4155 if (!getTarget().getTriple().isOSWindows()) 4156 return Arg->getType(); 4157 4158 if (Arg->getType()->isIntegerType() && 4159 getContext().getTypeSize(Arg->getType()) < 4160 getContext().getTargetInfo().getPointerWidth(0) && 4161 Arg->isNullPointerConstant(getContext(), 4162 Expr::NPC_ValueDependentIsNotNull)) { 4163 return getContext().getIntPtrType(); 4164 } 4165 4166 return Arg->getType(); 4167 } 4168 4169 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 4170 // optimizer it can aggressively ignore unwind edges. 4171 void 4172 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 4173 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 4174 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 4175 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 4176 CGM.getNoObjCARCExceptionsMetadata()); 4177 } 4178 4179 /// Emits a call to the given no-arguments nounwind runtime function. 4180 llvm::CallInst * 4181 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 4182 const llvm::Twine &name) { 4183 return EmitNounwindRuntimeCall(callee, None, name); 4184 } 4185 4186 /// Emits a call to the given nounwind runtime function. 4187 llvm::CallInst * 4188 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 4189 ArrayRef<llvm::Value *> args, 4190 const llvm::Twine &name) { 4191 llvm::CallInst *call = EmitRuntimeCall(callee, args, name); 4192 call->setDoesNotThrow(); 4193 return call; 4194 } 4195 4196 /// Emits a simple call (never an invoke) to the given no-arguments 4197 /// runtime function. 4198 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 4199 const llvm::Twine &name) { 4200 return EmitRuntimeCall(callee, None, name); 4201 } 4202 4203 // Calls which may throw must have operand bundles indicating which funclet 4204 // they are nested within. 4205 SmallVector<llvm::OperandBundleDef, 1> 4206 CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) { 4207 SmallVector<llvm::OperandBundleDef, 1> BundleList; 4208 // There is no need for a funclet operand bundle if we aren't inside a 4209 // funclet. 4210 if (!CurrentFuncletPad) 4211 return BundleList; 4212 4213 // Skip intrinsics which cannot throw. 4214 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts()); 4215 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) 4216 return BundleList; 4217 4218 BundleList.emplace_back("funclet", CurrentFuncletPad); 4219 return BundleList; 4220 } 4221 4222 /// Emits a simple call (never an invoke) to the given runtime function. 4223 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 4224 ArrayRef<llvm::Value *> args, 4225 const llvm::Twine &name) { 4226 llvm::CallInst *call = Builder.CreateCall( 4227 callee, args, getBundlesForFunclet(callee.getCallee()), name); 4228 call->setCallingConv(getRuntimeCC()); 4229 return call; 4230 } 4231 4232 /// Emits a call or invoke to the given noreturn runtime function. 4233 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke( 4234 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) { 4235 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4236 getBundlesForFunclet(callee.getCallee()); 4237 4238 if (getInvokeDest()) { 4239 llvm::InvokeInst *invoke = 4240 Builder.CreateInvoke(callee, 4241 getUnreachableBlock(), 4242 getInvokeDest(), 4243 args, 4244 BundleList); 4245 invoke->setDoesNotReturn(); 4246 invoke->setCallingConv(getRuntimeCC()); 4247 } else { 4248 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList); 4249 call->setDoesNotReturn(); 4250 call->setCallingConv(getRuntimeCC()); 4251 Builder.CreateUnreachable(); 4252 } 4253 } 4254 4255 /// Emits a call or invoke instruction to the given nullary runtime function. 4256 llvm::CallBase * 4257 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 4258 const Twine &name) { 4259 return EmitRuntimeCallOrInvoke(callee, None, name); 4260 } 4261 4262 /// Emits a call or invoke instruction to the given runtime function. 4263 llvm::CallBase * 4264 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 4265 ArrayRef<llvm::Value *> args, 4266 const Twine &name) { 4267 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name); 4268 call->setCallingConv(getRuntimeCC()); 4269 return call; 4270 } 4271 4272 /// Emits a call or invoke instruction to the given function, depending 4273 /// on the current state of the EH stack. 4274 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee, 4275 ArrayRef<llvm::Value *> Args, 4276 const Twine &Name) { 4277 llvm::BasicBlock *InvokeDest = getInvokeDest(); 4278 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4279 getBundlesForFunclet(Callee.getCallee()); 4280 4281 llvm::CallBase *Inst; 4282 if (!InvokeDest) 4283 Inst = Builder.CreateCall(Callee, Args, BundleList, Name); 4284 else { 4285 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 4286 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList, 4287 Name); 4288 EmitBlock(ContBB); 4289 } 4290 4291 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 4292 // optimizer it can aggressively ignore unwind edges. 4293 if (CGM.getLangOpts().ObjCAutoRefCount) 4294 AddObjCARCExceptionMetadata(Inst); 4295 4296 return Inst; 4297 } 4298 4299 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old, 4300 llvm::Value *New) { 4301 DeferredReplacements.push_back(std::make_pair(Old, New)); 4302 } 4303 4304 namespace { 4305 4306 /// Specify given \p NewAlign as the alignment of return value attribute. If 4307 /// such attribute already exists, re-set it to the maximal one of two options. 4308 LLVM_NODISCARD llvm::AttributeList 4309 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx, 4310 const llvm::AttributeList &Attrs, 4311 llvm::Align NewAlign) { 4312 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne(); 4313 if (CurAlign >= NewAlign) 4314 return Attrs; 4315 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign); 4316 return Attrs 4317 .removeAttribute(Ctx, llvm::AttributeList::ReturnIndex, 4318 llvm::Attribute::AttrKind::Alignment) 4319 .addAttribute(Ctx, llvm::AttributeList::ReturnIndex, AlignAttr); 4320 } 4321 4322 template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter { 4323 protected: 4324 CodeGenFunction &CGF; 4325 4326 /// We do nothing if this is, or becomes, nullptr. 4327 const AlignedAttrTy *AA = nullptr; 4328 4329 llvm::Value *Alignment = nullptr; // May or may not be a constant. 4330 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero. 4331 4332 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl) 4333 : CGF(CGF_) { 4334 if (!FuncDecl) 4335 return; 4336 AA = FuncDecl->getAttr<AlignedAttrTy>(); 4337 } 4338 4339 public: 4340 /// If we can, materialize the alignment as an attribute on return value. 4341 LLVM_NODISCARD llvm::AttributeList 4342 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) { 4343 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment)) 4344 return Attrs; 4345 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment); 4346 if (!AlignmentCI) 4347 return Attrs; 4348 // We may legitimately have non-power-of-2 alignment here. 4349 // If so, this is UB land, emit it via `@llvm.assume` instead. 4350 if (!AlignmentCI->getValue().isPowerOf2()) 4351 return Attrs; 4352 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute( 4353 CGF.getLLVMContext(), Attrs, 4354 llvm::Align( 4355 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment))); 4356 AA = nullptr; // We're done. Disallow doing anything else. 4357 return NewAttrs; 4358 } 4359 4360 /// Emit alignment assumption. 4361 /// This is a general fallback that we take if either there is an offset, 4362 /// or the alignment is variable or we are sanitizing for alignment. 4363 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) { 4364 if (!AA) 4365 return; 4366 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, 4367 AA->getLocation(), Alignment, OffsetCI); 4368 AA = nullptr; // We're done. Disallow doing anything else. 4369 } 4370 }; 4371 4372 /// Helper data structure to emit `AssumeAlignedAttr`. 4373 class AssumeAlignedAttrEmitter final 4374 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> { 4375 public: 4376 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl) 4377 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) { 4378 if (!AA) 4379 return; 4380 // It is guaranteed that the alignment/offset are constants. 4381 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment())); 4382 if (Expr *Offset = AA->getOffset()) { 4383 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset)); 4384 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset. 4385 OffsetCI = nullptr; 4386 } 4387 } 4388 }; 4389 4390 /// Helper data structure to emit `AllocAlignAttr`. 4391 class AllocAlignAttrEmitter final 4392 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> { 4393 public: 4394 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl, 4395 const CallArgList &CallArgs) 4396 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) { 4397 if (!AA) 4398 return; 4399 // Alignment may or may not be a constant, and that is okay. 4400 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()] 4401 .getRValue(CGF) 4402 .getScalarVal(); 4403 } 4404 }; 4405 4406 } // namespace 4407 4408 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 4409 const CGCallee &Callee, 4410 ReturnValueSlot ReturnValue, 4411 const CallArgList &CallArgs, 4412 llvm::CallBase **callOrInvoke, 4413 SourceLocation Loc) { 4414 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 4415 4416 assert(Callee.isOrdinary() || Callee.isVirtual()); 4417 4418 // Handle struct-return functions by passing a pointer to the 4419 // location that we would like to return into. 4420 QualType RetTy = CallInfo.getReturnType(); 4421 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 4422 4423 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo); 4424 4425 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl(); 4426 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) { 4427 // We can only guarantee that a function is called from the correct 4428 // context/function based on the appropriate target attributes, 4429 // so only check in the case where we have both always_inline and target 4430 // since otherwise we could be making a conditional call after a check for 4431 // the proper cpu features (and it won't cause code generation issues due to 4432 // function based code generation). 4433 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 4434 TargetDecl->hasAttr<TargetAttr>()) 4435 checkTargetFeatures(Loc, FD); 4436 4437 // Some architectures (such as x86-64) have the ABI changed based on 4438 // attribute-target/features. Give them a chance to diagnose. 4439 CGM.getTargetCodeGenInfo().checkFunctionCallABI( 4440 CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs); 4441 } 4442 4443 #ifndef NDEBUG 4444 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) { 4445 // For an inalloca varargs function, we don't expect CallInfo to match the 4446 // function pointer's type, because the inalloca struct a will have extra 4447 // fields in it for the varargs parameters. Code later in this function 4448 // bitcasts the function pointer to the type derived from CallInfo. 4449 // 4450 // In other cases, we assert that the types match up (until pointers stop 4451 // having pointee types). 4452 llvm::Type *TypeFromVal; 4453 if (Callee.isVirtual()) 4454 TypeFromVal = Callee.getVirtualFunctionType(); 4455 else 4456 TypeFromVal = 4457 Callee.getFunctionPointer()->getType()->getPointerElementType(); 4458 assert(IRFuncTy == TypeFromVal); 4459 } 4460 #endif 4461 4462 // 1. Set up the arguments. 4463 4464 // If we're using inalloca, insert the allocation after the stack save. 4465 // FIXME: Do this earlier rather than hacking it in here! 4466 Address ArgMemory = Address::invalid(); 4467 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) { 4468 const llvm::DataLayout &DL = CGM.getDataLayout(); 4469 llvm::Instruction *IP = CallArgs.getStackBase(); 4470 llvm::AllocaInst *AI; 4471 if (IP) { 4472 IP = IP->getNextNode(); 4473 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), 4474 "argmem", IP); 4475 } else { 4476 AI = CreateTempAlloca(ArgStruct, "argmem"); 4477 } 4478 auto Align = CallInfo.getArgStructAlignment(); 4479 AI->setAlignment(Align.getAsAlign()); 4480 AI->setUsedWithInAlloca(true); 4481 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca()); 4482 ArgMemory = Address(AI, Align); 4483 } 4484 4485 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo); 4486 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs()); 4487 4488 // If the call returns a temporary with struct return, create a temporary 4489 // alloca to hold the result, unless one is given to us. 4490 Address SRetPtr = Address::invalid(); 4491 Address SRetAlloca = Address::invalid(); 4492 llvm::Value *UnusedReturnSizePtr = nullptr; 4493 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) { 4494 if (!ReturnValue.isNull()) { 4495 SRetPtr = ReturnValue.getValue(); 4496 } else { 4497 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca); 4498 if (HaveInsertPoint() && ReturnValue.isUnused()) { 4499 uint64_t size = 4500 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); 4501 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer()); 4502 } 4503 } 4504 if (IRFunctionArgs.hasSRetArg()) { 4505 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer(); 4506 } else if (RetAI.isInAlloca()) { 4507 Address Addr = 4508 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex()); 4509 Builder.CreateStore(SRetPtr.getPointer(), Addr); 4510 } 4511 } 4512 4513 Address swiftErrorTemp = Address::invalid(); 4514 Address swiftErrorArg = Address::invalid(); 4515 4516 // When passing arguments using temporary allocas, we need to add the 4517 // appropriate lifetime markers. This vector keeps track of all the lifetime 4518 // markers that need to be ended right after the call. 4519 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall; 4520 4521 // Translate all of the arguments as necessary to match the IR lowering. 4522 assert(CallInfo.arg_size() == CallArgs.size() && 4523 "Mismatch between function signature & arguments."); 4524 unsigned ArgNo = 0; 4525 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 4526 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 4527 I != E; ++I, ++info_it, ++ArgNo) { 4528 const ABIArgInfo &ArgInfo = info_it->info; 4529 4530 // Insert a padding argument to ensure proper alignment. 4531 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 4532 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 4533 llvm::UndefValue::get(ArgInfo.getPaddingType()); 4534 4535 unsigned FirstIRArg, NumIRArgs; 4536 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 4537 4538 switch (ArgInfo.getKind()) { 4539 case ABIArgInfo::InAlloca: { 4540 assert(NumIRArgs == 0); 4541 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 4542 if (I->isAggregate()) { 4543 Address Addr = I->hasLValue() 4544 ? I->getKnownLValue().getAddress(*this) 4545 : I->getKnownRValue().getAggregateAddress(); 4546 llvm::Instruction *Placeholder = 4547 cast<llvm::Instruction>(Addr.getPointer()); 4548 4549 if (!ArgInfo.getInAllocaIndirect()) { 4550 // Replace the placeholder with the appropriate argument slot GEP. 4551 CGBuilderTy::InsertPoint IP = Builder.saveIP(); 4552 Builder.SetInsertPoint(Placeholder); 4553 Addr = Builder.CreateStructGEP(ArgMemory, 4554 ArgInfo.getInAllocaFieldIndex()); 4555 Builder.restoreIP(IP); 4556 } else { 4557 // For indirect things such as overaligned structs, replace the 4558 // placeholder with a regular aggregate temporary alloca. Store the 4559 // address of this alloca into the struct. 4560 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp"); 4561 Address ArgSlot = Builder.CreateStructGEP( 4562 ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4563 Builder.CreateStore(Addr.getPointer(), ArgSlot); 4564 } 4565 deferPlaceholderReplacement(Placeholder, Addr.getPointer()); 4566 } else if (ArgInfo.getInAllocaIndirect()) { 4567 // Make a temporary alloca and store the address of it into the argument 4568 // struct. 4569 Address Addr = CreateMemTempWithoutCast( 4570 I->Ty, getContext().getTypeAlignInChars(I->Ty), 4571 "indirect-arg-temp"); 4572 I->copyInto(*this, Addr); 4573 Address ArgSlot = 4574 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4575 Builder.CreateStore(Addr.getPointer(), ArgSlot); 4576 } else { 4577 // Store the RValue into the argument struct. 4578 Address Addr = 4579 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4580 unsigned AS = Addr.getType()->getPointerAddressSpace(); 4581 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS); 4582 // There are some cases where a trivial bitcast is not avoidable. The 4583 // definition of a type later in a translation unit may change it's type 4584 // from {}* to (%struct.foo*)*. 4585 if (Addr.getType() != MemType) 4586 Addr = Builder.CreateBitCast(Addr, MemType); 4587 I->copyInto(*this, Addr); 4588 } 4589 break; 4590 } 4591 4592 case ABIArgInfo::Indirect: 4593 case ABIArgInfo::IndirectAliased: { 4594 assert(NumIRArgs == 1); 4595 if (!I->isAggregate()) { 4596 // Make a temporary alloca to pass the argument. 4597 Address Addr = CreateMemTempWithoutCast( 4598 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp"); 4599 IRCallArgs[FirstIRArg] = Addr.getPointer(); 4600 4601 I->copyInto(*this, Addr); 4602 } else { 4603 // We want to avoid creating an unnecessary temporary+copy here; 4604 // however, we need one in three cases: 4605 // 1. If the argument is not byval, and we are required to copy the 4606 // source. (This case doesn't occur on any common architecture.) 4607 // 2. If the argument is byval, RV is not sufficiently aligned, and 4608 // we cannot force it to be sufficiently aligned. 4609 // 3. If the argument is byval, but RV is not located in default 4610 // or alloca address space. 4611 Address Addr = I->hasLValue() 4612 ? I->getKnownLValue().getAddress(*this) 4613 : I->getKnownRValue().getAggregateAddress(); 4614 llvm::Value *V = Addr.getPointer(); 4615 CharUnits Align = ArgInfo.getIndirectAlign(); 4616 const llvm::DataLayout *TD = &CGM.getDataLayout(); 4617 4618 assert((FirstIRArg >= IRFuncTy->getNumParams() || 4619 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == 4620 TD->getAllocaAddrSpace()) && 4621 "indirect argument must be in alloca address space"); 4622 4623 bool NeedCopy = false; 4624 4625 if (Addr.getAlignment() < Align && 4626 llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) < 4627 Align.getAsAlign()) { 4628 NeedCopy = true; 4629 } else if (I->hasLValue()) { 4630 auto LV = I->getKnownLValue(); 4631 auto AS = LV.getAddressSpace(); 4632 4633 if (!ArgInfo.getIndirectByVal() || 4634 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) { 4635 NeedCopy = true; 4636 } 4637 if (!getLangOpts().OpenCL) { 4638 if ((ArgInfo.getIndirectByVal() && 4639 (AS != LangAS::Default && 4640 AS != CGM.getASTAllocaAddressSpace()))) { 4641 NeedCopy = true; 4642 } 4643 } 4644 // For OpenCL even if RV is located in default or alloca address space 4645 // we don't want to perform address space cast for it. 4646 else if ((ArgInfo.getIndirectByVal() && 4647 Addr.getType()->getAddressSpace() != IRFuncTy-> 4648 getParamType(FirstIRArg)->getPointerAddressSpace())) { 4649 NeedCopy = true; 4650 } 4651 } 4652 4653 if (NeedCopy) { 4654 // Create an aligned temporary, and copy to it. 4655 Address AI = CreateMemTempWithoutCast( 4656 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp"); 4657 IRCallArgs[FirstIRArg] = AI.getPointer(); 4658 4659 // Emit lifetime markers for the temporary alloca. 4660 uint64_t ByvalTempElementSize = 4661 CGM.getDataLayout().getTypeAllocSize(AI.getElementType()); 4662 llvm::Value *LifetimeSize = 4663 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer()); 4664 4665 // Add cleanup code to emit the end lifetime marker after the call. 4666 if (LifetimeSize) // In case we disabled lifetime markers. 4667 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize); 4668 4669 // Generate the copy. 4670 I->copyInto(*this, AI); 4671 } else { 4672 // Skip the extra memcpy call. 4673 auto *T = V->getType()->getPointerElementType()->getPointerTo( 4674 CGM.getDataLayout().getAllocaAddrSpace()); 4675 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast( 4676 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T, 4677 true); 4678 } 4679 } 4680 break; 4681 } 4682 4683 case ABIArgInfo::Ignore: 4684 assert(NumIRArgs == 0); 4685 break; 4686 4687 case ABIArgInfo::Extend: 4688 case ABIArgInfo::Direct: { 4689 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 4690 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 4691 ArgInfo.getDirectOffset() == 0) { 4692 assert(NumIRArgs == 1); 4693 llvm::Value *V; 4694 if (!I->isAggregate()) 4695 V = I->getKnownRValue().getScalarVal(); 4696 else 4697 V = Builder.CreateLoad( 4698 I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4699 : I->getKnownRValue().getAggregateAddress()); 4700 4701 // Implement swifterror by copying into a new swifterror argument. 4702 // We'll write back in the normal path out of the call. 4703 if (CallInfo.getExtParameterInfo(ArgNo).getABI() 4704 == ParameterABI::SwiftErrorResult) { 4705 assert(!swiftErrorTemp.isValid() && "multiple swifterror args"); 4706 4707 QualType pointeeTy = I->Ty->getPointeeType(); 4708 swiftErrorArg = 4709 Address(V, getContext().getTypeAlignInChars(pointeeTy)); 4710 4711 swiftErrorTemp = 4712 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 4713 V = swiftErrorTemp.getPointer(); 4714 cast<llvm::AllocaInst>(V)->setSwiftError(true); 4715 4716 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg); 4717 Builder.CreateStore(errorValue, swiftErrorTemp); 4718 } 4719 4720 // We might have to widen integers, but we should never truncate. 4721 if (ArgInfo.getCoerceToType() != V->getType() && 4722 V->getType()->isIntegerTy()) 4723 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType()); 4724 4725 // If the argument doesn't match, perform a bitcast to coerce it. This 4726 // can happen due to trivial type mismatches. 4727 if (FirstIRArg < IRFuncTy->getNumParams() && 4728 V->getType() != IRFuncTy->getParamType(FirstIRArg)) 4729 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg)); 4730 4731 IRCallArgs[FirstIRArg] = V; 4732 break; 4733 } 4734 4735 // FIXME: Avoid the conversion through memory if possible. 4736 Address Src = Address::invalid(); 4737 if (!I->isAggregate()) { 4738 Src = CreateMemTemp(I->Ty, "coerce"); 4739 I->copyInto(*this, Src); 4740 } else { 4741 Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4742 : I->getKnownRValue().getAggregateAddress(); 4743 } 4744 4745 // If the value is offset in memory, apply the offset now. 4746 Src = emitAddressAtOffset(*this, Src, ArgInfo); 4747 4748 // Fast-isel and the optimizer generally like scalar values better than 4749 // FCAs, so we flatten them if this is safe to do for this argument. 4750 llvm::StructType *STy = 4751 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType()); 4752 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 4753 llvm::Type *SrcTy = Src.getElementType(); 4754 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4755 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy); 4756 4757 // If the source type is smaller than the destination type of the 4758 // coerce-to logic, copy the source value into a temp alloca the size 4759 // of the destination type to allow loading all of it. The bits past 4760 // the source value are left undef. 4761 if (SrcSize < DstSize) { 4762 Address TempAlloca 4763 = CreateTempAlloca(STy, Src.getAlignment(), 4764 Src.getName() + ".coerce"); 4765 Builder.CreateMemCpy(TempAlloca, Src, SrcSize); 4766 Src = TempAlloca; 4767 } else { 4768 Src = Builder.CreateBitCast(Src, 4769 STy->getPointerTo(Src.getAddressSpace())); 4770 } 4771 4772 assert(NumIRArgs == STy->getNumElements()); 4773 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 4774 Address EltPtr = Builder.CreateStructGEP(Src, i); 4775 llvm::Value *LI = Builder.CreateLoad(EltPtr); 4776 IRCallArgs[FirstIRArg + i] = LI; 4777 } 4778 } else { 4779 // In the simple case, just pass the coerced loaded value. 4780 assert(NumIRArgs == 1); 4781 llvm::Value *Load = 4782 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this); 4783 4784 if (CallInfo.isCmseNSCall()) { 4785 // For certain parameter types, clear padding bits, as they may reveal 4786 // sensitive information. 4787 // Small struct/union types are passed as integer arrays. 4788 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType()); 4789 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType())) 4790 Load = EmitCMSEClearRecord(Load, ATy, I->Ty); 4791 } 4792 IRCallArgs[FirstIRArg] = Load; 4793 } 4794 4795 break; 4796 } 4797 4798 case ABIArgInfo::CoerceAndExpand: { 4799 auto coercionType = ArgInfo.getCoerceAndExpandType(); 4800 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 4801 4802 llvm::Value *tempSize = nullptr; 4803 Address addr = Address::invalid(); 4804 Address AllocaAddr = Address::invalid(); 4805 if (I->isAggregate()) { 4806 addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4807 : I->getKnownRValue().getAggregateAddress(); 4808 4809 } else { 4810 RValue RV = I->getKnownRValue(); 4811 assert(RV.isScalar()); // complex should always just be direct 4812 4813 llvm::Type *scalarType = RV.getScalarVal()->getType(); 4814 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType); 4815 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType); 4816 4817 // Materialize to a temporary. 4818 addr = CreateTempAlloca( 4819 RV.getScalarVal()->getType(), 4820 CharUnits::fromQuantity(std::max( 4821 (unsigned)layout->getAlignment().value(), scalarAlign)), 4822 "tmp", 4823 /*ArraySize=*/nullptr, &AllocaAddr); 4824 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer()); 4825 4826 Builder.CreateStore(RV.getScalarVal(), addr); 4827 } 4828 4829 addr = Builder.CreateElementBitCast(addr, coercionType); 4830 4831 unsigned IRArgPos = FirstIRArg; 4832 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4833 llvm::Type *eltType = coercionType->getElementType(i); 4834 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4835 Address eltAddr = Builder.CreateStructGEP(addr, i); 4836 llvm::Value *elt = Builder.CreateLoad(eltAddr); 4837 IRCallArgs[IRArgPos++] = elt; 4838 } 4839 assert(IRArgPos == FirstIRArg + NumIRArgs); 4840 4841 if (tempSize) { 4842 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer()); 4843 } 4844 4845 break; 4846 } 4847 4848 case ABIArgInfo::Expand: { 4849 unsigned IRArgPos = FirstIRArg; 4850 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos); 4851 assert(IRArgPos == FirstIRArg + NumIRArgs); 4852 break; 4853 } 4854 } 4855 } 4856 4857 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this); 4858 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer(); 4859 4860 // If we're using inalloca, set up that argument. 4861 if (ArgMemory.isValid()) { 4862 llvm::Value *Arg = ArgMemory.getPointer(); 4863 if (CallInfo.isVariadic()) { 4864 // When passing non-POD arguments by value to variadic functions, we will 4865 // end up with a variadic prototype and an inalloca call site. In such 4866 // cases, we can't do any parameter mismatch checks. Give up and bitcast 4867 // the callee. 4868 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace(); 4869 CalleePtr = 4870 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS)); 4871 } else { 4872 llvm::Type *LastParamTy = 4873 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1); 4874 if (Arg->getType() != LastParamTy) { 4875 #ifndef NDEBUG 4876 // Assert that these structs have equivalent element types. 4877 llvm::StructType *FullTy = CallInfo.getArgStruct(); 4878 llvm::StructType *DeclaredTy = cast<llvm::StructType>( 4879 cast<llvm::PointerType>(LastParamTy)->getElementType()); 4880 assert(DeclaredTy->getNumElements() == FullTy->getNumElements()); 4881 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(), 4882 DE = DeclaredTy->element_end(), 4883 FI = FullTy->element_begin(); 4884 DI != DE; ++DI, ++FI) 4885 assert(*DI == *FI); 4886 #endif 4887 Arg = Builder.CreateBitCast(Arg, LastParamTy); 4888 } 4889 } 4890 assert(IRFunctionArgs.hasInallocaArg()); 4891 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg; 4892 } 4893 4894 // 2. Prepare the function pointer. 4895 4896 // If the callee is a bitcast of a non-variadic function to have a 4897 // variadic function pointer type, check to see if we can remove the 4898 // bitcast. This comes up with unprototyped functions. 4899 // 4900 // This makes the IR nicer, but more importantly it ensures that we 4901 // can inline the function at -O0 if it is marked always_inline. 4902 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT, 4903 llvm::Value *Ptr) -> llvm::Function * { 4904 if (!CalleeFT->isVarArg()) 4905 return nullptr; 4906 4907 // Get underlying value if it's a bitcast 4908 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) { 4909 if (CE->getOpcode() == llvm::Instruction::BitCast) 4910 Ptr = CE->getOperand(0); 4911 } 4912 4913 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr); 4914 if (!OrigFn) 4915 return nullptr; 4916 4917 llvm::FunctionType *OrigFT = OrigFn->getFunctionType(); 4918 4919 // If the original type is variadic, or if any of the component types 4920 // disagree, we cannot remove the cast. 4921 if (OrigFT->isVarArg() || 4922 OrigFT->getNumParams() != CalleeFT->getNumParams() || 4923 OrigFT->getReturnType() != CalleeFT->getReturnType()) 4924 return nullptr; 4925 4926 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i) 4927 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i)) 4928 return nullptr; 4929 4930 return OrigFn; 4931 }; 4932 4933 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) { 4934 CalleePtr = OrigFn; 4935 IRFuncTy = OrigFn->getFunctionType(); 4936 } 4937 4938 // 3. Perform the actual call. 4939 4940 // Deactivate any cleanups that we're supposed to do immediately before 4941 // the call. 4942 if (!CallArgs.getCleanupsToDeactivate().empty()) 4943 deactivateArgCleanupsBeforeCall(*this, CallArgs); 4944 4945 // Assert that the arguments we computed match up. The IR verifier 4946 // will catch this, but this is a common enough source of problems 4947 // during IRGen changes that it's way better for debugging to catch 4948 // it ourselves here. 4949 #ifndef NDEBUG 4950 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()); 4951 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4952 // Inalloca argument can have different type. 4953 if (IRFunctionArgs.hasInallocaArg() && 4954 i == IRFunctionArgs.getInallocaArgNo()) 4955 continue; 4956 if (i < IRFuncTy->getNumParams()) 4957 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)); 4958 } 4959 #endif 4960 4961 // Update the largest vector width if any arguments have vector types. 4962 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4963 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType())) 4964 LargestVectorWidth = 4965 std::max((uint64_t)LargestVectorWidth, 4966 VT->getPrimitiveSizeInBits().getKnownMinSize()); 4967 } 4968 4969 // Compute the calling convention and attributes. 4970 unsigned CallingConv; 4971 llvm::AttributeList Attrs; 4972 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo, 4973 Callee.getAbstractInfo(), Attrs, CallingConv, 4974 /*AttrOnCallSite=*/true); 4975 4976 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 4977 if (FD->hasAttr<StrictFPAttr>()) 4978 // All calls within a strictfp function are marked strictfp 4979 Attrs = 4980 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4981 llvm::Attribute::StrictFP); 4982 4983 // Add nomerge attribute to the call-site if the callee function doesn't have 4984 // the attribute. 4985 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 4986 if (!FD->hasAttr<NoMergeAttr>() && InNoMergeAttributedStmt) 4987 Attrs = Attrs.addAttribute(getLLVMContext(), 4988 llvm::AttributeList::FunctionIndex, 4989 llvm::Attribute::NoMerge); 4990 4991 // Apply some call-site-specific attributes. 4992 // TODO: work this into building the attribute set. 4993 4994 // Apply always_inline to all calls within flatten functions. 4995 // FIXME: should this really take priority over __try, below? 4996 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() && 4997 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) { 4998 Attrs = 4999 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 5000 llvm::Attribute::AlwaysInline); 5001 } 5002 5003 // Disable inlining inside SEH __try blocks. 5004 if (isSEHTryScope()) { 5005 Attrs = 5006 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 5007 llvm::Attribute::NoInline); 5008 } 5009 5010 // Decide whether to use a call or an invoke. 5011 bool CannotThrow; 5012 if (currentFunctionUsesSEHTry()) { 5013 // SEH cares about asynchronous exceptions, so everything can "throw." 5014 CannotThrow = false; 5015 } else if (isCleanupPadScope() && 5016 EHPersonality::get(*this).isMSVCXXPersonality()) { 5017 // The MSVC++ personality will implicitly terminate the program if an 5018 // exception is thrown during a cleanup outside of a try/catch. 5019 // We don't need to model anything in IR to get this behavior. 5020 CannotThrow = true; 5021 } else { 5022 // Otherwise, nounwind call sites will never throw. 5023 CannotThrow = Attrs.hasFnAttribute(llvm::Attribute::NoUnwind); 5024 5025 if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr)) 5026 if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind)) 5027 CannotThrow = true; 5028 } 5029 5030 // If we made a temporary, be sure to clean up after ourselves. Note that we 5031 // can't depend on being inside of an ExprWithCleanups, so we need to manually 5032 // pop this cleanup later on. Being eager about this is OK, since this 5033 // temporary is 'invisible' outside of the callee. 5034 if (UnusedReturnSizePtr) 5035 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca, 5036 UnusedReturnSizePtr); 5037 5038 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); 5039 5040 SmallVector<llvm::OperandBundleDef, 1> BundleList = 5041 getBundlesForFunclet(CalleePtr); 5042 5043 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 5044 if (FD->hasAttr<StrictFPAttr>()) 5045 // All calls within a strictfp function are marked strictfp 5046 Attrs = 5047 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 5048 llvm::Attribute::StrictFP); 5049 5050 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl); 5051 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs); 5052 5053 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs); 5054 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs); 5055 5056 // Emit the actual call/invoke instruction. 5057 llvm::CallBase *CI; 5058 if (!InvokeDest) { 5059 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList); 5060 } else { 5061 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 5062 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs, 5063 BundleList); 5064 EmitBlock(Cont); 5065 } 5066 if (callOrInvoke) 5067 *callOrInvoke = CI; 5068 5069 // If this is within a function that has the guard(nocf) attribute and is an 5070 // indirect call, add the "guard_nocf" attribute to this call to indicate that 5071 // Control Flow Guard checks should not be added, even if the call is inlined. 5072 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) { 5073 if (const auto *A = FD->getAttr<CFGuardAttr>()) { 5074 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction()) 5075 Attrs = Attrs.addAttribute( 5076 getLLVMContext(), llvm::AttributeList::FunctionIndex, "guard_nocf"); 5077 } 5078 } 5079 5080 // Apply the attributes and calling convention. 5081 CI->setAttributes(Attrs); 5082 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 5083 5084 // Apply various metadata. 5085 5086 if (!CI->getType()->isVoidTy()) 5087 CI->setName("call"); 5088 5089 // Update largest vector width from the return type. 5090 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType())) 5091 LargestVectorWidth = 5092 std::max((uint64_t)LargestVectorWidth, 5093 VT->getPrimitiveSizeInBits().getKnownMinSize()); 5094 5095 // Insert instrumentation or attach profile metadata at indirect call sites. 5096 // For more details, see the comment before the definition of 5097 // IPVK_IndirectCallTarget in InstrProfData.inc. 5098 if (!CI->getCalledFunction()) 5099 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget, 5100 CI, CalleePtr); 5101 5102 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 5103 // optimizer it can aggressively ignore unwind edges. 5104 if (CGM.getLangOpts().ObjCAutoRefCount) 5105 AddObjCARCExceptionMetadata(CI); 5106 5107 // Suppress tail calls if requested. 5108 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) { 5109 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>()) 5110 Call->setTailCallKind(llvm::CallInst::TCK_NoTail); 5111 } 5112 5113 // Add metadata for calls to MSAllocator functions 5114 if (getDebugInfo() && TargetDecl && 5115 TargetDecl->hasAttr<MSAllocatorAttr>()) 5116 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc); 5117 5118 // 4. Finish the call. 5119 5120 // If the call doesn't return, finish the basic block and clear the 5121 // insertion point; this allows the rest of IRGen to discard 5122 // unreachable code. 5123 if (CI->doesNotReturn()) { 5124 if (UnusedReturnSizePtr) 5125 PopCleanupBlock(); 5126 5127 // Strip away the noreturn attribute to better diagnose unreachable UB. 5128 if (SanOpts.has(SanitizerKind::Unreachable)) { 5129 // Also remove from function since CallBase::hasFnAttr additionally checks 5130 // attributes of the called function. 5131 if (auto *F = CI->getCalledFunction()) 5132 F->removeFnAttr(llvm::Attribute::NoReturn); 5133 CI->removeAttribute(llvm::AttributeList::FunctionIndex, 5134 llvm::Attribute::NoReturn); 5135 5136 // Avoid incompatibility with ASan which relies on the `noreturn` 5137 // attribute to insert handler calls. 5138 if (SanOpts.hasOneOf(SanitizerKind::Address | 5139 SanitizerKind::KernelAddress)) { 5140 SanitizerScope SanScope(this); 5141 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder); 5142 Builder.SetInsertPoint(CI); 5143 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 5144 llvm::FunctionCallee Fn = 5145 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return"); 5146 EmitNounwindRuntimeCall(Fn); 5147 } 5148 } 5149 5150 EmitUnreachable(Loc); 5151 Builder.ClearInsertionPoint(); 5152 5153 // FIXME: For now, emit a dummy basic block because expr emitters in 5154 // generally are not ready to handle emitting expressions at unreachable 5155 // points. 5156 EnsureInsertPoint(); 5157 5158 // Return a reasonable RValue. 5159 return GetUndefRValue(RetTy); 5160 } 5161 5162 // Perform the swifterror writeback. 5163 if (swiftErrorTemp.isValid()) { 5164 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp); 5165 Builder.CreateStore(errorResult, swiftErrorArg); 5166 } 5167 5168 // Emit any call-associated writebacks immediately. Arguably this 5169 // should happen after any return-value munging. 5170 if (CallArgs.hasWritebacks()) 5171 emitWritebacks(*this, CallArgs); 5172 5173 // The stack cleanup for inalloca arguments has to run out of the normal 5174 // lexical order, so deactivate it and run it manually here. 5175 CallArgs.freeArgumentMemory(*this); 5176 5177 // Extract the return value. 5178 RValue Ret = [&] { 5179 switch (RetAI.getKind()) { 5180 case ABIArgInfo::CoerceAndExpand: { 5181 auto coercionType = RetAI.getCoerceAndExpandType(); 5182 5183 Address addr = SRetPtr; 5184 addr = Builder.CreateElementBitCast(addr, coercionType); 5185 5186 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType()); 5187 bool requiresExtract = isa<llvm::StructType>(CI->getType()); 5188 5189 unsigned unpaddedIndex = 0; 5190 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 5191 llvm::Type *eltType = coercionType->getElementType(i); 5192 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 5193 Address eltAddr = Builder.CreateStructGEP(addr, i); 5194 llvm::Value *elt = CI; 5195 if (requiresExtract) 5196 elt = Builder.CreateExtractValue(elt, unpaddedIndex++); 5197 else 5198 assert(unpaddedIndex == 0); 5199 Builder.CreateStore(elt, eltAddr); 5200 } 5201 // FALLTHROUGH 5202 LLVM_FALLTHROUGH; 5203 } 5204 5205 case ABIArgInfo::InAlloca: 5206 case ABIArgInfo::Indirect: { 5207 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); 5208 if (UnusedReturnSizePtr) 5209 PopCleanupBlock(); 5210 return ret; 5211 } 5212 5213 case ABIArgInfo::Ignore: 5214 // If we are ignoring an argument that had a result, make sure to 5215 // construct the appropriate return value for our caller. 5216 return GetUndefRValue(RetTy); 5217 5218 case ABIArgInfo::Extend: 5219 case ABIArgInfo::Direct: { 5220 llvm::Type *RetIRTy = ConvertType(RetTy); 5221 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 5222 switch (getEvaluationKind(RetTy)) { 5223 case TEK_Complex: { 5224 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 5225 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 5226 return RValue::getComplex(std::make_pair(Real, Imag)); 5227 } 5228 case TEK_Aggregate: { 5229 Address DestPtr = ReturnValue.getValue(); 5230 bool DestIsVolatile = ReturnValue.isVolatile(); 5231 5232 if (!DestPtr.isValid()) { 5233 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 5234 DestIsVolatile = false; 5235 } 5236 EmitAggregateStore(CI, DestPtr, DestIsVolatile); 5237 return RValue::getAggregate(DestPtr); 5238 } 5239 case TEK_Scalar: { 5240 // If the argument doesn't match, perform a bitcast to coerce it. This 5241 // can happen due to trivial type mismatches. 5242 llvm::Value *V = CI; 5243 if (V->getType() != RetIRTy) 5244 V = Builder.CreateBitCast(V, RetIRTy); 5245 return RValue::get(V); 5246 } 5247 } 5248 llvm_unreachable("bad evaluation kind"); 5249 } 5250 5251 Address DestPtr = ReturnValue.getValue(); 5252 bool DestIsVolatile = ReturnValue.isVolatile(); 5253 5254 if (!DestPtr.isValid()) { 5255 DestPtr = CreateMemTemp(RetTy, "coerce"); 5256 DestIsVolatile = false; 5257 } 5258 5259 // If the value is offset in memory, apply the offset now. 5260 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI); 5261 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 5262 5263 return convertTempToRValue(DestPtr, RetTy, SourceLocation()); 5264 } 5265 5266 case ABIArgInfo::Expand: 5267 case ABIArgInfo::IndirectAliased: 5268 llvm_unreachable("Invalid ABI kind for return argument"); 5269 } 5270 5271 llvm_unreachable("Unhandled ABIArgInfo::Kind"); 5272 } (); 5273 5274 // Emit the assume_aligned check on the return value. 5275 if (Ret.isScalar() && TargetDecl) { 5276 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret); 5277 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret); 5278 } 5279 5280 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though 5281 // we can't use the full cleanup mechanism. 5282 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall) 5283 LifetimeEnd.Emit(*this, /*Flags=*/{}); 5284 5285 if (!ReturnValue.isExternallyDestructed() && 5286 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct) 5287 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(), 5288 RetTy); 5289 5290 return Ret; 5291 } 5292 5293 CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const { 5294 if (isVirtual()) { 5295 const CallExpr *CE = getVirtualCallExpr(); 5296 return CGF.CGM.getCXXABI().getVirtualFunctionPointer( 5297 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(), 5298 CE ? CE->getBeginLoc() : SourceLocation()); 5299 } 5300 5301 return *this; 5302 } 5303 5304 /* VarArg handling */ 5305 5306 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) { 5307 VAListAddr = VE->isMicrosoftABI() 5308 ? EmitMSVAListRef(VE->getSubExpr()) 5309 : EmitVAListRef(VE->getSubExpr()); 5310 QualType Ty = VE->getType(); 5311 if (VE->isMicrosoftABI()) 5312 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty); 5313 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty); 5314 } 5315