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