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