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.getType()->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.getType()->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.getType()->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 ArgAttrs[IRFunctionArgs.getSRetArgNo()] = 2088 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs); 2089 } 2090 2091 // Attach attributes to inalloca argument. 2092 if (IRFunctionArgs.hasInallocaArg()) { 2093 llvm::AttrBuilder Attrs; 2094 Attrs.addAttribute(llvm::Attribute::InAlloca); 2095 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] = 2096 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2097 } 2098 2099 unsigned ArgNo = 0; 2100 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(), 2101 E = FI.arg_end(); 2102 I != E; ++I, ++ArgNo) { 2103 QualType ParamType = I->type; 2104 const ABIArgInfo &AI = I->info; 2105 llvm::AttrBuilder Attrs; 2106 2107 // Add attribute for padding argument, if necessary. 2108 if (IRFunctionArgs.hasPaddingArg(ArgNo)) { 2109 if (AI.getPaddingInReg()) { 2110 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 2111 llvm::AttributeSet::get( 2112 getLLVMContext(), 2113 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg)); 2114 } 2115 } 2116 2117 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 2118 // have the corresponding parameter variable. It doesn't make 2119 // sense to do it here because parameters are so messed up. 2120 switch (AI.getKind()) { 2121 case ABIArgInfo::Extend: 2122 if (AI.isSignExt()) 2123 Attrs.addAttribute(llvm::Attribute::SExt); 2124 else 2125 Attrs.addAttribute(llvm::Attribute::ZExt); 2126 LLVM_FALLTHROUGH; 2127 case ABIArgInfo::Direct: 2128 if (ArgNo == 0 && FI.isChainCall()) 2129 Attrs.addAttribute(llvm::Attribute::Nest); 2130 else if (AI.getInReg()) 2131 Attrs.addAttribute(llvm::Attribute::InReg); 2132 break; 2133 2134 case ABIArgInfo::Indirect: { 2135 if (AI.getInReg()) 2136 Attrs.addAttribute(llvm::Attribute::InReg); 2137 2138 if (AI.getIndirectByVal()) 2139 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType)); 2140 2141 CharUnits Align = AI.getIndirectAlign(); 2142 2143 // In a byval argument, it is important that the required 2144 // alignment of the type is honored, as LLVM might be creating a 2145 // *new* stack object, and needs to know what alignment to give 2146 // it. (Sometimes it can deduce a sensible alignment on its own, 2147 // but not if clang decides it must emit a packed struct, or the 2148 // user specifies increased alignment requirements.) 2149 // 2150 // This is different from indirect *not* byval, where the object 2151 // exists already, and the align attribute is purely 2152 // informative. 2153 assert(!Align.isZero()); 2154 2155 // For now, only add this when we have a byval argument. 2156 // TODO: be less lazy about updating test cases. 2157 if (AI.getIndirectByVal()) 2158 Attrs.addAlignmentAttr(Align.getQuantity()); 2159 2160 // byval disables readnone and readonly. 2161 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2162 .removeAttribute(llvm::Attribute::ReadNone); 2163 break; 2164 } 2165 case ABIArgInfo::Ignore: 2166 case ABIArgInfo::Expand: 2167 case ABIArgInfo::CoerceAndExpand: 2168 break; 2169 2170 case ABIArgInfo::InAlloca: 2171 // inalloca disables readnone and readonly. 2172 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2173 .removeAttribute(llvm::Attribute::ReadNone); 2174 continue; 2175 } 2176 2177 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) { 2178 QualType PTy = RefTy->getPointeeType(); 2179 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 2180 Attrs.addDereferenceableAttr( 2181 getMinimumObjectSize(PTy).getQuantity()); 2182 else if (getContext().getTargetAddressSpace(PTy) == 0 && 2183 !CodeGenOpts.NullPointerIsValid) 2184 Attrs.addAttribute(llvm::Attribute::NonNull); 2185 } 2186 2187 switch (FI.getExtParameterInfo(ArgNo).getABI()) { 2188 case ParameterABI::Ordinary: 2189 break; 2190 2191 case ParameterABI::SwiftIndirectResult: { 2192 // Add 'sret' if we haven't already used it for something, but 2193 // only if the result is void. 2194 if (!hasUsedSRet && RetTy->isVoidType()) { 2195 Attrs.addAttribute(llvm::Attribute::StructRet); 2196 hasUsedSRet = true; 2197 } 2198 2199 // Add 'noalias' in either case. 2200 Attrs.addAttribute(llvm::Attribute::NoAlias); 2201 2202 // Add 'dereferenceable' and 'alignment'. 2203 auto PTy = ParamType->getPointeeType(); 2204 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) { 2205 auto info = getContext().getTypeInfoInChars(PTy); 2206 Attrs.addDereferenceableAttr(info.first.getQuantity()); 2207 Attrs.addAttribute(llvm::Attribute::getWithAlignment( 2208 getLLVMContext(), info.second.getAsAlign())); 2209 } 2210 break; 2211 } 2212 2213 case ParameterABI::SwiftErrorResult: 2214 Attrs.addAttribute(llvm::Attribute::SwiftError); 2215 break; 2216 2217 case ParameterABI::SwiftContext: 2218 Attrs.addAttribute(llvm::Attribute::SwiftSelf); 2219 break; 2220 } 2221 2222 if (FI.getExtParameterInfo(ArgNo).isNoEscape()) 2223 Attrs.addAttribute(llvm::Attribute::NoCapture); 2224 2225 if (Attrs.hasAttributes()) { 2226 unsigned FirstIRArg, NumIRArgs; 2227 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2228 for (unsigned i = 0; i < NumIRArgs; i++) 2229 ArgAttrs[FirstIRArg + i] = 2230 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2231 } 2232 } 2233 assert(ArgNo == FI.arg_size()); 2234 2235 AttrList = llvm::AttributeList::get( 2236 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs), 2237 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs); 2238 } 2239 2240 /// An argument came in as a promoted argument; demote it back to its 2241 /// declared type. 2242 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF, 2243 const VarDecl *var, 2244 llvm::Value *value) { 2245 llvm::Type *varType = CGF.ConvertType(var->getType()); 2246 2247 // This can happen with promotions that actually don't change the 2248 // underlying type, like the enum promotions. 2249 if (value->getType() == varType) return value; 2250 2251 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) 2252 && "unexpected promotion type"); 2253 2254 if (isa<llvm::IntegerType>(varType)) 2255 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote"); 2256 2257 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote"); 2258 } 2259 2260 /// Returns the attribute (either parameter attribute, or function 2261 /// attribute), which declares argument ArgNo to be non-null. 2262 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, 2263 QualType ArgType, unsigned ArgNo) { 2264 // FIXME: __attribute__((nonnull)) can also be applied to: 2265 // - references to pointers, where the pointee is known to be 2266 // nonnull (apparently a Clang extension) 2267 // - transparent unions containing pointers 2268 // In the former case, LLVM IR cannot represent the constraint. In 2269 // the latter case, we have no guarantee that the transparent union 2270 // is in fact passed as a pointer. 2271 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType()) 2272 return nullptr; 2273 // First, check attribute on parameter itself. 2274 if (PVD) { 2275 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>()) 2276 return ParmNNAttr; 2277 } 2278 // Check function attributes. 2279 if (!FD) 2280 return nullptr; 2281 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) { 2282 if (NNAttr->isNonNull(ArgNo)) 2283 return NNAttr; 2284 } 2285 return nullptr; 2286 } 2287 2288 namespace { 2289 struct CopyBackSwiftError final : EHScopeStack::Cleanup { 2290 Address Temp; 2291 Address Arg; 2292 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {} 2293 void Emit(CodeGenFunction &CGF, Flags flags) override { 2294 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp); 2295 CGF.Builder.CreateStore(errorValue, Arg); 2296 } 2297 }; 2298 } 2299 2300 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 2301 llvm::Function *Fn, 2302 const FunctionArgList &Args) { 2303 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) 2304 // Naked functions don't have prologues. 2305 return; 2306 2307 // If this is an implicit-return-zero function, go ahead and 2308 // initialize the return value. TODO: it might be nice to have 2309 // a more general mechanism for this that didn't require synthesized 2310 // return statements. 2311 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) { 2312 if (FD->hasImplicitReturnZero()) { 2313 QualType RetTy = FD->getReturnType().getUnqualifiedType(); 2314 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 2315 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 2316 Builder.CreateStore(Zero, ReturnValue); 2317 } 2318 } 2319 2320 // FIXME: We no longer need the types from FunctionArgList; lift up and 2321 // simplify. 2322 2323 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI); 2324 // Flattened function arguments. 2325 SmallVector<llvm::Value *, 16> FnArgs; 2326 FnArgs.reserve(IRFunctionArgs.totalIRArgs()); 2327 for (auto &Arg : Fn->args()) { 2328 FnArgs.push_back(&Arg); 2329 } 2330 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs()); 2331 2332 // If we're using inalloca, all the memory arguments are GEPs off of the last 2333 // parameter, which is a pointer to the complete memory area. 2334 Address ArgStruct = Address::invalid(); 2335 if (IRFunctionArgs.hasInallocaArg()) { 2336 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()], 2337 FI.getArgStructAlignment()); 2338 2339 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo()); 2340 } 2341 2342 // Name the struct return parameter. 2343 if (IRFunctionArgs.hasSRetArg()) { 2344 auto AI = cast<llvm::Argument>(FnArgs[IRFunctionArgs.getSRetArgNo()]); 2345 AI->setName("agg.result"); 2346 AI->addAttr(llvm::Attribute::NoAlias); 2347 } 2348 2349 // Track if we received the parameter as a pointer (indirect, byval, or 2350 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it 2351 // into a local alloca for us. 2352 SmallVector<ParamValue, 16> ArgVals; 2353 ArgVals.reserve(Args.size()); 2354 2355 // Create a pointer value for every parameter declaration. This usually 2356 // entails copying one or more LLVM IR arguments into an alloca. Don't push 2357 // any cleanups or do anything that might unwind. We do that separately, so 2358 // we can push the cleanups in the correct order for the ABI. 2359 assert(FI.arg_size() == Args.size() && 2360 "Mismatch between function signature & arguments."); 2361 unsigned ArgNo = 0; 2362 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 2363 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 2364 i != e; ++i, ++info_it, ++ArgNo) { 2365 const VarDecl *Arg = *i; 2366 const ABIArgInfo &ArgI = info_it->info; 2367 2368 bool isPromoted = 2369 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted(); 2370 // We are converting from ABIArgInfo type to VarDecl type directly, unless 2371 // the parameter is promoted. In this case we convert to 2372 // CGFunctionInfo::ArgInfo type with subsequent argument demotion. 2373 QualType Ty = isPromoted ? info_it->type : Arg->getType(); 2374 assert(hasScalarEvaluationKind(Ty) == 2375 hasScalarEvaluationKind(Arg->getType())); 2376 2377 unsigned FirstIRArg, NumIRArgs; 2378 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2379 2380 switch (ArgI.getKind()) { 2381 case ABIArgInfo::InAlloca: { 2382 assert(NumIRArgs == 0); 2383 auto FieldIndex = ArgI.getInAllocaFieldIndex(); 2384 Address V = 2385 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName()); 2386 if (ArgI.getInAllocaIndirect()) 2387 V = Address(Builder.CreateLoad(V), 2388 getContext().getTypeAlignInChars(Ty)); 2389 ArgVals.push_back(ParamValue::forIndirect(V)); 2390 break; 2391 } 2392 2393 case ABIArgInfo::Indirect: { 2394 assert(NumIRArgs == 1); 2395 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign()); 2396 2397 if (!hasScalarEvaluationKind(Ty)) { 2398 // Aggregates and complex variables are accessed by reference. All we 2399 // need to do is realign the value, if requested. 2400 Address V = ParamAddr; 2401 if (ArgI.getIndirectRealign()) { 2402 Address AlignedTemp = CreateMemTemp(Ty, "coerce"); 2403 2404 // Copy from the incoming argument pointer to the temporary with the 2405 // appropriate alignment. 2406 // 2407 // FIXME: We should have a common utility for generating an aggregate 2408 // copy. 2409 CharUnits Size = getContext().getTypeSizeInChars(Ty); 2410 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()); 2411 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy); 2412 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy); 2413 Builder.CreateMemCpy(Dst, Src, SizeVal, false); 2414 V = AlignedTemp; 2415 } 2416 ArgVals.push_back(ParamValue::forIndirect(V)); 2417 } else { 2418 // Load scalar value from indirect argument. 2419 llvm::Value *V = 2420 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc()); 2421 2422 if (isPromoted) 2423 V = emitArgumentDemotion(*this, Arg, V); 2424 ArgVals.push_back(ParamValue::forDirect(V)); 2425 } 2426 break; 2427 } 2428 2429 case ABIArgInfo::Extend: 2430 case ABIArgInfo::Direct: { 2431 2432 // If we have the trivial case, handle it with no muss and fuss. 2433 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) && 2434 ArgI.getCoerceToType() == ConvertType(Ty) && 2435 ArgI.getDirectOffset() == 0) { 2436 assert(NumIRArgs == 1); 2437 llvm::Value *V = FnArgs[FirstIRArg]; 2438 auto AI = cast<llvm::Argument>(V); 2439 2440 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) { 2441 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(), 2442 PVD->getFunctionScopeIndex()) && 2443 !CGM.getCodeGenOpts().NullPointerIsValid) 2444 AI->addAttr(llvm::Attribute::NonNull); 2445 2446 QualType OTy = PVD->getOriginalType(); 2447 if (const auto *ArrTy = 2448 getContext().getAsConstantArrayType(OTy)) { 2449 // A C99 array parameter declaration with the static keyword also 2450 // indicates dereferenceability, and if the size is constant we can 2451 // use the dereferenceable attribute (which requires the size in 2452 // bytes). 2453 if (ArrTy->getSizeModifier() == ArrayType::Static) { 2454 QualType ETy = ArrTy->getElementType(); 2455 uint64_t ArrSize = ArrTy->getSize().getZExtValue(); 2456 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() && 2457 ArrSize) { 2458 llvm::AttrBuilder Attrs; 2459 Attrs.addDereferenceableAttr( 2460 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize); 2461 AI->addAttrs(Attrs); 2462 } else if (getContext().getTargetAddressSpace(ETy) == 0 && 2463 !CGM.getCodeGenOpts().NullPointerIsValid) { 2464 AI->addAttr(llvm::Attribute::NonNull); 2465 } 2466 } 2467 } else if (const auto *ArrTy = 2468 getContext().getAsVariableArrayType(OTy)) { 2469 // For C99 VLAs with the static keyword, we don't know the size so 2470 // we can't use the dereferenceable attribute, but in addrspace(0) 2471 // we know that it must be nonnull. 2472 if (ArrTy->getSizeModifier() == VariableArrayType::Static && 2473 !getContext().getTargetAddressSpace(ArrTy->getElementType()) && 2474 !CGM.getCodeGenOpts().NullPointerIsValid) 2475 AI->addAttr(llvm::Attribute::NonNull); 2476 } 2477 2478 const auto *AVAttr = PVD->getAttr<AlignValueAttr>(); 2479 if (!AVAttr) 2480 if (const auto *TOTy = dyn_cast<TypedefType>(OTy)) 2481 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>(); 2482 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) { 2483 // If alignment-assumption sanitizer is enabled, we do *not* add 2484 // alignment attribute here, but emit normal alignment assumption, 2485 // so the UBSAN check could function. 2486 llvm::Value *AlignmentValue = 2487 EmitScalarExpr(AVAttr->getAlignment()); 2488 llvm::ConstantInt *AlignmentCI = 2489 cast<llvm::ConstantInt>(AlignmentValue); 2490 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(llvm::MaybeAlign( 2491 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)))); 2492 } 2493 } 2494 2495 if (Arg->getType().isRestrictQualified()) 2496 AI->addAttr(llvm::Attribute::NoAlias); 2497 2498 // LLVM expects swifterror parameters to be used in very restricted 2499 // ways. Copy the value into a less-restricted temporary. 2500 if (FI.getExtParameterInfo(ArgNo).getABI() 2501 == ParameterABI::SwiftErrorResult) { 2502 QualType pointeeTy = Ty->getPointeeType(); 2503 assert(pointeeTy->isPointerType()); 2504 Address temp = 2505 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 2506 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy)); 2507 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg); 2508 Builder.CreateStore(incomingErrorValue, temp); 2509 V = temp.getPointer(); 2510 2511 // Push a cleanup to copy the value back at the end of the function. 2512 // The convention does not guarantee that the value will be written 2513 // back if the function exits with an unwind exception. 2514 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg); 2515 } 2516 2517 // Ensure the argument is the correct type. 2518 if (V->getType() != ArgI.getCoerceToType()) 2519 V = Builder.CreateBitCast(V, ArgI.getCoerceToType()); 2520 2521 if (isPromoted) 2522 V = emitArgumentDemotion(*this, Arg, V); 2523 2524 // Because of merging of function types from multiple decls it is 2525 // possible for the type of an argument to not match the corresponding 2526 // type in the function type. Since we are codegening the callee 2527 // in here, add a cast to the argument type. 2528 llvm::Type *LTy = ConvertType(Arg->getType()); 2529 if (V->getType() != LTy) 2530 V = Builder.CreateBitCast(V, LTy); 2531 2532 ArgVals.push_back(ParamValue::forDirect(V)); 2533 break; 2534 } 2535 2536 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg), 2537 Arg->getName()); 2538 2539 // Pointer to store into. 2540 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI); 2541 2542 // Fast-isel and the optimizer generally like scalar values better than 2543 // FCAs, so we flatten them if this is safe to do for this argument. 2544 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType()); 2545 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy && 2546 STy->getNumElements() > 1) { 2547 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy); 2548 llvm::Type *DstTy = Ptr.getElementType(); 2549 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy); 2550 2551 Address AddrToStoreInto = Address::invalid(); 2552 if (SrcSize <= DstSize) { 2553 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy); 2554 } else { 2555 AddrToStoreInto = 2556 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce"); 2557 } 2558 2559 assert(STy->getNumElements() == NumIRArgs); 2560 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2561 auto AI = FnArgs[FirstIRArg + i]; 2562 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 2563 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i); 2564 Builder.CreateStore(AI, EltPtr); 2565 } 2566 2567 if (SrcSize > DstSize) { 2568 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize); 2569 } 2570 2571 } else { 2572 // Simple case, just do a coerced store of the argument into the alloca. 2573 assert(NumIRArgs == 1); 2574 auto AI = FnArgs[FirstIRArg]; 2575 AI->setName(Arg->getName() + ".coerce"); 2576 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this); 2577 } 2578 2579 // Match to what EmitParmDecl is expecting for this type. 2580 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) { 2581 llvm::Value *V = 2582 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc()); 2583 if (isPromoted) 2584 V = emitArgumentDemotion(*this, Arg, V); 2585 ArgVals.push_back(ParamValue::forDirect(V)); 2586 } else { 2587 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2588 } 2589 break; 2590 } 2591 2592 case ABIArgInfo::CoerceAndExpand: { 2593 // Reconstruct into a temporary. 2594 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2595 ArgVals.push_back(ParamValue::forIndirect(alloca)); 2596 2597 auto coercionType = ArgI.getCoerceAndExpandType(); 2598 alloca = Builder.CreateElementBitCast(alloca, coercionType); 2599 2600 unsigned argIndex = FirstIRArg; 2601 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 2602 llvm::Type *eltType = coercionType->getElementType(i); 2603 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) 2604 continue; 2605 2606 auto eltAddr = Builder.CreateStructGEP(alloca, i); 2607 auto elt = FnArgs[argIndex++]; 2608 Builder.CreateStore(elt, eltAddr); 2609 } 2610 assert(argIndex == FirstIRArg + NumIRArgs); 2611 break; 2612 } 2613 2614 case ABIArgInfo::Expand: { 2615 // If this structure was expanded into multiple arguments then 2616 // we need to create a temporary and reconstruct it from the 2617 // arguments. 2618 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2619 LValue LV = MakeAddrLValue(Alloca, Ty); 2620 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2621 2622 auto FnArgIter = FnArgs.begin() + FirstIRArg; 2623 ExpandTypeFromArgs(Ty, LV, FnArgIter); 2624 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs); 2625 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) { 2626 auto AI = FnArgs[FirstIRArg + i]; 2627 AI->setName(Arg->getName() + "." + Twine(i)); 2628 } 2629 break; 2630 } 2631 2632 case ABIArgInfo::Ignore: 2633 assert(NumIRArgs == 0); 2634 // Initialize the local variable appropriately. 2635 if (!hasScalarEvaluationKind(Ty)) { 2636 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty))); 2637 } else { 2638 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType())); 2639 ArgVals.push_back(ParamValue::forDirect(U)); 2640 } 2641 break; 2642 } 2643 } 2644 2645 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2646 for (int I = Args.size() - 1; I >= 0; --I) 2647 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2648 } else { 2649 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2650 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2651 } 2652 } 2653 2654 static void eraseUnusedBitCasts(llvm::Instruction *insn) { 2655 while (insn->use_empty()) { 2656 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn); 2657 if (!bitcast) return; 2658 2659 // This is "safe" because we would have used a ConstantExpr otherwise. 2660 insn = cast<llvm::Instruction>(bitcast->getOperand(0)); 2661 bitcast->eraseFromParent(); 2662 } 2663 } 2664 2665 /// Try to emit a fused autorelease of a return result. 2666 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, 2667 llvm::Value *result) { 2668 // We must be immediately followed the cast. 2669 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock(); 2670 if (BB->empty()) return nullptr; 2671 if (&BB->back() != result) return nullptr; 2672 2673 llvm::Type *resultType = result->getType(); 2674 2675 // result is in a BasicBlock and is therefore an Instruction. 2676 llvm::Instruction *generator = cast<llvm::Instruction>(result); 2677 2678 SmallVector<llvm::Instruction *, 4> InstsToKill; 2679 2680 // Look for: 2681 // %generator = bitcast %type1* %generator2 to %type2* 2682 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) { 2683 // We would have emitted this as a constant if the operand weren't 2684 // an Instruction. 2685 generator = cast<llvm::Instruction>(bitcast->getOperand(0)); 2686 2687 // Require the generator to be immediately followed by the cast. 2688 if (generator->getNextNode() != bitcast) 2689 return nullptr; 2690 2691 InstsToKill.push_back(bitcast); 2692 } 2693 2694 // Look for: 2695 // %generator = call i8* @objc_retain(i8* %originalResult) 2696 // or 2697 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult) 2698 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator); 2699 if (!call) return nullptr; 2700 2701 bool doRetainAutorelease; 2702 2703 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) { 2704 doRetainAutorelease = true; 2705 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints() 2706 .objc_retainAutoreleasedReturnValue) { 2707 doRetainAutorelease = false; 2708 2709 // If we emitted an assembly marker for this call (and the 2710 // ARCEntrypoints field should have been set if so), go looking 2711 // for that call. If we can't find it, we can't do this 2712 // optimization. But it should always be the immediately previous 2713 // instruction, unless we needed bitcasts around the call. 2714 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) { 2715 llvm::Instruction *prev = call->getPrevNode(); 2716 assert(prev); 2717 if (isa<llvm::BitCastInst>(prev)) { 2718 prev = prev->getPrevNode(); 2719 assert(prev); 2720 } 2721 assert(isa<llvm::CallInst>(prev)); 2722 assert(cast<llvm::CallInst>(prev)->getCalledValue() == 2723 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker); 2724 InstsToKill.push_back(prev); 2725 } 2726 } else { 2727 return nullptr; 2728 } 2729 2730 result = call->getArgOperand(0); 2731 InstsToKill.push_back(call); 2732 2733 // Keep killing bitcasts, for sanity. Note that we no longer care 2734 // about precise ordering as long as there's exactly one use. 2735 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) { 2736 if (!bitcast->hasOneUse()) break; 2737 InstsToKill.push_back(bitcast); 2738 result = bitcast->getOperand(0); 2739 } 2740 2741 // Delete all the unnecessary instructions, from latest to earliest. 2742 for (auto *I : InstsToKill) 2743 I->eraseFromParent(); 2744 2745 // Do the fused retain/autorelease if we were asked to. 2746 if (doRetainAutorelease) 2747 result = CGF.EmitARCRetainAutoreleaseReturnValue(result); 2748 2749 // Cast back to the result type. 2750 return CGF.Builder.CreateBitCast(result, resultType); 2751 } 2752 2753 /// If this is a +1 of the value of an immutable 'self', remove it. 2754 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, 2755 llvm::Value *result) { 2756 // This is only applicable to a method with an immutable 'self'. 2757 const ObjCMethodDecl *method = 2758 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl); 2759 if (!method) return nullptr; 2760 const VarDecl *self = method->getSelfDecl(); 2761 if (!self->getType().isConstQualified()) return nullptr; 2762 2763 // Look for a retain call. 2764 llvm::CallInst *retainCall = 2765 dyn_cast<llvm::CallInst>(result->stripPointerCasts()); 2766 if (!retainCall || 2767 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain) 2768 return nullptr; 2769 2770 // Look for an ordinary load of 'self'. 2771 llvm::Value *retainedValue = retainCall->getArgOperand(0); 2772 llvm::LoadInst *load = 2773 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); 2774 if (!load || load->isAtomic() || load->isVolatile() || 2775 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) 2776 return nullptr; 2777 2778 // Okay! Burn it all down. This relies for correctness on the 2779 // assumption that the retain is emitted as part of the return and 2780 // that thereafter everything is used "linearly". 2781 llvm::Type *resultType = result->getType(); 2782 eraseUnusedBitCasts(cast<llvm::Instruction>(result)); 2783 assert(retainCall->use_empty()); 2784 retainCall->eraseFromParent(); 2785 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue)); 2786 2787 return CGF.Builder.CreateBitCast(load, resultType); 2788 } 2789 2790 /// Emit an ARC autorelease of the result of a function. 2791 /// 2792 /// \return the value to actually return from the function 2793 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF, 2794 llvm::Value *result) { 2795 // If we're returning 'self', kill the initial retain. This is a 2796 // heuristic attempt to "encourage correctness" in the really unfortunate 2797 // case where we have a return of self during a dealloc and we desperately 2798 // need to avoid the possible autorelease. 2799 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result)) 2800 return self; 2801 2802 // At -O0, try to emit a fused retain/autorelease. 2803 if (CGF.shouldUseFusedARCCalls()) 2804 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result)) 2805 return fused; 2806 2807 return CGF.EmitARCAutoreleaseReturnValue(result); 2808 } 2809 2810 /// Heuristically search for a dominating store to the return-value slot. 2811 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) { 2812 // Check if a User is a store which pointerOperand is the ReturnValue. 2813 // We are looking for stores to the ReturnValue, not for stores of the 2814 // ReturnValue to some other location. 2815 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * { 2816 auto *SI = dyn_cast<llvm::StoreInst>(U); 2817 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer()) 2818 return nullptr; 2819 // These aren't actually possible for non-coerced returns, and we 2820 // only care about non-coerced returns on this code path. 2821 assert(!SI->isAtomic() && !SI->isVolatile()); 2822 return SI; 2823 }; 2824 // If there are multiple uses of the return-value slot, just check 2825 // for something immediately preceding the IP. Sometimes this can 2826 // happen with how we generate implicit-returns; it can also happen 2827 // with noreturn cleanups. 2828 if (!CGF.ReturnValue.getPointer()->hasOneUse()) { 2829 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2830 if (IP->empty()) return nullptr; 2831 llvm::Instruction *I = &IP->back(); 2832 2833 // Skip lifetime markers 2834 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(), 2835 IE = IP->rend(); 2836 II != IE; ++II) { 2837 if (llvm::IntrinsicInst *Intrinsic = 2838 dyn_cast<llvm::IntrinsicInst>(&*II)) { 2839 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) { 2840 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1); 2841 ++II; 2842 if (II == IE) 2843 break; 2844 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II)) 2845 continue; 2846 } 2847 } 2848 I = &*II; 2849 break; 2850 } 2851 2852 return GetStoreIfValid(I); 2853 } 2854 2855 llvm::StoreInst *store = 2856 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back()); 2857 if (!store) return nullptr; 2858 2859 // Now do a first-and-dirty dominance check: just walk up the 2860 // single-predecessors chain from the current insertion point. 2861 llvm::BasicBlock *StoreBB = store->getParent(); 2862 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2863 while (IP != StoreBB) { 2864 if (!(IP = IP->getSinglePredecessor())) 2865 return nullptr; 2866 } 2867 2868 // Okay, the store's basic block dominates the insertion point; we 2869 // can do our thing. 2870 return store; 2871 } 2872 2873 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 2874 bool EmitRetDbgLoc, 2875 SourceLocation EndLoc) { 2876 if (FI.isNoReturn()) { 2877 // Noreturn functions don't return. 2878 EmitUnreachable(EndLoc); 2879 return; 2880 } 2881 2882 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) { 2883 // Naked functions don't have epilogues. 2884 Builder.CreateUnreachable(); 2885 return; 2886 } 2887 2888 // Functions with no result always return void. 2889 if (!ReturnValue.isValid()) { 2890 Builder.CreateRetVoid(); 2891 return; 2892 } 2893 2894 llvm::DebugLoc RetDbgLoc; 2895 llvm::Value *RV = nullptr; 2896 QualType RetTy = FI.getReturnType(); 2897 const ABIArgInfo &RetAI = FI.getReturnInfo(); 2898 2899 switch (RetAI.getKind()) { 2900 case ABIArgInfo::InAlloca: 2901 // Aggregrates get evaluated directly into the destination. Sometimes we 2902 // need to return the sret value in a register, though. 2903 assert(hasAggregateEvaluationKind(RetTy)); 2904 if (RetAI.getInAllocaSRet()) { 2905 llvm::Function::arg_iterator EI = CurFn->arg_end(); 2906 --EI; 2907 llvm::Value *ArgStruct = &*EI; 2908 llvm::Value *SRet = Builder.CreateStructGEP( 2909 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex()); 2910 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret"); 2911 } 2912 break; 2913 2914 case ABIArgInfo::Indirect: { 2915 auto AI = CurFn->arg_begin(); 2916 if (RetAI.isSRetAfterThis()) 2917 ++AI; 2918 switch (getEvaluationKind(RetTy)) { 2919 case TEK_Complex: { 2920 ComplexPairTy RT = 2921 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc); 2922 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy), 2923 /*isInit*/ true); 2924 break; 2925 } 2926 case TEK_Aggregate: 2927 // Do nothing; aggregrates get evaluated directly into the destination. 2928 break; 2929 case TEK_Scalar: 2930 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), 2931 MakeNaturalAlignAddrLValue(&*AI, RetTy), 2932 /*isInit*/ true); 2933 break; 2934 } 2935 break; 2936 } 2937 2938 case ABIArgInfo::Extend: 2939 case ABIArgInfo::Direct: 2940 if (RetAI.getCoerceToType() == ConvertType(RetTy) && 2941 RetAI.getDirectOffset() == 0) { 2942 // The internal return value temp always will have pointer-to-return-type 2943 // type, just do a load. 2944 2945 // If there is a dominating store to ReturnValue, we can elide 2946 // the load, zap the store, and usually zap the alloca. 2947 if (llvm::StoreInst *SI = 2948 findDominatingStoreToReturnValue(*this)) { 2949 // Reuse the debug location from the store unless there is 2950 // cleanup code to be emitted between the store and return 2951 // instruction. 2952 if (EmitRetDbgLoc && !AutoreleaseResult) 2953 RetDbgLoc = SI->getDebugLoc(); 2954 // Get the stored value and nuke the now-dead store. 2955 RV = SI->getValueOperand(); 2956 SI->eraseFromParent(); 2957 2958 // Otherwise, we have to do a simple load. 2959 } else { 2960 RV = Builder.CreateLoad(ReturnValue); 2961 } 2962 } else { 2963 // If the value is offset in memory, apply the offset now. 2964 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI); 2965 2966 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this); 2967 } 2968 2969 // In ARC, end functions that return a retainable type with a call 2970 // to objc_autoreleaseReturnValue. 2971 if (AutoreleaseResult) { 2972 #ifndef NDEBUG 2973 // Type::isObjCRetainabletype has to be called on a QualType that hasn't 2974 // been stripped of the typedefs, so we cannot use RetTy here. Get the 2975 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from 2976 // CurCodeDecl or BlockInfo. 2977 QualType RT; 2978 2979 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl)) 2980 RT = FD->getReturnType(); 2981 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl)) 2982 RT = MD->getReturnType(); 2983 else if (isa<BlockDecl>(CurCodeDecl)) 2984 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType(); 2985 else 2986 llvm_unreachable("Unexpected function/method type"); 2987 2988 assert(getLangOpts().ObjCAutoRefCount && 2989 !FI.isReturnsRetained() && 2990 RT->isObjCRetainableType()); 2991 #endif 2992 RV = emitAutoreleaseOfResult(*this, RV); 2993 } 2994 2995 break; 2996 2997 case ABIArgInfo::Ignore: 2998 break; 2999 3000 case ABIArgInfo::CoerceAndExpand: { 3001 auto coercionType = RetAI.getCoerceAndExpandType(); 3002 3003 // Load all of the coerced elements out into results. 3004 llvm::SmallVector<llvm::Value*, 4> results; 3005 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType); 3006 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 3007 auto coercedEltType = coercionType->getElementType(i); 3008 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType)) 3009 continue; 3010 3011 auto eltAddr = Builder.CreateStructGEP(addr, i); 3012 auto elt = Builder.CreateLoad(eltAddr); 3013 results.push_back(elt); 3014 } 3015 3016 // If we have one result, it's the single direct result type. 3017 if (results.size() == 1) { 3018 RV = results[0]; 3019 3020 // Otherwise, we need to make a first-class aggregate. 3021 } else { 3022 // Construct a return type that lacks padding elements. 3023 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType(); 3024 3025 RV = llvm::UndefValue::get(returnType); 3026 for (unsigned i = 0, e = results.size(); i != e; ++i) { 3027 RV = Builder.CreateInsertValue(RV, results[i], i); 3028 } 3029 } 3030 break; 3031 } 3032 3033 case ABIArgInfo::Expand: 3034 llvm_unreachable("Invalid ABI kind for return argument"); 3035 } 3036 3037 llvm::Instruction *Ret; 3038 if (RV) { 3039 EmitReturnValueCheck(RV); 3040 Ret = Builder.CreateRet(RV); 3041 } else { 3042 Ret = Builder.CreateRetVoid(); 3043 } 3044 3045 if (RetDbgLoc) 3046 Ret->setDebugLoc(std::move(RetDbgLoc)); 3047 } 3048 3049 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) { 3050 // A current decl may not be available when emitting vtable thunks. 3051 if (!CurCodeDecl) 3052 return; 3053 3054 // If the return block isn't reachable, neither is this check, so don't emit 3055 // it. 3056 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) 3057 return; 3058 3059 ReturnsNonNullAttr *RetNNAttr = nullptr; 3060 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) 3061 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>(); 3062 3063 if (!RetNNAttr && !requiresReturnValueNullabilityCheck()) 3064 return; 3065 3066 // Prefer the returns_nonnull attribute if it's present. 3067 SourceLocation AttrLoc; 3068 SanitizerMask CheckKind; 3069 SanitizerHandler Handler; 3070 if (RetNNAttr) { 3071 assert(!requiresReturnValueNullabilityCheck() && 3072 "Cannot check nullability and the nonnull attribute"); 3073 AttrLoc = RetNNAttr->getLocation(); 3074 CheckKind = SanitizerKind::ReturnsNonnullAttribute; 3075 Handler = SanitizerHandler::NonnullReturn; 3076 } else { 3077 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl)) 3078 if (auto *TSI = DD->getTypeSourceInfo()) 3079 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>()) 3080 AttrLoc = FTL.getReturnLoc().findNullabilityLoc(); 3081 CheckKind = SanitizerKind::NullabilityReturn; 3082 Handler = SanitizerHandler::NullabilityReturn; 3083 } 3084 3085 SanitizerScope SanScope(this); 3086 3087 // Make sure the "return" source location is valid. If we're checking a 3088 // nullability annotation, make sure the preconditions for the check are met. 3089 llvm::BasicBlock *Check = createBasicBlock("nullcheck"); 3090 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck"); 3091 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load"); 3092 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr); 3093 if (requiresReturnValueNullabilityCheck()) 3094 CanNullCheck = 3095 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition); 3096 Builder.CreateCondBr(CanNullCheck, Check, NoCheck); 3097 EmitBlock(Check); 3098 3099 // Now do the null check. 3100 llvm::Value *Cond = Builder.CreateIsNotNull(RV); 3101 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)}; 3102 llvm::Value *DynamicData[] = {SLocPtr}; 3103 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData); 3104 3105 EmitBlock(NoCheck); 3106 3107 #ifndef NDEBUG 3108 // The return location should not be used after the check has been emitted. 3109 ReturnLocation = Address::invalid(); 3110 #endif 3111 } 3112 3113 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) { 3114 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 3115 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory; 3116 } 3117 3118 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, 3119 QualType Ty) { 3120 // FIXME: Generate IR in one pass, rather than going back and fixing up these 3121 // placeholders. 3122 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty); 3123 llvm::Type *IRPtrTy = IRTy->getPointerTo(); 3124 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo()); 3125 3126 // FIXME: When we generate this IR in one pass, we shouldn't need 3127 // this win32-specific alignment hack. 3128 CharUnits Align = CharUnits::fromQuantity(4); 3129 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align); 3130 3131 return AggValueSlot::forAddr(Address(Placeholder, Align), 3132 Ty.getQualifiers(), 3133 AggValueSlot::IsNotDestructed, 3134 AggValueSlot::DoesNotNeedGCBarriers, 3135 AggValueSlot::IsNotAliased, 3136 AggValueSlot::DoesNotOverlap); 3137 } 3138 3139 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args, 3140 const VarDecl *param, 3141 SourceLocation loc) { 3142 // StartFunction converted the ABI-lowered parameter(s) into a 3143 // local alloca. We need to turn that into an r-value suitable 3144 // for EmitCall. 3145 Address local = GetAddrOfLocalVar(param); 3146 3147 QualType type = param->getType(); 3148 3149 if (isInAllocaArgument(CGM.getCXXABI(), type)) { 3150 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter"); 3151 } 3152 3153 // GetAddrOfLocalVar returns a pointer-to-pointer for references, 3154 // but the argument needs to be the original pointer. 3155 if (type->isReferenceType()) { 3156 args.add(RValue::get(Builder.CreateLoad(local)), type); 3157 3158 // In ARC, move out of consumed arguments so that the release cleanup 3159 // entered by StartFunction doesn't cause an over-release. This isn't 3160 // optimal -O0 code generation, but it should get cleaned up when 3161 // optimization is enabled. This also assumes that delegate calls are 3162 // performed exactly once for a set of arguments, but that should be safe. 3163 } else if (getLangOpts().ObjCAutoRefCount && 3164 param->hasAttr<NSConsumedAttr>() && 3165 type->isObjCRetainableType()) { 3166 llvm::Value *ptr = Builder.CreateLoad(local); 3167 auto null = 3168 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType())); 3169 Builder.CreateStore(null, local); 3170 args.add(RValue::get(ptr), type); 3171 3172 // For the most part, we just need to load the alloca, except that 3173 // aggregate r-values are actually pointers to temporaries. 3174 } else { 3175 args.add(convertTempToRValue(local, type, loc), type); 3176 } 3177 3178 // Deactivate the cleanup for the callee-destructed param that was pushed. 3179 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk && 3180 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() && 3181 param->needsDestruction(getContext())) { 3182 EHScopeStack::stable_iterator cleanup = 3183 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param)); 3184 assert(cleanup.isValid() && 3185 "cleanup for callee-destructed param not recorded"); 3186 // This unreachable is a temporary marker which will be removed later. 3187 llvm::Instruction *isActive = Builder.CreateUnreachable(); 3188 args.addArgCleanupDeactivation(cleanup, isActive); 3189 } 3190 } 3191 3192 static bool isProvablyNull(llvm::Value *addr) { 3193 return isa<llvm::ConstantPointerNull>(addr); 3194 } 3195 3196 /// Emit the actual writing-back of a writeback. 3197 static void emitWriteback(CodeGenFunction &CGF, 3198 const CallArgList::Writeback &writeback) { 3199 const LValue &srcLV = writeback.Source; 3200 Address srcAddr = srcLV.getAddress(CGF); 3201 assert(!isProvablyNull(srcAddr.getPointer()) && 3202 "shouldn't have writeback for provably null argument"); 3203 3204 llvm::BasicBlock *contBB = nullptr; 3205 3206 // If the argument wasn't provably non-null, we need to null check 3207 // before doing the store. 3208 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3209 CGF.CGM.getDataLayout()); 3210 if (!provablyNonNull) { 3211 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback"); 3212 contBB = CGF.createBasicBlock("icr.done"); 3213 3214 llvm::Value *isNull = 3215 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3216 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB); 3217 CGF.EmitBlock(writebackBB); 3218 } 3219 3220 // Load the value to writeback. 3221 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary); 3222 3223 // Cast it back, in case we're writing an id to a Foo* or something. 3224 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), 3225 "icr.writeback-cast"); 3226 3227 // Perform the writeback. 3228 3229 // If we have a "to use" value, it's something we need to emit a use 3230 // of. This has to be carefully threaded in: if it's done after the 3231 // release it's potentially undefined behavior (and the optimizer 3232 // will ignore it), and if it happens before the retain then the 3233 // optimizer could move the release there. 3234 if (writeback.ToUse) { 3235 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong); 3236 3237 // Retain the new value. No need to block-copy here: the block's 3238 // being passed up the stack. 3239 value = CGF.EmitARCRetainNonBlock(value); 3240 3241 // Emit the intrinsic use here. 3242 CGF.EmitARCIntrinsicUse(writeback.ToUse); 3243 3244 // Load the old value (primitively). 3245 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation()); 3246 3247 // Put the new value in place (primitively). 3248 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false); 3249 3250 // Release the old value. 3251 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime()); 3252 3253 // Otherwise, we can just do a normal lvalue store. 3254 } else { 3255 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV); 3256 } 3257 3258 // Jump to the continuation block. 3259 if (!provablyNonNull) 3260 CGF.EmitBlock(contBB); 3261 } 3262 3263 static void emitWritebacks(CodeGenFunction &CGF, 3264 const CallArgList &args) { 3265 for (const auto &I : args.writebacks()) 3266 emitWriteback(CGF, I); 3267 } 3268 3269 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, 3270 const CallArgList &CallArgs) { 3271 ArrayRef<CallArgList::CallArgCleanup> Cleanups = 3272 CallArgs.getCleanupsToDeactivate(); 3273 // Iterate in reverse to increase the likelihood of popping the cleanup. 3274 for (const auto &I : llvm::reverse(Cleanups)) { 3275 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP); 3276 I.IsActiveIP->eraseFromParent(); 3277 } 3278 } 3279 3280 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) { 3281 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens())) 3282 if (uop->getOpcode() == UO_AddrOf) 3283 return uop->getSubExpr(); 3284 return nullptr; 3285 } 3286 3287 /// Emit an argument that's being passed call-by-writeback. That is, 3288 /// we are passing the address of an __autoreleased temporary; it 3289 /// might be copy-initialized with the current value of the given 3290 /// address, but it will definitely be copied out of after the call. 3291 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, 3292 const ObjCIndirectCopyRestoreExpr *CRE) { 3293 LValue srcLV; 3294 3295 // Make an optimistic effort to emit the address as an l-value. 3296 // This can fail if the argument expression is more complicated. 3297 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) { 3298 srcLV = CGF.EmitLValue(lvExpr); 3299 3300 // Otherwise, just emit it as a scalar. 3301 } else { 3302 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr()); 3303 3304 QualType srcAddrType = 3305 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 3306 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType); 3307 } 3308 Address srcAddr = srcLV.getAddress(CGF); 3309 3310 // The dest and src types don't necessarily match in LLVM terms 3311 // because of the crazy ObjC compatibility rules. 3312 3313 llvm::PointerType *destType = 3314 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType())); 3315 3316 // If the address is a constant null, just pass the appropriate null. 3317 if (isProvablyNull(srcAddr.getPointer())) { 3318 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)), 3319 CRE->getType()); 3320 return; 3321 } 3322 3323 // Create the temporary. 3324 Address temp = CGF.CreateTempAlloca(destType->getElementType(), 3325 CGF.getPointerAlign(), 3326 "icr.temp"); 3327 // Loading an l-value can introduce a cleanup if the l-value is __weak, 3328 // and that cleanup will be conditional if we can't prove that the l-value 3329 // isn't null, so we need to register a dominating point so that the cleanups 3330 // system will make valid IR. 3331 CodeGenFunction::ConditionalEvaluation condEval(CGF); 3332 3333 // Zero-initialize it if we're not doing a copy-initialization. 3334 bool shouldCopy = CRE->shouldCopy(); 3335 if (!shouldCopy) { 3336 llvm::Value *null = 3337 llvm::ConstantPointerNull::get( 3338 cast<llvm::PointerType>(destType->getElementType())); 3339 CGF.Builder.CreateStore(null, temp); 3340 } 3341 3342 llvm::BasicBlock *contBB = nullptr; 3343 llvm::BasicBlock *originBB = nullptr; 3344 3345 // If the address is *not* known to be non-null, we need to switch. 3346 llvm::Value *finalArgument; 3347 3348 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3349 CGF.CGM.getDataLayout()); 3350 if (provablyNonNull) { 3351 finalArgument = temp.getPointer(); 3352 } else { 3353 llvm::Value *isNull = 3354 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3355 3356 finalArgument = CGF.Builder.CreateSelect(isNull, 3357 llvm::ConstantPointerNull::get(destType), 3358 temp.getPointer(), "icr.argument"); 3359 3360 // If we need to copy, then the load has to be conditional, which 3361 // means we need control flow. 3362 if (shouldCopy) { 3363 originBB = CGF.Builder.GetInsertBlock(); 3364 contBB = CGF.createBasicBlock("icr.cont"); 3365 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy"); 3366 CGF.Builder.CreateCondBr(isNull, contBB, copyBB); 3367 CGF.EmitBlock(copyBB); 3368 condEval.begin(CGF); 3369 } 3370 } 3371 3372 llvm::Value *valueToUse = nullptr; 3373 3374 // Perform a copy if necessary. 3375 if (shouldCopy) { 3376 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation()); 3377 assert(srcRV.isScalar()); 3378 3379 llvm::Value *src = srcRV.getScalarVal(); 3380 src = CGF.Builder.CreateBitCast(src, destType->getElementType(), 3381 "icr.cast"); 3382 3383 // Use an ordinary store, not a store-to-lvalue. 3384 CGF.Builder.CreateStore(src, temp); 3385 3386 // If optimization is enabled, and the value was held in a 3387 // __strong variable, we need to tell the optimizer that this 3388 // value has to stay alive until we're doing the store back. 3389 // This is because the temporary is effectively unretained, 3390 // and so otherwise we can violate the high-level semantics. 3391 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 && 3392 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) { 3393 valueToUse = src; 3394 } 3395 } 3396 3397 // Finish the control flow if we needed it. 3398 if (shouldCopy && !provablyNonNull) { 3399 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); 3400 CGF.EmitBlock(contBB); 3401 3402 // Make a phi for the value to intrinsically use. 3403 if (valueToUse) { 3404 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2, 3405 "icr.to-use"); 3406 phiToUse->addIncoming(valueToUse, copyBB); 3407 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()), 3408 originBB); 3409 valueToUse = phiToUse; 3410 } 3411 3412 condEval.end(CGF); 3413 } 3414 3415 args.addWriteback(srcLV, temp, valueToUse); 3416 args.add(RValue::get(finalArgument), CRE->getType()); 3417 } 3418 3419 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) { 3420 assert(!StackBase); 3421 3422 // Save the stack. 3423 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave); 3424 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save"); 3425 } 3426 3427 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const { 3428 if (StackBase) { 3429 // Restore the stack after the call. 3430 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 3431 CGF.Builder.CreateCall(F, StackBase); 3432 } 3433 } 3434 3435 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, 3436 SourceLocation ArgLoc, 3437 AbstractCallee AC, 3438 unsigned ParmNum) { 3439 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) || 3440 SanOpts.has(SanitizerKind::NullabilityArg))) 3441 return; 3442 3443 // The param decl may be missing in a variadic function. 3444 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr; 3445 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; 3446 3447 // Prefer the nonnull attribute if it's present. 3448 const NonNullAttr *NNAttr = nullptr; 3449 if (SanOpts.has(SanitizerKind::NonnullAttribute)) 3450 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo); 3451 3452 bool CanCheckNullability = false; 3453 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) { 3454 auto Nullability = PVD->getType()->getNullability(getContext()); 3455 CanCheckNullability = Nullability && 3456 *Nullability == NullabilityKind::NonNull && 3457 PVD->getTypeSourceInfo(); 3458 } 3459 3460 if (!NNAttr && !CanCheckNullability) 3461 return; 3462 3463 SourceLocation AttrLoc; 3464 SanitizerMask CheckKind; 3465 SanitizerHandler Handler; 3466 if (NNAttr) { 3467 AttrLoc = NNAttr->getLocation(); 3468 CheckKind = SanitizerKind::NonnullAttribute; 3469 Handler = SanitizerHandler::NonnullArg; 3470 } else { 3471 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc(); 3472 CheckKind = SanitizerKind::NullabilityArg; 3473 Handler = SanitizerHandler::NullabilityArg; 3474 } 3475 3476 SanitizerScope SanScope(this); 3477 assert(RV.isScalar()); 3478 llvm::Value *V = RV.getScalarVal(); 3479 llvm::Value *Cond = 3480 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType())); 3481 llvm::Constant *StaticData[] = { 3482 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc), 3483 llvm::ConstantInt::get(Int32Ty, ArgNo + 1), 3484 }; 3485 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None); 3486 } 3487 3488 void CodeGenFunction::EmitCallArgs( 3489 CallArgList &Args, ArrayRef<QualType> ArgTypes, 3490 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3491 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) { 3492 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())); 3493 3494 // We *have* to evaluate arguments from right to left in the MS C++ ABI, 3495 // because arguments are destroyed left to right in the callee. As a special 3496 // case, there are certain language constructs that require left-to-right 3497 // evaluation, and in those cases we consider the evaluation order requirement 3498 // to trump the "destruction order is reverse construction order" guarantee. 3499 bool LeftToRight = 3500 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee() 3501 ? Order == EvaluationOrder::ForceLeftToRight 3502 : Order != EvaluationOrder::ForceRightToLeft; 3503 3504 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg, 3505 RValue EmittedArg) { 3506 if (!AC.hasFunctionDecl() || I >= AC.getNumParams()) 3507 return; 3508 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>(); 3509 if (PS == nullptr) 3510 return; 3511 3512 const auto &Context = getContext(); 3513 auto SizeTy = Context.getSizeType(); 3514 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy)); 3515 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?"); 3516 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T, 3517 EmittedArg.getScalarVal(), 3518 PS->isDynamic()); 3519 Args.add(RValue::get(V), SizeTy); 3520 // If we're emitting args in reverse, be sure to do so with 3521 // pass_object_size, as well. 3522 if (!LeftToRight) 3523 std::swap(Args.back(), *(&Args.back() - 1)); 3524 }; 3525 3526 // Insert a stack save if we're going to need any inalloca args. 3527 bool HasInAllocaArgs = false; 3528 if (CGM.getTarget().getCXXABI().isMicrosoft()) { 3529 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end(); 3530 I != E && !HasInAllocaArgs; ++I) 3531 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I); 3532 if (HasInAllocaArgs) { 3533 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 3534 Args.allocateArgumentMemory(*this); 3535 } 3536 } 3537 3538 // Evaluate each argument in the appropriate order. 3539 size_t CallArgsStart = Args.size(); 3540 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) { 3541 unsigned Idx = LeftToRight ? I : E - I - 1; 3542 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx; 3543 unsigned InitialArgSize = Args.size(); 3544 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of 3545 // the argument and parameter match or the objc method is parameterized. 3546 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || 3547 getContext().hasSameUnqualifiedType((*Arg)->getType(), 3548 ArgTypes[Idx]) || 3549 (isa<ObjCMethodDecl>(AC.getDecl()) && 3550 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && 3551 "Argument and parameter types don't match"); 3552 EmitCallArg(Args, *Arg, ArgTypes[Idx]); 3553 // In particular, we depend on it being the last arg in Args, and the 3554 // objectsize bits depend on there only being one arg if !LeftToRight. 3555 assert(InitialArgSize + 1 == Args.size() && 3556 "The code below depends on only adding one arg per EmitCallArg"); 3557 (void)InitialArgSize; 3558 // Since pointer argument are never emitted as LValue, it is safe to emit 3559 // non-null argument check for r-value only. 3560 if (!Args.back().hasLValue()) { 3561 RValue RVArg = Args.back().getKnownRValue(); 3562 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC, 3563 ParamsToSkip + Idx); 3564 // @llvm.objectsize should never have side-effects and shouldn't need 3565 // destruction/cleanups, so we can safely "emit" it after its arg, 3566 // regardless of right-to-leftness 3567 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg); 3568 } 3569 } 3570 3571 if (!LeftToRight) { 3572 // Un-reverse the arguments we just evaluated so they match up with the LLVM 3573 // IR function. 3574 std::reverse(Args.begin() + CallArgsStart, Args.end()); 3575 } 3576 } 3577 3578 namespace { 3579 3580 struct DestroyUnpassedArg final : EHScopeStack::Cleanup { 3581 DestroyUnpassedArg(Address Addr, QualType Ty) 3582 : Addr(Addr), Ty(Ty) {} 3583 3584 Address Addr; 3585 QualType Ty; 3586 3587 void Emit(CodeGenFunction &CGF, Flags flags) override { 3588 QualType::DestructionKind DtorKind = Ty.isDestructedType(); 3589 if (DtorKind == QualType::DK_cxx_destructor) { 3590 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 3591 assert(!Dtor->isTrivial()); 3592 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false, 3593 /*Delegating=*/false, Addr, Ty); 3594 } else { 3595 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty)); 3596 } 3597 } 3598 }; 3599 3600 struct DisableDebugLocationUpdates { 3601 CodeGenFunction &CGF; 3602 bool disabledDebugInfo; 3603 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) { 3604 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo())) 3605 CGF.disableDebugInfo(); 3606 } 3607 ~DisableDebugLocationUpdates() { 3608 if (disabledDebugInfo) 3609 CGF.enableDebugInfo(); 3610 } 3611 }; 3612 3613 } // end anonymous namespace 3614 3615 RValue CallArg::getRValue(CodeGenFunction &CGF) const { 3616 if (!HasLV) 3617 return RV; 3618 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty); 3619 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap, 3620 LV.isVolatile()); 3621 IsUsed = true; 3622 return RValue::getAggregate(Copy.getAddress(CGF)); 3623 } 3624 3625 void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const { 3626 LValue Dst = CGF.MakeAddrLValue(Addr, Ty); 3627 if (!HasLV && RV.isScalar()) 3628 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true); 3629 else if (!HasLV && RV.isComplex()) 3630 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true); 3631 else { 3632 auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress(); 3633 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty); 3634 // We assume that call args are never copied into subobjects. 3635 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap, 3636 HasLV ? LV.isVolatileQualified() 3637 : RV.isVolatileQualified()); 3638 } 3639 IsUsed = true; 3640 } 3641 3642 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, 3643 QualType type) { 3644 DisableDebugLocationUpdates Dis(*this, E); 3645 if (const ObjCIndirectCopyRestoreExpr *CRE 3646 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { 3647 assert(getLangOpts().ObjCAutoRefCount); 3648 return emitWritebackArg(*this, args, CRE); 3649 } 3650 3651 assert(type->isReferenceType() == E->isGLValue() && 3652 "reference binding to unmaterialized r-value!"); 3653 3654 if (E->isGLValue()) { 3655 assert(E->getObjectKind() == OK_Ordinary); 3656 return args.add(EmitReferenceBindingToExpr(E), type); 3657 } 3658 3659 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type); 3660 3661 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee. 3662 // However, we still have to push an EH-only cleanup in case we unwind before 3663 // we make it to the call. 3664 if (HasAggregateEvalKind && 3665 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) { 3666 // If we're using inalloca, use the argument memory. Otherwise, use a 3667 // temporary. 3668 AggValueSlot Slot; 3669 if (args.isUsingInAlloca()) 3670 Slot = createPlaceholderSlot(*this, type); 3671 else 3672 Slot = CreateAggTemp(type, "agg.tmp"); 3673 3674 bool DestroyedInCallee = true, NeedsEHCleanup = true; 3675 if (const auto *RD = type->getAsCXXRecordDecl()) 3676 DestroyedInCallee = RD->hasNonTrivialDestructor(); 3677 else 3678 NeedsEHCleanup = needsEHCleanup(type.isDestructedType()); 3679 3680 if (DestroyedInCallee) 3681 Slot.setExternallyDestructed(); 3682 3683 EmitAggExpr(E, Slot); 3684 RValue RV = Slot.asRValue(); 3685 args.add(RV, type); 3686 3687 if (DestroyedInCallee && NeedsEHCleanup) { 3688 // Create a no-op GEP between the placeholder and the cleanup so we can 3689 // RAUW it successfully. It also serves as a marker of the first 3690 // instruction where the cleanup is active. 3691 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(), 3692 type); 3693 // This unreachable is a temporary marker which will be removed later. 3694 llvm::Instruction *IsActive = Builder.CreateUnreachable(); 3695 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive); 3696 } 3697 return; 3698 } 3699 3700 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) && 3701 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 3702 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 3703 assert(L.isSimple()); 3704 args.addUncopiedAggregate(L, type); 3705 return; 3706 } 3707 3708 args.add(EmitAnyExprToTemp(E), type); 3709 } 3710 3711 QualType CodeGenFunction::getVarArgType(const Expr *Arg) { 3712 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC 3713 // implicitly widens null pointer constants that are arguments to varargs 3714 // functions to pointer-sized ints. 3715 if (!getTarget().getTriple().isOSWindows()) 3716 return Arg->getType(); 3717 3718 if (Arg->getType()->isIntegerType() && 3719 getContext().getTypeSize(Arg->getType()) < 3720 getContext().getTargetInfo().getPointerWidth(0) && 3721 Arg->isNullPointerConstant(getContext(), 3722 Expr::NPC_ValueDependentIsNotNull)) { 3723 return getContext().getIntPtrType(); 3724 } 3725 3726 return Arg->getType(); 3727 } 3728 3729 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3730 // optimizer it can aggressively ignore unwind edges. 3731 void 3732 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 3733 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 3734 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 3735 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 3736 CGM.getNoObjCARCExceptionsMetadata()); 3737 } 3738 3739 /// Emits a call to the given no-arguments nounwind runtime function. 3740 llvm::CallInst * 3741 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3742 const llvm::Twine &name) { 3743 return EmitNounwindRuntimeCall(callee, None, name); 3744 } 3745 3746 /// Emits a call to the given nounwind runtime function. 3747 llvm::CallInst * 3748 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3749 ArrayRef<llvm::Value *> args, 3750 const llvm::Twine &name) { 3751 llvm::CallInst *call = EmitRuntimeCall(callee, args, name); 3752 call->setDoesNotThrow(); 3753 return call; 3754 } 3755 3756 /// Emits a simple call (never an invoke) to the given no-arguments 3757 /// runtime function. 3758 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 3759 const llvm::Twine &name) { 3760 return EmitRuntimeCall(callee, None, name); 3761 } 3762 3763 // Calls which may throw must have operand bundles indicating which funclet 3764 // they are nested within. 3765 SmallVector<llvm::OperandBundleDef, 1> 3766 CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) { 3767 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3768 // There is no need for a funclet operand bundle if we aren't inside a 3769 // funclet. 3770 if (!CurrentFuncletPad) 3771 return BundleList; 3772 3773 // Skip intrinsics which cannot throw. 3774 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts()); 3775 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) 3776 return BundleList; 3777 3778 BundleList.emplace_back("funclet", CurrentFuncletPad); 3779 return BundleList; 3780 } 3781 3782 /// Emits a simple call (never an invoke) to the given runtime function. 3783 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 3784 ArrayRef<llvm::Value *> args, 3785 const llvm::Twine &name) { 3786 llvm::CallInst *call = Builder.CreateCall( 3787 callee, args, getBundlesForFunclet(callee.getCallee()), name); 3788 call->setCallingConv(getRuntimeCC()); 3789 return call; 3790 } 3791 3792 /// Emits a call or invoke to the given noreturn runtime function. 3793 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke( 3794 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) { 3795 SmallVector<llvm::OperandBundleDef, 1> BundleList = 3796 getBundlesForFunclet(callee.getCallee()); 3797 3798 if (getInvokeDest()) { 3799 llvm::InvokeInst *invoke = 3800 Builder.CreateInvoke(callee, 3801 getUnreachableBlock(), 3802 getInvokeDest(), 3803 args, 3804 BundleList); 3805 invoke->setDoesNotReturn(); 3806 invoke->setCallingConv(getRuntimeCC()); 3807 } else { 3808 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList); 3809 call->setDoesNotReturn(); 3810 call->setCallingConv(getRuntimeCC()); 3811 Builder.CreateUnreachable(); 3812 } 3813 } 3814 3815 /// Emits a call or invoke instruction to the given nullary runtime function. 3816 llvm::CallBase * 3817 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3818 const Twine &name) { 3819 return EmitRuntimeCallOrInvoke(callee, None, name); 3820 } 3821 3822 /// Emits a call or invoke instruction to the given runtime function. 3823 llvm::CallBase * 3824 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 3825 ArrayRef<llvm::Value *> args, 3826 const Twine &name) { 3827 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name); 3828 call->setCallingConv(getRuntimeCC()); 3829 return call; 3830 } 3831 3832 /// Emits a call or invoke instruction to the given function, depending 3833 /// on the current state of the EH stack. 3834 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee, 3835 ArrayRef<llvm::Value *> Args, 3836 const Twine &Name) { 3837 llvm::BasicBlock *InvokeDest = getInvokeDest(); 3838 SmallVector<llvm::OperandBundleDef, 1> BundleList = 3839 getBundlesForFunclet(Callee.getCallee()); 3840 3841 llvm::CallBase *Inst; 3842 if (!InvokeDest) 3843 Inst = Builder.CreateCall(Callee, Args, BundleList, Name); 3844 else { 3845 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 3846 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList, 3847 Name); 3848 EmitBlock(ContBB); 3849 } 3850 3851 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3852 // optimizer it can aggressively ignore unwind edges. 3853 if (CGM.getLangOpts().ObjCAutoRefCount) 3854 AddObjCARCExceptionMetadata(Inst); 3855 3856 return Inst; 3857 } 3858 3859 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old, 3860 llvm::Value *New) { 3861 DeferredReplacements.push_back(std::make_pair(Old, New)); 3862 } 3863 3864 namespace { 3865 3866 /// Specify given \p NewAlign as the alignment of return value attribute. If 3867 /// such attribute already exists, re-set it to the maximal one of two options. 3868 LLVM_NODISCARD llvm::AttributeList 3869 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx, 3870 const llvm::AttributeList &Attrs, 3871 llvm::Align NewAlign) { 3872 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne(); 3873 if (CurAlign >= NewAlign) 3874 return Attrs; 3875 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign); 3876 return Attrs 3877 .removeAttribute(Ctx, llvm::AttributeList::ReturnIndex, 3878 llvm::Attribute::AttrKind::Alignment) 3879 .addAttribute(Ctx, llvm::AttributeList::ReturnIndex, AlignAttr); 3880 } 3881 3882 template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter { 3883 protected: 3884 CodeGenFunction &CGF; 3885 3886 /// We do nothing if this is, or becomes, nullptr. 3887 const AlignedAttrTy *AA = nullptr; 3888 3889 llvm::Value *Alignment = nullptr; // May or may not be a constant. 3890 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero. 3891 3892 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl) 3893 : CGF(CGF_) { 3894 if (!FuncDecl) 3895 return; 3896 AA = FuncDecl->getAttr<AlignedAttrTy>(); 3897 } 3898 3899 public: 3900 /// If we can, materialize the alignment as an attribute on return value. 3901 LLVM_NODISCARD llvm::AttributeList 3902 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) { 3903 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment)) 3904 return Attrs; 3905 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment); 3906 if (!AlignmentCI) 3907 return Attrs; 3908 // We may legitimately have non-power-of-2 alignment here. 3909 // If so, this is UB land, emit it via `@llvm.assume` instead. 3910 if (!AlignmentCI->getValue().isPowerOf2()) 3911 return Attrs; 3912 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute( 3913 CGF.getLLVMContext(), Attrs, 3914 llvm::Align( 3915 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment))); 3916 AA = nullptr; // We're done. Disallow doing anything else. 3917 return NewAttrs; 3918 } 3919 3920 /// Emit alignment assumption. 3921 /// This is a general fallback that we take if either there is an offset, 3922 /// or the alignment is variable or we are sanitizing for alignment. 3923 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) { 3924 if (!AA) 3925 return; 3926 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, 3927 AA->getLocation(), Alignment, OffsetCI); 3928 AA = nullptr; // We're done. Disallow doing anything else. 3929 } 3930 }; 3931 3932 /// Helper data structure to emit `AssumeAlignedAttr`. 3933 class AssumeAlignedAttrEmitter final 3934 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> { 3935 public: 3936 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl) 3937 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) { 3938 if (!AA) 3939 return; 3940 // It is guaranteed that the alignment/offset are constants. 3941 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment())); 3942 if (Expr *Offset = AA->getOffset()) { 3943 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset)); 3944 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset. 3945 OffsetCI = nullptr; 3946 } 3947 } 3948 }; 3949 3950 /// Helper data structure to emit `AllocAlignAttr`. 3951 class AllocAlignAttrEmitter final 3952 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> { 3953 public: 3954 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl, 3955 const CallArgList &CallArgs) 3956 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) { 3957 if (!AA) 3958 return; 3959 // Alignment may or may not be a constant, and that is okay. 3960 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()] 3961 .getRValue(CGF) 3962 .getScalarVal(); 3963 } 3964 }; 3965 3966 } // namespace 3967 3968 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 3969 const CGCallee &Callee, 3970 ReturnValueSlot ReturnValue, 3971 const CallArgList &CallArgs, 3972 llvm::CallBase **callOrInvoke, 3973 SourceLocation Loc) { 3974 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 3975 3976 assert(Callee.isOrdinary() || Callee.isVirtual()); 3977 3978 // Handle struct-return functions by passing a pointer to the 3979 // location that we would like to return into. 3980 QualType RetTy = CallInfo.getReturnType(); 3981 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 3982 3983 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo); 3984 3985 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl(); 3986 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 3987 // We can only guarantee that a function is called from the correct 3988 // context/function based on the appropriate target attributes, 3989 // so only check in the case where we have both always_inline and target 3990 // since otherwise we could be making a conditional call after a check for 3991 // the proper cpu features (and it won't cause code generation issues due to 3992 // function based code generation). 3993 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 3994 TargetDecl->hasAttr<TargetAttr>()) 3995 checkTargetFeatures(Loc, FD); 3996 3997 #ifndef NDEBUG 3998 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) { 3999 // For an inalloca varargs function, we don't expect CallInfo to match the 4000 // function pointer's type, because the inalloca struct a will have extra 4001 // fields in it for the varargs parameters. Code later in this function 4002 // bitcasts the function pointer to the type derived from CallInfo. 4003 // 4004 // In other cases, we assert that the types match up (until pointers stop 4005 // having pointee types). 4006 llvm::Type *TypeFromVal; 4007 if (Callee.isVirtual()) 4008 TypeFromVal = Callee.getVirtualFunctionType(); 4009 else 4010 TypeFromVal = 4011 Callee.getFunctionPointer()->getType()->getPointerElementType(); 4012 assert(IRFuncTy == TypeFromVal); 4013 } 4014 #endif 4015 4016 // 1. Set up the arguments. 4017 4018 // If we're using inalloca, insert the allocation after the stack save. 4019 // FIXME: Do this earlier rather than hacking it in here! 4020 Address ArgMemory = Address::invalid(); 4021 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) { 4022 const llvm::DataLayout &DL = CGM.getDataLayout(); 4023 llvm::Instruction *IP = CallArgs.getStackBase(); 4024 llvm::AllocaInst *AI; 4025 if (IP) { 4026 IP = IP->getNextNode(); 4027 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), 4028 "argmem", IP); 4029 } else { 4030 AI = CreateTempAlloca(ArgStruct, "argmem"); 4031 } 4032 auto Align = CallInfo.getArgStructAlignment(); 4033 AI->setAlignment(Align.getAsAlign()); 4034 AI->setUsedWithInAlloca(true); 4035 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca()); 4036 ArgMemory = Address(AI, Align); 4037 } 4038 4039 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo); 4040 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs()); 4041 4042 // If the call returns a temporary with struct return, create a temporary 4043 // alloca to hold the result, unless one is given to us. 4044 Address SRetPtr = Address::invalid(); 4045 Address SRetAlloca = Address::invalid(); 4046 llvm::Value *UnusedReturnSizePtr = nullptr; 4047 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) { 4048 if (!ReturnValue.isNull()) { 4049 SRetPtr = ReturnValue.getValue(); 4050 } else { 4051 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca); 4052 if (HaveInsertPoint() && ReturnValue.isUnused()) { 4053 uint64_t size = 4054 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); 4055 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer()); 4056 } 4057 } 4058 if (IRFunctionArgs.hasSRetArg()) { 4059 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer(); 4060 } else if (RetAI.isInAlloca()) { 4061 Address Addr = 4062 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex()); 4063 Builder.CreateStore(SRetPtr.getPointer(), Addr); 4064 } 4065 } 4066 4067 Address swiftErrorTemp = Address::invalid(); 4068 Address swiftErrorArg = Address::invalid(); 4069 4070 // When passing arguments using temporary allocas, we need to add the 4071 // appropriate lifetime markers. This vector keeps track of all the lifetime 4072 // markers that need to be ended right after the call. 4073 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall; 4074 4075 // Translate all of the arguments as necessary to match the IR lowering. 4076 assert(CallInfo.arg_size() == CallArgs.size() && 4077 "Mismatch between function signature & arguments."); 4078 unsigned ArgNo = 0; 4079 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 4080 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 4081 I != E; ++I, ++info_it, ++ArgNo) { 4082 const ABIArgInfo &ArgInfo = info_it->info; 4083 4084 // Insert a padding argument to ensure proper alignment. 4085 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 4086 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 4087 llvm::UndefValue::get(ArgInfo.getPaddingType()); 4088 4089 unsigned FirstIRArg, NumIRArgs; 4090 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 4091 4092 switch (ArgInfo.getKind()) { 4093 case ABIArgInfo::InAlloca: { 4094 assert(NumIRArgs == 0); 4095 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 4096 if (I->isAggregate()) { 4097 Address Addr = I->hasLValue() 4098 ? I->getKnownLValue().getAddress(*this) 4099 : I->getKnownRValue().getAggregateAddress(); 4100 llvm::Instruction *Placeholder = 4101 cast<llvm::Instruction>(Addr.getPointer()); 4102 4103 if (!ArgInfo.getInAllocaIndirect()) { 4104 // Replace the placeholder with the appropriate argument slot GEP. 4105 CGBuilderTy::InsertPoint IP = Builder.saveIP(); 4106 Builder.SetInsertPoint(Placeholder); 4107 Addr = Builder.CreateStructGEP(ArgMemory, 4108 ArgInfo.getInAllocaFieldIndex()); 4109 Builder.restoreIP(IP); 4110 } else { 4111 // For indirect things such as overaligned structs, replace the 4112 // placeholder with a regular aggregate temporary alloca. Store the 4113 // address of this alloca into the struct. 4114 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp"); 4115 Address ArgSlot = Builder.CreateStructGEP( 4116 ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4117 Builder.CreateStore(Addr.getPointer(), ArgSlot); 4118 } 4119 deferPlaceholderReplacement(Placeholder, Addr.getPointer()); 4120 } else if (ArgInfo.getInAllocaIndirect()) { 4121 // Make a temporary alloca and store the address of it into the argument 4122 // struct. 4123 Address Addr = CreateMemTempWithoutCast( 4124 I->Ty, getContext().getTypeAlignInChars(I->Ty), 4125 "indirect-arg-temp"); 4126 I->copyInto(*this, Addr); 4127 Address ArgSlot = 4128 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4129 Builder.CreateStore(Addr.getPointer(), ArgSlot); 4130 } else { 4131 // Store the RValue into the argument struct. 4132 Address Addr = 4133 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4134 unsigned AS = Addr.getType()->getPointerAddressSpace(); 4135 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS); 4136 // There are some cases where a trivial bitcast is not avoidable. The 4137 // definition of a type later in a translation unit may change it's type 4138 // from {}* to (%struct.foo*)*. 4139 if (Addr.getType() != MemType) 4140 Addr = Builder.CreateBitCast(Addr, MemType); 4141 I->copyInto(*this, Addr); 4142 } 4143 break; 4144 } 4145 4146 case ABIArgInfo::Indirect: { 4147 assert(NumIRArgs == 1); 4148 if (!I->isAggregate()) { 4149 // Make a temporary alloca to pass the argument. 4150 Address Addr = CreateMemTempWithoutCast( 4151 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp"); 4152 IRCallArgs[FirstIRArg] = Addr.getPointer(); 4153 4154 I->copyInto(*this, Addr); 4155 } else { 4156 // We want to avoid creating an unnecessary temporary+copy here; 4157 // however, we need one in three cases: 4158 // 1. If the argument is not byval, and we are required to copy the 4159 // source. (This case doesn't occur on any common architecture.) 4160 // 2. If the argument is byval, RV is not sufficiently aligned, and 4161 // we cannot force it to be sufficiently aligned. 4162 // 3. If the argument is byval, but RV is not located in default 4163 // or alloca address space. 4164 Address Addr = I->hasLValue() 4165 ? I->getKnownLValue().getAddress(*this) 4166 : I->getKnownRValue().getAggregateAddress(); 4167 llvm::Value *V = Addr.getPointer(); 4168 CharUnits Align = ArgInfo.getIndirectAlign(); 4169 const llvm::DataLayout *TD = &CGM.getDataLayout(); 4170 4171 assert((FirstIRArg >= IRFuncTy->getNumParams() || 4172 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == 4173 TD->getAllocaAddrSpace()) && 4174 "indirect argument must be in alloca address space"); 4175 4176 bool NeedCopy = false; 4177 4178 if (Addr.getAlignment() < Align && 4179 llvm::getOrEnforceKnownAlignment(V, Align.getQuantity(), *TD) < 4180 Align.getQuantity()) { 4181 NeedCopy = true; 4182 } else if (I->hasLValue()) { 4183 auto LV = I->getKnownLValue(); 4184 auto AS = LV.getAddressSpace(); 4185 4186 if (!ArgInfo.getIndirectByVal() || 4187 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) { 4188 NeedCopy = true; 4189 } 4190 if (!getLangOpts().OpenCL) { 4191 if ((ArgInfo.getIndirectByVal() && 4192 (AS != LangAS::Default && 4193 AS != CGM.getASTAllocaAddressSpace()))) { 4194 NeedCopy = true; 4195 } 4196 } 4197 // For OpenCL even if RV is located in default or alloca address space 4198 // we don't want to perform address space cast for it. 4199 else if ((ArgInfo.getIndirectByVal() && 4200 Addr.getType()->getAddressSpace() != IRFuncTy-> 4201 getParamType(FirstIRArg)->getPointerAddressSpace())) { 4202 NeedCopy = true; 4203 } 4204 } 4205 4206 if (NeedCopy) { 4207 // Create an aligned temporary, and copy to it. 4208 Address AI = CreateMemTempWithoutCast( 4209 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp"); 4210 IRCallArgs[FirstIRArg] = AI.getPointer(); 4211 4212 // Emit lifetime markers for the temporary alloca. 4213 uint64_t ByvalTempElementSize = 4214 CGM.getDataLayout().getTypeAllocSize(AI.getElementType()); 4215 llvm::Value *LifetimeSize = 4216 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer()); 4217 4218 // Add cleanup code to emit the end lifetime marker after the call. 4219 if (LifetimeSize) // In case we disabled lifetime markers. 4220 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize); 4221 4222 // Generate the copy. 4223 I->copyInto(*this, AI); 4224 } else { 4225 // Skip the extra memcpy call. 4226 auto *T = V->getType()->getPointerElementType()->getPointerTo( 4227 CGM.getDataLayout().getAllocaAddrSpace()); 4228 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast( 4229 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T, 4230 true); 4231 } 4232 } 4233 break; 4234 } 4235 4236 case ABIArgInfo::Ignore: 4237 assert(NumIRArgs == 0); 4238 break; 4239 4240 case ABIArgInfo::Extend: 4241 case ABIArgInfo::Direct: { 4242 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 4243 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 4244 ArgInfo.getDirectOffset() == 0) { 4245 assert(NumIRArgs == 1); 4246 llvm::Value *V; 4247 if (!I->isAggregate()) 4248 V = I->getKnownRValue().getScalarVal(); 4249 else 4250 V = Builder.CreateLoad( 4251 I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4252 : I->getKnownRValue().getAggregateAddress()); 4253 4254 // Implement swifterror by copying into a new swifterror argument. 4255 // We'll write back in the normal path out of the call. 4256 if (CallInfo.getExtParameterInfo(ArgNo).getABI() 4257 == ParameterABI::SwiftErrorResult) { 4258 assert(!swiftErrorTemp.isValid() && "multiple swifterror args"); 4259 4260 QualType pointeeTy = I->Ty->getPointeeType(); 4261 swiftErrorArg = 4262 Address(V, getContext().getTypeAlignInChars(pointeeTy)); 4263 4264 swiftErrorTemp = 4265 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 4266 V = swiftErrorTemp.getPointer(); 4267 cast<llvm::AllocaInst>(V)->setSwiftError(true); 4268 4269 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg); 4270 Builder.CreateStore(errorValue, swiftErrorTemp); 4271 } 4272 4273 // We might have to widen integers, but we should never truncate. 4274 if (ArgInfo.getCoerceToType() != V->getType() && 4275 V->getType()->isIntegerTy()) 4276 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType()); 4277 4278 // If the argument doesn't match, perform a bitcast to coerce it. This 4279 // can happen due to trivial type mismatches. 4280 if (FirstIRArg < IRFuncTy->getNumParams() && 4281 V->getType() != IRFuncTy->getParamType(FirstIRArg)) 4282 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg)); 4283 4284 IRCallArgs[FirstIRArg] = V; 4285 break; 4286 } 4287 4288 // FIXME: Avoid the conversion through memory if possible. 4289 Address Src = Address::invalid(); 4290 if (!I->isAggregate()) { 4291 Src = CreateMemTemp(I->Ty, "coerce"); 4292 I->copyInto(*this, Src); 4293 } else { 4294 Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4295 : I->getKnownRValue().getAggregateAddress(); 4296 } 4297 4298 // If the value is offset in memory, apply the offset now. 4299 Src = emitAddressAtOffset(*this, Src, ArgInfo); 4300 4301 // Fast-isel and the optimizer generally like scalar values better than 4302 // FCAs, so we flatten them if this is safe to do for this argument. 4303 llvm::StructType *STy = 4304 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType()); 4305 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 4306 llvm::Type *SrcTy = Src.getType()->getElementType(); 4307 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4308 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy); 4309 4310 // If the source type is smaller than the destination type of the 4311 // coerce-to logic, copy the source value into a temp alloca the size 4312 // of the destination type to allow loading all of it. The bits past 4313 // the source value are left undef. 4314 if (SrcSize < DstSize) { 4315 Address TempAlloca 4316 = CreateTempAlloca(STy, Src.getAlignment(), 4317 Src.getName() + ".coerce"); 4318 Builder.CreateMemCpy(TempAlloca, Src, SrcSize); 4319 Src = TempAlloca; 4320 } else { 4321 Src = Builder.CreateBitCast(Src, 4322 STy->getPointerTo(Src.getAddressSpace())); 4323 } 4324 4325 assert(NumIRArgs == STy->getNumElements()); 4326 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 4327 Address EltPtr = Builder.CreateStructGEP(Src, i); 4328 llvm::Value *LI = Builder.CreateLoad(EltPtr); 4329 IRCallArgs[FirstIRArg + i] = LI; 4330 } 4331 } else { 4332 // In the simple case, just pass the coerced loaded value. 4333 assert(NumIRArgs == 1); 4334 IRCallArgs[FirstIRArg] = 4335 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this); 4336 } 4337 4338 break; 4339 } 4340 4341 case ABIArgInfo::CoerceAndExpand: { 4342 auto coercionType = ArgInfo.getCoerceAndExpandType(); 4343 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 4344 4345 llvm::Value *tempSize = nullptr; 4346 Address addr = Address::invalid(); 4347 Address AllocaAddr = Address::invalid(); 4348 if (I->isAggregate()) { 4349 addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4350 : I->getKnownRValue().getAggregateAddress(); 4351 4352 } else { 4353 RValue RV = I->getKnownRValue(); 4354 assert(RV.isScalar()); // complex should always just be direct 4355 4356 llvm::Type *scalarType = RV.getScalarVal()->getType(); 4357 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType); 4358 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType); 4359 4360 // Materialize to a temporary. 4361 addr = CreateTempAlloca( 4362 RV.getScalarVal()->getType(), 4363 CharUnits::fromQuantity(std::max( 4364 (unsigned)layout->getAlignment().value(), scalarAlign)), 4365 "tmp", 4366 /*ArraySize=*/nullptr, &AllocaAddr); 4367 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer()); 4368 4369 Builder.CreateStore(RV.getScalarVal(), addr); 4370 } 4371 4372 addr = Builder.CreateElementBitCast(addr, coercionType); 4373 4374 unsigned IRArgPos = FirstIRArg; 4375 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4376 llvm::Type *eltType = coercionType->getElementType(i); 4377 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4378 Address eltAddr = Builder.CreateStructGEP(addr, i); 4379 llvm::Value *elt = Builder.CreateLoad(eltAddr); 4380 IRCallArgs[IRArgPos++] = elt; 4381 } 4382 assert(IRArgPos == FirstIRArg + NumIRArgs); 4383 4384 if (tempSize) { 4385 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer()); 4386 } 4387 4388 break; 4389 } 4390 4391 case ABIArgInfo::Expand: 4392 unsigned IRArgPos = FirstIRArg; 4393 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos); 4394 assert(IRArgPos == FirstIRArg + NumIRArgs); 4395 break; 4396 } 4397 } 4398 4399 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this); 4400 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer(); 4401 4402 // If we're using inalloca, set up that argument. 4403 if (ArgMemory.isValid()) { 4404 llvm::Value *Arg = ArgMemory.getPointer(); 4405 if (CallInfo.isVariadic()) { 4406 // When passing non-POD arguments by value to variadic functions, we will 4407 // end up with a variadic prototype and an inalloca call site. In such 4408 // cases, we can't do any parameter mismatch checks. Give up and bitcast 4409 // the callee. 4410 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace(); 4411 CalleePtr = 4412 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS)); 4413 } else { 4414 llvm::Type *LastParamTy = 4415 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1); 4416 if (Arg->getType() != LastParamTy) { 4417 #ifndef NDEBUG 4418 // Assert that these structs have equivalent element types. 4419 llvm::StructType *FullTy = CallInfo.getArgStruct(); 4420 llvm::StructType *DeclaredTy = cast<llvm::StructType>( 4421 cast<llvm::PointerType>(LastParamTy)->getElementType()); 4422 assert(DeclaredTy->getNumElements() == FullTy->getNumElements()); 4423 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(), 4424 DE = DeclaredTy->element_end(), 4425 FI = FullTy->element_begin(); 4426 DI != DE; ++DI, ++FI) 4427 assert(*DI == *FI); 4428 #endif 4429 Arg = Builder.CreateBitCast(Arg, LastParamTy); 4430 } 4431 } 4432 assert(IRFunctionArgs.hasInallocaArg()); 4433 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg; 4434 } 4435 4436 // 2. Prepare the function pointer. 4437 4438 // If the callee is a bitcast of a non-variadic function to have a 4439 // variadic function pointer type, check to see if we can remove the 4440 // bitcast. This comes up with unprototyped functions. 4441 // 4442 // This makes the IR nicer, but more importantly it ensures that we 4443 // can inline the function at -O0 if it is marked always_inline. 4444 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT, 4445 llvm::Value *Ptr) -> llvm::Function * { 4446 if (!CalleeFT->isVarArg()) 4447 return nullptr; 4448 4449 // Get underlying value if it's a bitcast 4450 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) { 4451 if (CE->getOpcode() == llvm::Instruction::BitCast) 4452 Ptr = CE->getOperand(0); 4453 } 4454 4455 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr); 4456 if (!OrigFn) 4457 return nullptr; 4458 4459 llvm::FunctionType *OrigFT = OrigFn->getFunctionType(); 4460 4461 // If the original type is variadic, or if any of the component types 4462 // disagree, we cannot remove the cast. 4463 if (OrigFT->isVarArg() || 4464 OrigFT->getNumParams() != CalleeFT->getNumParams() || 4465 OrigFT->getReturnType() != CalleeFT->getReturnType()) 4466 return nullptr; 4467 4468 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i) 4469 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i)) 4470 return nullptr; 4471 4472 return OrigFn; 4473 }; 4474 4475 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) { 4476 CalleePtr = OrigFn; 4477 IRFuncTy = OrigFn->getFunctionType(); 4478 } 4479 4480 // 3. Perform the actual call. 4481 4482 // Deactivate any cleanups that we're supposed to do immediately before 4483 // the call. 4484 if (!CallArgs.getCleanupsToDeactivate().empty()) 4485 deactivateArgCleanupsBeforeCall(*this, CallArgs); 4486 4487 // Assert that the arguments we computed match up. The IR verifier 4488 // will catch this, but this is a common enough source of problems 4489 // during IRGen changes that it's way better for debugging to catch 4490 // it ourselves here. 4491 #ifndef NDEBUG 4492 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()); 4493 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4494 // Inalloca argument can have different type. 4495 if (IRFunctionArgs.hasInallocaArg() && 4496 i == IRFunctionArgs.getInallocaArgNo()) 4497 continue; 4498 if (i < IRFuncTy->getNumParams()) 4499 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)); 4500 } 4501 #endif 4502 4503 // Update the largest vector width if any arguments have vector types. 4504 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4505 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType())) 4506 LargestVectorWidth = 4507 std::max((uint64_t)LargestVectorWidth, 4508 VT->getPrimitiveSizeInBits().getKnownMinSize()); 4509 } 4510 4511 // Compute the calling convention and attributes. 4512 unsigned CallingConv; 4513 llvm::AttributeList Attrs; 4514 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo, 4515 Callee.getAbstractInfo(), Attrs, CallingConv, 4516 /*AttrOnCallSite=*/true); 4517 4518 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 4519 if (FD->usesFPIntrin()) 4520 // All calls within a strictfp function are marked strictfp 4521 Attrs = 4522 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4523 llvm::Attribute::StrictFP); 4524 4525 // Apply some call-site-specific attributes. 4526 // TODO: work this into building the attribute set. 4527 4528 // Apply always_inline to all calls within flatten functions. 4529 // FIXME: should this really take priority over __try, below? 4530 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() && 4531 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) { 4532 Attrs = 4533 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4534 llvm::Attribute::AlwaysInline); 4535 } 4536 4537 // Disable inlining inside SEH __try blocks. 4538 if (isSEHTryScope()) { 4539 Attrs = 4540 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4541 llvm::Attribute::NoInline); 4542 } 4543 4544 // Decide whether to use a call or an invoke. 4545 bool CannotThrow; 4546 if (currentFunctionUsesSEHTry()) { 4547 // SEH cares about asynchronous exceptions, so everything can "throw." 4548 CannotThrow = false; 4549 } else if (isCleanupPadScope() && 4550 EHPersonality::get(*this).isMSVCXXPersonality()) { 4551 // The MSVC++ personality will implicitly terminate the program if an 4552 // exception is thrown during a cleanup outside of a try/catch. 4553 // We don't need to model anything in IR to get this behavior. 4554 CannotThrow = true; 4555 } else { 4556 // Otherwise, nounwind call sites will never throw. 4557 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex, 4558 llvm::Attribute::NoUnwind); 4559 } 4560 4561 // If we made a temporary, be sure to clean up after ourselves. Note that we 4562 // can't depend on being inside of an ExprWithCleanups, so we need to manually 4563 // pop this cleanup later on. Being eager about this is OK, since this 4564 // temporary is 'invisible' outside of the callee. 4565 if (UnusedReturnSizePtr) 4566 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca, 4567 UnusedReturnSizePtr); 4568 4569 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); 4570 4571 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4572 getBundlesForFunclet(CalleePtr); 4573 4574 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 4575 if (FD->usesFPIntrin()) 4576 // All calls within a strictfp function are marked strictfp 4577 Attrs = 4578 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4579 llvm::Attribute::StrictFP); 4580 4581 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl); 4582 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs); 4583 4584 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs); 4585 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs); 4586 4587 // Emit the actual call/invoke instruction. 4588 llvm::CallBase *CI; 4589 if (!InvokeDest) { 4590 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList); 4591 } else { 4592 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 4593 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs, 4594 BundleList); 4595 EmitBlock(Cont); 4596 } 4597 if (callOrInvoke) 4598 *callOrInvoke = CI; 4599 4600 // If this is within a function that has the guard(nocf) attribute and is an 4601 // indirect call, add the "guard_nocf" attribute to this call to indicate that 4602 // Control Flow Guard checks should not be added, even if the call is inlined. 4603 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) { 4604 if (const auto *A = FD->getAttr<CFGuardAttr>()) { 4605 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction()) 4606 Attrs = Attrs.addAttribute( 4607 getLLVMContext(), llvm::AttributeList::FunctionIndex, "guard_nocf"); 4608 } 4609 } 4610 4611 // Apply the attributes and calling convention. 4612 CI->setAttributes(Attrs); 4613 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 4614 4615 // Apply various metadata. 4616 4617 if (!CI->getType()->isVoidTy()) 4618 CI->setName("call"); 4619 4620 // Update largest vector width from the return type. 4621 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType())) 4622 LargestVectorWidth = 4623 std::max((uint64_t)LargestVectorWidth, 4624 VT->getPrimitiveSizeInBits().getKnownMinSize()); 4625 4626 // Insert instrumentation or attach profile metadata at indirect call sites. 4627 // For more details, see the comment before the definition of 4628 // IPVK_IndirectCallTarget in InstrProfData.inc. 4629 if (!CI->getCalledFunction()) 4630 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget, 4631 CI, CalleePtr); 4632 4633 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 4634 // optimizer it can aggressively ignore unwind edges. 4635 if (CGM.getLangOpts().ObjCAutoRefCount) 4636 AddObjCARCExceptionMetadata(CI); 4637 4638 // Suppress tail calls if requested. 4639 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) { 4640 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>()) 4641 Call->setTailCallKind(llvm::CallInst::TCK_NoTail); 4642 } 4643 4644 // Add metadata for calls to MSAllocator functions 4645 if (getDebugInfo() && TargetDecl && 4646 TargetDecl->hasAttr<MSAllocatorAttr>()) 4647 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc); 4648 4649 // 4. Finish the call. 4650 4651 // If the call doesn't return, finish the basic block and clear the 4652 // insertion point; this allows the rest of IRGen to discard 4653 // unreachable code. 4654 if (CI->doesNotReturn()) { 4655 if (UnusedReturnSizePtr) 4656 PopCleanupBlock(); 4657 4658 // Strip away the noreturn attribute to better diagnose unreachable UB. 4659 if (SanOpts.has(SanitizerKind::Unreachable)) { 4660 // Also remove from function since CallBase::hasFnAttr additionally checks 4661 // attributes of the called function. 4662 if (auto *F = CI->getCalledFunction()) 4663 F->removeFnAttr(llvm::Attribute::NoReturn); 4664 CI->removeAttribute(llvm::AttributeList::FunctionIndex, 4665 llvm::Attribute::NoReturn); 4666 4667 // Avoid incompatibility with ASan which relies on the `noreturn` 4668 // attribute to insert handler calls. 4669 if (SanOpts.hasOneOf(SanitizerKind::Address | 4670 SanitizerKind::KernelAddress)) { 4671 SanitizerScope SanScope(this); 4672 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder); 4673 Builder.SetInsertPoint(CI); 4674 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 4675 llvm::FunctionCallee Fn = 4676 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return"); 4677 EmitNounwindRuntimeCall(Fn); 4678 } 4679 } 4680 4681 EmitUnreachable(Loc); 4682 Builder.ClearInsertionPoint(); 4683 4684 // FIXME: For now, emit a dummy basic block because expr emitters in 4685 // generally are not ready to handle emitting expressions at unreachable 4686 // points. 4687 EnsureInsertPoint(); 4688 4689 // Return a reasonable RValue. 4690 return GetUndefRValue(RetTy); 4691 } 4692 4693 // Perform the swifterror writeback. 4694 if (swiftErrorTemp.isValid()) { 4695 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp); 4696 Builder.CreateStore(errorResult, swiftErrorArg); 4697 } 4698 4699 // Emit any call-associated writebacks immediately. Arguably this 4700 // should happen after any return-value munging. 4701 if (CallArgs.hasWritebacks()) 4702 emitWritebacks(*this, CallArgs); 4703 4704 // The stack cleanup for inalloca arguments has to run out of the normal 4705 // lexical order, so deactivate it and run it manually here. 4706 CallArgs.freeArgumentMemory(*this); 4707 4708 // Extract the return value. 4709 RValue Ret = [&] { 4710 switch (RetAI.getKind()) { 4711 case ABIArgInfo::CoerceAndExpand: { 4712 auto coercionType = RetAI.getCoerceAndExpandType(); 4713 4714 Address addr = SRetPtr; 4715 addr = Builder.CreateElementBitCast(addr, coercionType); 4716 4717 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType()); 4718 bool requiresExtract = isa<llvm::StructType>(CI->getType()); 4719 4720 unsigned unpaddedIndex = 0; 4721 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4722 llvm::Type *eltType = coercionType->getElementType(i); 4723 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4724 Address eltAddr = Builder.CreateStructGEP(addr, i); 4725 llvm::Value *elt = CI; 4726 if (requiresExtract) 4727 elt = Builder.CreateExtractValue(elt, unpaddedIndex++); 4728 else 4729 assert(unpaddedIndex == 0); 4730 Builder.CreateStore(elt, eltAddr); 4731 } 4732 // FALLTHROUGH 4733 LLVM_FALLTHROUGH; 4734 } 4735 4736 case ABIArgInfo::InAlloca: 4737 case ABIArgInfo::Indirect: { 4738 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); 4739 if (UnusedReturnSizePtr) 4740 PopCleanupBlock(); 4741 return ret; 4742 } 4743 4744 case ABIArgInfo::Ignore: 4745 // If we are ignoring an argument that had a result, make sure to 4746 // construct the appropriate return value for our caller. 4747 return GetUndefRValue(RetTy); 4748 4749 case ABIArgInfo::Extend: 4750 case ABIArgInfo::Direct: { 4751 llvm::Type *RetIRTy = ConvertType(RetTy); 4752 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 4753 switch (getEvaluationKind(RetTy)) { 4754 case TEK_Complex: { 4755 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 4756 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 4757 return RValue::getComplex(std::make_pair(Real, Imag)); 4758 } 4759 case TEK_Aggregate: { 4760 Address DestPtr = ReturnValue.getValue(); 4761 bool DestIsVolatile = ReturnValue.isVolatile(); 4762 4763 if (!DestPtr.isValid()) { 4764 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 4765 DestIsVolatile = false; 4766 } 4767 BuildAggStore(*this, CI, DestPtr, DestIsVolatile); 4768 return RValue::getAggregate(DestPtr); 4769 } 4770 case TEK_Scalar: { 4771 // If the argument doesn't match, perform a bitcast to coerce it. This 4772 // can happen due to trivial type mismatches. 4773 llvm::Value *V = CI; 4774 if (V->getType() != RetIRTy) 4775 V = Builder.CreateBitCast(V, RetIRTy); 4776 return RValue::get(V); 4777 } 4778 } 4779 llvm_unreachable("bad evaluation kind"); 4780 } 4781 4782 Address DestPtr = ReturnValue.getValue(); 4783 bool DestIsVolatile = ReturnValue.isVolatile(); 4784 4785 if (!DestPtr.isValid()) { 4786 DestPtr = CreateMemTemp(RetTy, "coerce"); 4787 DestIsVolatile = false; 4788 } 4789 4790 // If the value is offset in memory, apply the offset now. 4791 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI); 4792 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 4793 4794 return convertTempToRValue(DestPtr, RetTy, SourceLocation()); 4795 } 4796 4797 case ABIArgInfo::Expand: 4798 llvm_unreachable("Invalid ABI kind for return argument"); 4799 } 4800 4801 llvm_unreachable("Unhandled ABIArgInfo::Kind"); 4802 } (); 4803 4804 // Emit the assume_aligned check on the return value. 4805 if (Ret.isScalar() && TargetDecl) { 4806 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret); 4807 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret); 4808 } 4809 4810 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though 4811 // we can't use the full cleanup mechanism. 4812 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall) 4813 LifetimeEnd.Emit(*this, /*Flags=*/{}); 4814 4815 if (!ReturnValue.isExternallyDestructed() && 4816 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct) 4817 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(), 4818 RetTy); 4819 4820 return Ret; 4821 } 4822 4823 CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const { 4824 if (isVirtual()) { 4825 const CallExpr *CE = getVirtualCallExpr(); 4826 return CGF.CGM.getCXXABI().getVirtualFunctionPointer( 4827 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(), 4828 CE ? CE->getBeginLoc() : SourceLocation()); 4829 } 4830 4831 return *this; 4832 } 4833 4834 /* VarArg handling */ 4835 4836 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) { 4837 VAListAddr = VE->isMicrosoftABI() 4838 ? EmitMSVAListRef(VE->getSubExpr()) 4839 : EmitVAListRef(VE->getSubExpr()); 4840 QualType Ty = VE->getType(); 4841 if (VE->isMicrosoftABI()) 4842 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty); 4843 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty); 4844 } 4845