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 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty); 1266 Address SrcCasted = CGF.Builder.CreateElementBitCast(Src,CGF.Int8Ty); 1267 CGF.Builder.CreateMemCpy(Casted, SrcCasted, 1268 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize), 1269 false); 1270 return CGF.Builder.CreateLoad(Tmp); 1271 } 1272 1273 // Function to store a first-class aggregate into memory. We prefer to 1274 // store the elements rather than the aggregate to be more friendly to 1275 // fast-isel. 1276 // FIXME: Do we need to recurse here? 1277 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val, 1278 Address Dest, bool DestIsVolatile) { 1279 // Prefer scalar stores to first-class aggregate stores. 1280 if (llvm::StructType *STy = 1281 dyn_cast<llvm::StructType>(Val->getType())) { 1282 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1283 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i); 1284 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i); 1285 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile); 1286 } 1287 } else { 1288 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile); 1289 } 1290 } 1291 1292 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 1293 /// where the source and destination may have different types. The 1294 /// destination is known to be aligned to \arg DstAlign bytes. 1295 /// 1296 /// This safely handles the case when the src type is larger than the 1297 /// destination type; the upper bits of the src will be lost. 1298 static void CreateCoercedStore(llvm::Value *Src, 1299 Address Dst, 1300 bool DstIsVolatile, 1301 CodeGenFunction &CGF) { 1302 llvm::Type *SrcTy = Src->getType(); 1303 llvm::Type *DstTy = Dst.getElementType(); 1304 if (SrcTy == DstTy) { 1305 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1306 return; 1307 } 1308 1309 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1310 1311 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) { 1312 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF); 1313 DstTy = Dst.getElementType(); 1314 } 1315 1316 llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy); 1317 llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy); 1318 if (SrcPtrTy && DstPtrTy && 1319 SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) { 1320 Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy); 1321 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1322 return; 1323 } 1324 1325 // If the source and destination are integer or pointer types, just do an 1326 // extension or truncation to the desired type. 1327 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) && 1328 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) { 1329 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF); 1330 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1331 return; 1332 } 1333 1334 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy); 1335 1336 // If store is legal, just bitcast the src pointer. 1337 if (SrcSize <= DstSize) { 1338 Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy); 1339 BuildAggStore(CGF, Src, Dst, DstIsVolatile); 1340 } else { 1341 // Otherwise do coercion through memory. This is stupid, but 1342 // simple. 1343 1344 // Generally SrcSize is never greater than DstSize, since this means we are 1345 // losing bits. However, this can happen in cases where the structure has 1346 // additional padding, for example due to a user specified alignment. 1347 // 1348 // FIXME: Assert that we aren't truncating non-padding bits when have access 1349 // to that information. 1350 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment()); 1351 CGF.Builder.CreateStore(Src, Tmp); 1352 Address Casted = CGF.Builder.CreateElementBitCast(Tmp,CGF.Int8Ty); 1353 Address DstCasted = CGF.Builder.CreateElementBitCast(Dst,CGF.Int8Ty); 1354 CGF.Builder.CreateMemCpy(DstCasted, Casted, 1355 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize), 1356 false); 1357 } 1358 } 1359 1360 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, 1361 const ABIArgInfo &info) { 1362 if (unsigned offset = info.getDirectOffset()) { 1363 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty); 1364 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr, 1365 CharUnits::fromQuantity(offset)); 1366 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType()); 1367 } 1368 return addr; 1369 } 1370 1371 namespace { 1372 1373 /// Encapsulates information about the way function arguments from 1374 /// CGFunctionInfo should be passed to actual LLVM IR function. 1375 class ClangToLLVMArgMapping { 1376 static const unsigned InvalidIndex = ~0U; 1377 unsigned InallocaArgNo; 1378 unsigned SRetArgNo; 1379 unsigned TotalIRArgs; 1380 1381 /// Arguments of LLVM IR function corresponding to single Clang argument. 1382 struct IRArgs { 1383 unsigned PaddingArgIndex; 1384 // Argument is expanded to IR arguments at positions 1385 // [FirstArgIndex, FirstArgIndex + NumberOfArgs). 1386 unsigned FirstArgIndex; 1387 unsigned NumberOfArgs; 1388 1389 IRArgs() 1390 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex), 1391 NumberOfArgs(0) {} 1392 }; 1393 1394 SmallVector<IRArgs, 8> ArgInfo; 1395 1396 public: 1397 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI, 1398 bool OnlyRequiredArgs = false) 1399 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0), 1400 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) { 1401 construct(Context, FI, OnlyRequiredArgs); 1402 } 1403 1404 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; } 1405 unsigned getInallocaArgNo() const { 1406 assert(hasInallocaArg()); 1407 return InallocaArgNo; 1408 } 1409 1410 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; } 1411 unsigned getSRetArgNo() const { 1412 assert(hasSRetArg()); 1413 return SRetArgNo; 1414 } 1415 1416 unsigned totalIRArgs() const { return TotalIRArgs; } 1417 1418 bool hasPaddingArg(unsigned ArgNo) const { 1419 assert(ArgNo < ArgInfo.size()); 1420 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex; 1421 } 1422 unsigned getPaddingArgNo(unsigned ArgNo) const { 1423 assert(hasPaddingArg(ArgNo)); 1424 return ArgInfo[ArgNo].PaddingArgIndex; 1425 } 1426 1427 /// Returns index of first IR argument corresponding to ArgNo, and their 1428 /// quantity. 1429 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const { 1430 assert(ArgNo < ArgInfo.size()); 1431 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex, 1432 ArgInfo[ArgNo].NumberOfArgs); 1433 } 1434 1435 private: 1436 void construct(const ASTContext &Context, const CGFunctionInfo &FI, 1437 bool OnlyRequiredArgs); 1438 }; 1439 1440 void ClangToLLVMArgMapping::construct(const ASTContext &Context, 1441 const CGFunctionInfo &FI, 1442 bool OnlyRequiredArgs) { 1443 unsigned IRArgNo = 0; 1444 bool SwapThisWithSRet = false; 1445 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1446 1447 if (RetAI.getKind() == ABIArgInfo::Indirect) { 1448 SwapThisWithSRet = RetAI.isSRetAfterThis(); 1449 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++; 1450 } 1451 1452 unsigned ArgNo = 0; 1453 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size(); 1454 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs; 1455 ++I, ++ArgNo) { 1456 assert(I != FI.arg_end()); 1457 QualType ArgType = I->type; 1458 const ABIArgInfo &AI = I->info; 1459 // Collect data about IR arguments corresponding to Clang argument ArgNo. 1460 auto &IRArgs = ArgInfo[ArgNo]; 1461 1462 if (AI.getPaddingType()) 1463 IRArgs.PaddingArgIndex = IRArgNo++; 1464 1465 switch (AI.getKind()) { 1466 case ABIArgInfo::Extend: 1467 case ABIArgInfo::Direct: { 1468 // FIXME: handle sseregparm someday... 1469 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType()); 1470 if (AI.isDirect() && AI.getCanBeFlattened() && STy) { 1471 IRArgs.NumberOfArgs = STy->getNumElements(); 1472 } else { 1473 IRArgs.NumberOfArgs = 1; 1474 } 1475 break; 1476 } 1477 case ABIArgInfo::Indirect: 1478 IRArgs.NumberOfArgs = 1; 1479 break; 1480 case ABIArgInfo::Ignore: 1481 case ABIArgInfo::InAlloca: 1482 // ignore and inalloca doesn't have matching LLVM parameters. 1483 IRArgs.NumberOfArgs = 0; 1484 break; 1485 case ABIArgInfo::CoerceAndExpand: 1486 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size(); 1487 break; 1488 case ABIArgInfo::Expand: 1489 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context); 1490 break; 1491 } 1492 1493 if (IRArgs.NumberOfArgs > 0) { 1494 IRArgs.FirstArgIndex = IRArgNo; 1495 IRArgNo += IRArgs.NumberOfArgs; 1496 } 1497 1498 // Skip over the sret parameter when it comes second. We already handled it 1499 // above. 1500 if (IRArgNo == 1 && SwapThisWithSRet) 1501 IRArgNo++; 1502 } 1503 assert(ArgNo == ArgInfo.size()); 1504 1505 if (FI.usesInAlloca()) 1506 InallocaArgNo = IRArgNo++; 1507 1508 TotalIRArgs = IRArgNo; 1509 } 1510 } // namespace 1511 1512 /***/ 1513 1514 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) { 1515 const auto &RI = FI.getReturnInfo(); 1516 return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet()); 1517 } 1518 1519 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) { 1520 return ReturnTypeUsesSRet(FI) && 1521 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs(); 1522 } 1523 1524 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) { 1525 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) { 1526 switch (BT->getKind()) { 1527 default: 1528 return false; 1529 case BuiltinType::Float: 1530 return getTarget().useObjCFPRetForRealType(TargetInfo::Float); 1531 case BuiltinType::Double: 1532 return getTarget().useObjCFPRetForRealType(TargetInfo::Double); 1533 case BuiltinType::LongDouble: 1534 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble); 1535 } 1536 } 1537 1538 return false; 1539 } 1540 1541 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) { 1542 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) { 1543 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) { 1544 if (BT->getKind() == BuiltinType::LongDouble) 1545 return getTarget().useObjCFP2RetForComplexLongDouble(); 1546 } 1547 } 1548 1549 return false; 1550 } 1551 1552 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) { 1553 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD); 1554 return GetFunctionType(FI); 1555 } 1556 1557 llvm::FunctionType * 1558 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) { 1559 1560 bool Inserted = FunctionsBeingProcessed.insert(&FI).second; 1561 (void)Inserted; 1562 assert(Inserted && "Recursively being processed?"); 1563 1564 llvm::Type *resultType = nullptr; 1565 const ABIArgInfo &retAI = FI.getReturnInfo(); 1566 switch (retAI.getKind()) { 1567 case ABIArgInfo::Expand: 1568 llvm_unreachable("Invalid ABI kind for return argument"); 1569 1570 case ABIArgInfo::Extend: 1571 case ABIArgInfo::Direct: 1572 resultType = retAI.getCoerceToType(); 1573 break; 1574 1575 case ABIArgInfo::InAlloca: 1576 if (retAI.getInAllocaSRet()) { 1577 // sret things on win32 aren't void, they return the sret pointer. 1578 QualType ret = FI.getReturnType(); 1579 llvm::Type *ty = ConvertType(ret); 1580 unsigned addressSpace = Context.getTargetAddressSpace(ret); 1581 resultType = llvm::PointerType::get(ty, addressSpace); 1582 } else { 1583 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1584 } 1585 break; 1586 1587 case ABIArgInfo::Indirect: 1588 case ABIArgInfo::Ignore: 1589 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1590 break; 1591 1592 case ABIArgInfo::CoerceAndExpand: 1593 resultType = retAI.getUnpaddedCoerceAndExpandType(); 1594 break; 1595 } 1596 1597 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true); 1598 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs()); 1599 1600 // Add type for sret argument. 1601 if (IRFunctionArgs.hasSRetArg()) { 1602 QualType Ret = FI.getReturnType(); 1603 llvm::Type *Ty = ConvertType(Ret); 1604 unsigned AddressSpace = Context.getTargetAddressSpace(Ret); 1605 ArgTypes[IRFunctionArgs.getSRetArgNo()] = 1606 llvm::PointerType::get(Ty, AddressSpace); 1607 } 1608 1609 // Add type for inalloca argument. 1610 if (IRFunctionArgs.hasInallocaArg()) { 1611 auto ArgStruct = FI.getArgStruct(); 1612 assert(ArgStruct); 1613 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo(); 1614 } 1615 1616 // Add in all of the required arguments. 1617 unsigned ArgNo = 0; 1618 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 1619 ie = it + FI.getNumRequiredArgs(); 1620 for (; it != ie; ++it, ++ArgNo) { 1621 const ABIArgInfo &ArgInfo = it->info; 1622 1623 // Insert a padding type to ensure proper alignment. 1624 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 1625 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 1626 ArgInfo.getPaddingType(); 1627 1628 unsigned FirstIRArg, NumIRArgs; 1629 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1630 1631 switch (ArgInfo.getKind()) { 1632 case ABIArgInfo::Ignore: 1633 case ABIArgInfo::InAlloca: 1634 assert(NumIRArgs == 0); 1635 break; 1636 1637 case ABIArgInfo::Indirect: { 1638 assert(NumIRArgs == 1); 1639 // indirect arguments are always on the stack, which is alloca addr space. 1640 llvm::Type *LTy = ConvertTypeForMem(it->type); 1641 ArgTypes[FirstIRArg] = LTy->getPointerTo( 1642 CGM.getDataLayout().getAllocaAddrSpace()); 1643 break; 1644 } 1645 1646 case ABIArgInfo::Extend: 1647 case ABIArgInfo::Direct: { 1648 // Fast-isel and the optimizer generally like scalar values better than 1649 // FCAs, so we flatten them if this is safe to do for this argument. 1650 llvm::Type *argType = ArgInfo.getCoerceToType(); 1651 llvm::StructType *st = dyn_cast<llvm::StructType>(argType); 1652 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 1653 assert(NumIRArgs == st->getNumElements()); 1654 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i) 1655 ArgTypes[FirstIRArg + i] = st->getElementType(i); 1656 } else { 1657 assert(NumIRArgs == 1); 1658 ArgTypes[FirstIRArg] = argType; 1659 } 1660 break; 1661 } 1662 1663 case ABIArgInfo::CoerceAndExpand: { 1664 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1665 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) { 1666 *ArgTypesIter++ = EltTy; 1667 } 1668 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1669 break; 1670 } 1671 1672 case ABIArgInfo::Expand: 1673 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1674 getExpandedTypes(it->type, ArgTypesIter); 1675 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1676 break; 1677 } 1678 } 1679 1680 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased; 1681 assert(Erased && "Not in set?"); 1682 1683 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic()); 1684 } 1685 1686 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { 1687 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1688 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1689 1690 if (!isFuncTypeConvertible(FPT)) 1691 return llvm::StructType::get(getLLVMContext()); 1692 1693 return GetFunctionType(GD); 1694 } 1695 1696 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, 1697 llvm::AttrBuilder &FuncAttrs, 1698 const FunctionProtoType *FPT) { 1699 if (!FPT) 1700 return; 1701 1702 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 1703 FPT->isNothrow()) 1704 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1705 } 1706 1707 void CodeGenModule::ConstructDefaultFnAttrList(StringRef Name, bool HasOptnone, 1708 bool AttrOnCallSite, 1709 llvm::AttrBuilder &FuncAttrs) { 1710 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed. 1711 if (!HasOptnone) { 1712 if (CodeGenOpts.OptimizeSize) 1713 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize); 1714 if (CodeGenOpts.OptimizeSize == 2) 1715 FuncAttrs.addAttribute(llvm::Attribute::MinSize); 1716 } 1717 1718 if (CodeGenOpts.DisableRedZone) 1719 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone); 1720 if (CodeGenOpts.IndirectTlsSegRefs) 1721 FuncAttrs.addAttribute("indirect-tls-seg-refs"); 1722 if (CodeGenOpts.NoImplicitFloat) 1723 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat); 1724 1725 if (AttrOnCallSite) { 1726 // Attributes that should go on the call site only. 1727 if (!CodeGenOpts.SimplifyLibCalls || 1728 CodeGenOpts.isNoBuiltinFunc(Name.data())) 1729 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin); 1730 if (!CodeGenOpts.TrapFuncName.empty()) 1731 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName); 1732 } else { 1733 StringRef FpKind; 1734 switch (CodeGenOpts.getFramePointer()) { 1735 case CodeGenOptions::FramePointerKind::None: 1736 FpKind = "none"; 1737 break; 1738 case CodeGenOptions::FramePointerKind::NonLeaf: 1739 FpKind = "non-leaf"; 1740 break; 1741 case CodeGenOptions::FramePointerKind::All: 1742 FpKind = "all"; 1743 break; 1744 } 1745 FuncAttrs.addAttribute("frame-pointer", FpKind); 1746 1747 FuncAttrs.addAttribute("less-precise-fpmad", 1748 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD)); 1749 1750 if (CodeGenOpts.NullPointerIsValid) 1751 FuncAttrs.addAttribute("null-pointer-is-valid", "true"); 1752 1753 if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE()) 1754 FuncAttrs.addAttribute("denormal-fp-math", 1755 CodeGenOpts.FPDenormalMode.str()); 1756 if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) { 1757 FuncAttrs.addAttribute( 1758 "denormal-fp-math-f32", 1759 CodeGenOpts.FP32DenormalMode.str()); 1760 } 1761 1762 FuncAttrs.addAttribute("no-trapping-math", 1763 llvm::toStringRef(CodeGenOpts.NoTrappingMath)); 1764 1765 // Strict (compliant) code is the default, so only add this attribute to 1766 // indicate that we are trying to workaround a problem case. 1767 if (!CodeGenOpts.StrictFloatCastOverflow) 1768 FuncAttrs.addAttribute("strict-float-cast-overflow", "false"); 1769 1770 // TODO: Are these all needed? 1771 // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags. 1772 FuncAttrs.addAttribute("no-infs-fp-math", 1773 llvm::toStringRef(CodeGenOpts.NoInfsFPMath)); 1774 FuncAttrs.addAttribute("no-nans-fp-math", 1775 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath)); 1776 FuncAttrs.addAttribute("unsafe-fp-math", 1777 llvm::toStringRef(CodeGenOpts.UnsafeFPMath)); 1778 FuncAttrs.addAttribute("use-soft-float", 1779 llvm::toStringRef(CodeGenOpts.SoftFloat)); 1780 FuncAttrs.addAttribute("stack-protector-buffer-size", 1781 llvm::utostr(CodeGenOpts.SSPBufferSize)); 1782 FuncAttrs.addAttribute("no-signed-zeros-fp-math", 1783 llvm::toStringRef(CodeGenOpts.NoSignedZeros)); 1784 FuncAttrs.addAttribute( 1785 "correctly-rounded-divide-sqrt-fp-math", 1786 llvm::toStringRef(CodeGenOpts.CorrectlyRoundedDivSqrt)); 1787 1788 // TODO: Reciprocal estimate codegen options should apply to instructions? 1789 const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals; 1790 if (!Recips.empty()) 1791 FuncAttrs.addAttribute("reciprocal-estimates", 1792 llvm::join(Recips, ",")); 1793 1794 if (!CodeGenOpts.PreferVectorWidth.empty() && 1795 CodeGenOpts.PreferVectorWidth != "none") 1796 FuncAttrs.addAttribute("prefer-vector-width", 1797 CodeGenOpts.PreferVectorWidth); 1798 1799 if (CodeGenOpts.StackRealignment) 1800 FuncAttrs.addAttribute("stackrealign"); 1801 if (CodeGenOpts.Backchain) 1802 FuncAttrs.addAttribute("backchain"); 1803 1804 if (CodeGenOpts.SpeculativeLoadHardening) 1805 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening); 1806 } 1807 1808 if (getLangOpts().assumeFunctionsAreConvergent()) { 1809 // Conservatively, mark all functions and calls in CUDA and OpenCL as 1810 // convergent (meaning, they may call an intrinsically convergent op, such 1811 // as __syncthreads() / barrier(), and so can't have certain optimizations 1812 // applied around them). LLVM will remove this attribute where it safely 1813 // can. 1814 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1815 } 1816 1817 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 1818 // Exceptions aren't supported in CUDA device code. 1819 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1820 } 1821 1822 for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) { 1823 StringRef Var, Value; 1824 std::tie(Var, Value) = Attr.split('='); 1825 FuncAttrs.addAttribute(Var, Value); 1826 } 1827 } 1828 1829 void CodeGenModule::AddDefaultFnAttrs(llvm::Function &F) { 1830 llvm::AttrBuilder FuncAttrs; 1831 ConstructDefaultFnAttrList(F.getName(), F.hasOptNone(), 1832 /* AttrOnCallSite = */ false, FuncAttrs); 1833 F.addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs); 1834 } 1835 1836 static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs, 1837 const LangOptions &LangOpts, 1838 const NoBuiltinAttr *NBA = nullptr) { 1839 auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) { 1840 SmallString<32> AttributeName; 1841 AttributeName += "no-builtin-"; 1842 AttributeName += BuiltinName; 1843 FuncAttrs.addAttribute(AttributeName); 1844 }; 1845 1846 // First, handle the language options passed through -fno-builtin. 1847 if (LangOpts.NoBuiltin) { 1848 // -fno-builtin disables them all. 1849 FuncAttrs.addAttribute("no-builtins"); 1850 return; 1851 } 1852 1853 // Then, add attributes for builtins specified through -fno-builtin-<name>. 1854 llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr); 1855 1856 // Now, let's check the __attribute__((no_builtin("...")) attribute added to 1857 // the source. 1858 if (!NBA) 1859 return; 1860 1861 // If there is a wildcard in the builtin names specified through the 1862 // attribute, disable them all. 1863 if (llvm::is_contained(NBA->builtinNames(), "*")) { 1864 FuncAttrs.addAttribute("no-builtins"); 1865 return; 1866 } 1867 1868 // And last, add the rest of the builtin names. 1869 llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr); 1870 } 1871 1872 void CodeGenModule::ConstructAttributeList( 1873 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo, 1874 llvm::AttributeList &AttrList, unsigned &CallingConv, bool AttrOnCallSite) { 1875 llvm::AttrBuilder FuncAttrs; 1876 llvm::AttrBuilder RetAttrs; 1877 1878 CallingConv = FI.getEffectiveCallingConvention(); 1879 if (FI.isNoReturn()) 1880 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1881 1882 if (FI.isCmseNSCall()) 1883 FuncAttrs.addAttribute("cmse_nonsecure_call"); 1884 1885 // If we have information about the function prototype, we can learn 1886 // attributes from there. 1887 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs, 1888 CalleeInfo.getCalleeFunctionProtoType()); 1889 1890 const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl(); 1891 1892 bool HasOptnone = false; 1893 // The NoBuiltinAttr attached to a TargetDecl (only allowed on FunctionDecls). 1894 const NoBuiltinAttr *NBA = nullptr; 1895 // FIXME: handle sseregparm someday... 1896 if (TargetDecl) { 1897 if (TargetDecl->hasAttr<ReturnsTwiceAttr>()) 1898 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice); 1899 if (TargetDecl->hasAttr<NoThrowAttr>()) 1900 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1901 if (TargetDecl->hasAttr<NoReturnAttr>()) 1902 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1903 if (TargetDecl->hasAttr<ColdAttr>()) 1904 FuncAttrs.addAttribute(llvm::Attribute::Cold); 1905 if (TargetDecl->hasAttr<NoDuplicateAttr>()) 1906 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate); 1907 if (TargetDecl->hasAttr<ConvergentAttr>()) 1908 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1909 1910 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 1911 AddAttributesFromFunctionProtoType( 1912 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>()); 1913 if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) { 1914 // A sane operator new returns a non-aliasing pointer. 1915 auto Kind = Fn->getDeclName().getCXXOverloadedOperator(); 1916 if (getCodeGenOpts().AssumeSaneOperatorNew && 1917 (Kind == OO_New || Kind == OO_Array_New)) 1918 RetAttrs.addAttribute(llvm::Attribute::NoAlias); 1919 } 1920 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn); 1921 const bool IsVirtualCall = MD && MD->isVirtual(); 1922 // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a 1923 // virtual function. These attributes are not inherited by overloads. 1924 if (!(AttrOnCallSite && IsVirtualCall)) { 1925 if (Fn->isNoReturn()) 1926 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1927 NBA = Fn->getAttr<NoBuiltinAttr>(); 1928 } 1929 } 1930 1931 // 'const', 'pure' and 'noalias' attributed functions are also nounwind. 1932 if (TargetDecl->hasAttr<ConstAttr>()) { 1933 FuncAttrs.addAttribute(llvm::Attribute::ReadNone); 1934 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1935 } else if (TargetDecl->hasAttr<PureAttr>()) { 1936 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly); 1937 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1938 } else if (TargetDecl->hasAttr<NoAliasAttr>()) { 1939 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly); 1940 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1941 } 1942 if (TargetDecl->hasAttr<RestrictAttr>()) 1943 RetAttrs.addAttribute(llvm::Attribute::NoAlias); 1944 if (TargetDecl->hasAttr<ReturnsNonNullAttr>() && 1945 !CodeGenOpts.NullPointerIsValid) 1946 RetAttrs.addAttribute(llvm::Attribute::NonNull); 1947 if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>()) 1948 FuncAttrs.addAttribute("no_caller_saved_registers"); 1949 if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>()) 1950 FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck); 1951 1952 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>(); 1953 if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) { 1954 Optional<unsigned> NumElemsParam; 1955 if (AllocSize->getNumElemsParam().isValid()) 1956 NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex(); 1957 FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(), 1958 NumElemsParam); 1959 } 1960 } 1961 1962 // Attach "no-builtins" attributes to: 1963 // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>". 1964 // * definitions: "no-builtins" or "no-builtin-<name>" only. 1965 // The attributes can come from: 1966 // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name> 1967 // * FunctionDecl attributes: __attribute__((no_builtin(...))) 1968 addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA); 1969 1970 ConstructDefaultFnAttrList(Name, HasOptnone, AttrOnCallSite, FuncAttrs); 1971 1972 // This must run after constructing the default function attribute list 1973 // to ensure that the speculative load hardening attribute is removed 1974 // in the case where the -mspeculative-load-hardening flag was passed. 1975 if (TargetDecl) { 1976 if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>()) 1977 FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening); 1978 if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>()) 1979 FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening); 1980 } 1981 1982 if (CodeGenOpts.EnableSegmentedStacks && 1983 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>())) 1984 FuncAttrs.addAttribute("split-stack"); 1985 1986 // Add NonLazyBind attribute to function declarations when -fno-plt 1987 // is used. 1988 if (TargetDecl && CodeGenOpts.NoPLT) { 1989 if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 1990 if (!Fn->isDefined() && !AttrOnCallSite) { 1991 FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind); 1992 } 1993 } 1994 } 1995 1996 if (TargetDecl && TargetDecl->hasAttr<OpenCLKernelAttr>()) { 1997 if (getLangOpts().OpenCLVersion <= 120) { 1998 // OpenCL v1.2 Work groups are always uniform 1999 FuncAttrs.addAttribute("uniform-work-group-size", "true"); 2000 } else { 2001 // OpenCL v2.0 Work groups may be whether uniform or not. 2002 // '-cl-uniform-work-group-size' compile option gets a hint 2003 // to the compiler that the global work-size be a multiple of 2004 // the work-group size specified to clEnqueueNDRangeKernel 2005 // (i.e. work groups are uniform). 2006 FuncAttrs.addAttribute("uniform-work-group-size", 2007 llvm::toStringRef(CodeGenOpts.UniformWGSize)); 2008 } 2009 } 2010 2011 if (!AttrOnCallSite) { 2012 if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>()) 2013 FuncAttrs.addAttribute("cmse_nonsecure_entry"); 2014 2015 bool DisableTailCalls = false; 2016 2017 if (CodeGenOpts.DisableTailCalls) 2018 DisableTailCalls = true; 2019 else if (TargetDecl) { 2020 if (TargetDecl->hasAttr<DisableTailCallsAttr>() || 2021 TargetDecl->hasAttr<AnyX86InterruptAttr>()) 2022 DisableTailCalls = true; 2023 else if (CodeGenOpts.NoEscapingBlockTailCalls) { 2024 if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl)) 2025 if (!BD->doesNotEscape()) 2026 DisableTailCalls = true; 2027 } 2028 } 2029 2030 FuncAttrs.addAttribute("disable-tail-calls", 2031 llvm::toStringRef(DisableTailCalls)); 2032 GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs); 2033 } 2034 2035 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI); 2036 2037 QualType RetTy = FI.getReturnType(); 2038 const ABIArgInfo &RetAI = FI.getReturnInfo(); 2039 switch (RetAI.getKind()) { 2040 case ABIArgInfo::Extend: 2041 if (RetAI.isSignExt()) 2042 RetAttrs.addAttribute(llvm::Attribute::SExt); 2043 else 2044 RetAttrs.addAttribute(llvm::Attribute::ZExt); 2045 LLVM_FALLTHROUGH; 2046 case ABIArgInfo::Direct: 2047 if (RetAI.getInReg()) 2048 RetAttrs.addAttribute(llvm::Attribute::InReg); 2049 break; 2050 case ABIArgInfo::Ignore: 2051 break; 2052 2053 case ABIArgInfo::InAlloca: 2054 case ABIArgInfo::Indirect: { 2055 // inalloca and sret disable readnone and readonly 2056 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2057 .removeAttribute(llvm::Attribute::ReadNone); 2058 break; 2059 } 2060 2061 case ABIArgInfo::CoerceAndExpand: 2062 break; 2063 2064 case ABIArgInfo::Expand: 2065 llvm_unreachable("Invalid ABI kind for return argument"); 2066 } 2067 2068 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) { 2069 QualType PTy = RefTy->getPointeeType(); 2070 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 2071 RetAttrs.addDereferenceableAttr( 2072 getMinimumObjectSize(PTy).getQuantity()); 2073 else if (getContext().getTargetAddressSpace(PTy) == 0 && 2074 !CodeGenOpts.NullPointerIsValid) 2075 RetAttrs.addAttribute(llvm::Attribute::NonNull); 2076 } 2077 2078 bool hasUsedSRet = false; 2079 SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs()); 2080 2081 // Attach attributes to sret. 2082 if (IRFunctionArgs.hasSRetArg()) { 2083 llvm::AttrBuilder SRETAttrs; 2084 SRETAttrs.addAttribute(llvm::Attribute::StructRet); 2085 hasUsedSRet = true; 2086 if (RetAI.getInReg()) 2087 SRETAttrs.addAttribute(llvm::Attribute::InReg); 2088 SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity()); 2089 ArgAttrs[IRFunctionArgs.getSRetArgNo()] = 2090 llvm::AttributeSet::get(getLLVMContext(), SRETAttrs); 2091 } 2092 2093 // Attach attributes to inalloca argument. 2094 if (IRFunctionArgs.hasInallocaArg()) { 2095 llvm::AttrBuilder Attrs; 2096 Attrs.addAttribute(llvm::Attribute::InAlloca); 2097 ArgAttrs[IRFunctionArgs.getInallocaArgNo()] = 2098 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2099 } 2100 2101 unsigned ArgNo = 0; 2102 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(), 2103 E = FI.arg_end(); 2104 I != E; ++I, ++ArgNo) { 2105 QualType ParamType = I->type; 2106 const ABIArgInfo &AI = I->info; 2107 llvm::AttrBuilder Attrs; 2108 2109 // Add attribute for padding argument, if necessary. 2110 if (IRFunctionArgs.hasPaddingArg(ArgNo)) { 2111 if (AI.getPaddingInReg()) { 2112 ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 2113 llvm::AttributeSet::get( 2114 getLLVMContext(), 2115 llvm::AttrBuilder().addAttribute(llvm::Attribute::InReg)); 2116 } 2117 } 2118 2119 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 2120 // have the corresponding parameter variable. It doesn't make 2121 // sense to do it here because parameters are so messed up. 2122 switch (AI.getKind()) { 2123 case ABIArgInfo::Extend: 2124 if (AI.isSignExt()) 2125 Attrs.addAttribute(llvm::Attribute::SExt); 2126 else 2127 Attrs.addAttribute(llvm::Attribute::ZExt); 2128 LLVM_FALLTHROUGH; 2129 case ABIArgInfo::Direct: 2130 if (ArgNo == 0 && FI.isChainCall()) 2131 Attrs.addAttribute(llvm::Attribute::Nest); 2132 else if (AI.getInReg()) 2133 Attrs.addAttribute(llvm::Attribute::InReg); 2134 break; 2135 2136 case ABIArgInfo::Indirect: { 2137 if (AI.getInReg()) 2138 Attrs.addAttribute(llvm::Attribute::InReg); 2139 2140 if (AI.getIndirectByVal()) 2141 Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType)); 2142 2143 CharUnits Align = AI.getIndirectAlign(); 2144 2145 // In a byval argument, it is important that the required 2146 // alignment of the type is honored, as LLVM might be creating a 2147 // *new* stack object, and needs to know what alignment to give 2148 // it. (Sometimes it can deduce a sensible alignment on its own, 2149 // but not if clang decides it must emit a packed struct, or the 2150 // user specifies increased alignment requirements.) 2151 // 2152 // This is different from indirect *not* byval, where the object 2153 // exists already, and the align attribute is purely 2154 // informative. 2155 assert(!Align.isZero()); 2156 2157 // For now, only add this when we have a byval argument. 2158 // TODO: be less lazy about updating test cases. 2159 if (AI.getIndirectByVal()) 2160 Attrs.addAlignmentAttr(Align.getQuantity()); 2161 2162 // byval disables readnone and readonly. 2163 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2164 .removeAttribute(llvm::Attribute::ReadNone); 2165 break; 2166 } 2167 case ABIArgInfo::Ignore: 2168 case ABIArgInfo::Expand: 2169 case ABIArgInfo::CoerceAndExpand: 2170 break; 2171 2172 case ABIArgInfo::InAlloca: 2173 // inalloca disables readnone and readonly. 2174 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 2175 .removeAttribute(llvm::Attribute::ReadNone); 2176 continue; 2177 } 2178 2179 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) { 2180 QualType PTy = RefTy->getPointeeType(); 2181 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 2182 Attrs.addDereferenceableAttr( 2183 getMinimumObjectSize(PTy).getQuantity()); 2184 else if (getContext().getTargetAddressSpace(PTy) == 0 && 2185 !CodeGenOpts.NullPointerIsValid) 2186 Attrs.addAttribute(llvm::Attribute::NonNull); 2187 } 2188 2189 switch (FI.getExtParameterInfo(ArgNo).getABI()) { 2190 case ParameterABI::Ordinary: 2191 break; 2192 2193 case ParameterABI::SwiftIndirectResult: { 2194 // Add 'sret' if we haven't already used it for something, but 2195 // only if the result is void. 2196 if (!hasUsedSRet && RetTy->isVoidType()) { 2197 Attrs.addAttribute(llvm::Attribute::StructRet); 2198 hasUsedSRet = true; 2199 } 2200 2201 // Add 'noalias' in either case. 2202 Attrs.addAttribute(llvm::Attribute::NoAlias); 2203 2204 // Add 'dereferenceable' and 'alignment'. 2205 auto PTy = ParamType->getPointeeType(); 2206 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) { 2207 auto info = getContext().getTypeInfoInChars(PTy); 2208 Attrs.addDereferenceableAttr(info.first.getQuantity()); 2209 Attrs.addAttribute(llvm::Attribute::getWithAlignment( 2210 getLLVMContext(), info.second.getAsAlign())); 2211 } 2212 break; 2213 } 2214 2215 case ParameterABI::SwiftErrorResult: 2216 Attrs.addAttribute(llvm::Attribute::SwiftError); 2217 break; 2218 2219 case ParameterABI::SwiftContext: 2220 Attrs.addAttribute(llvm::Attribute::SwiftSelf); 2221 break; 2222 } 2223 2224 if (FI.getExtParameterInfo(ArgNo).isNoEscape()) 2225 Attrs.addAttribute(llvm::Attribute::NoCapture); 2226 2227 if (Attrs.hasAttributes()) { 2228 unsigned FirstIRArg, NumIRArgs; 2229 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2230 for (unsigned i = 0; i < NumIRArgs; i++) 2231 ArgAttrs[FirstIRArg + i] = 2232 llvm::AttributeSet::get(getLLVMContext(), Attrs); 2233 } 2234 } 2235 assert(ArgNo == FI.arg_size()); 2236 2237 AttrList = llvm::AttributeList::get( 2238 getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs), 2239 llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs); 2240 } 2241 2242 /// An argument came in as a promoted argument; demote it back to its 2243 /// declared type. 2244 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF, 2245 const VarDecl *var, 2246 llvm::Value *value) { 2247 llvm::Type *varType = CGF.ConvertType(var->getType()); 2248 2249 // This can happen with promotions that actually don't change the 2250 // underlying type, like the enum promotions. 2251 if (value->getType() == varType) return value; 2252 2253 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) 2254 && "unexpected promotion type"); 2255 2256 if (isa<llvm::IntegerType>(varType)) 2257 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote"); 2258 2259 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote"); 2260 } 2261 2262 /// Returns the attribute (either parameter attribute, or function 2263 /// attribute), which declares argument ArgNo to be non-null. 2264 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, 2265 QualType ArgType, unsigned ArgNo) { 2266 // FIXME: __attribute__((nonnull)) can also be applied to: 2267 // - references to pointers, where the pointee is known to be 2268 // nonnull (apparently a Clang extension) 2269 // - transparent unions containing pointers 2270 // In the former case, LLVM IR cannot represent the constraint. In 2271 // the latter case, we have no guarantee that the transparent union 2272 // is in fact passed as a pointer. 2273 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType()) 2274 return nullptr; 2275 // First, check attribute on parameter itself. 2276 if (PVD) { 2277 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>()) 2278 return ParmNNAttr; 2279 } 2280 // Check function attributes. 2281 if (!FD) 2282 return nullptr; 2283 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) { 2284 if (NNAttr->isNonNull(ArgNo)) 2285 return NNAttr; 2286 } 2287 return nullptr; 2288 } 2289 2290 namespace { 2291 struct CopyBackSwiftError final : EHScopeStack::Cleanup { 2292 Address Temp; 2293 Address Arg; 2294 CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {} 2295 void Emit(CodeGenFunction &CGF, Flags flags) override { 2296 llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp); 2297 CGF.Builder.CreateStore(errorValue, Arg); 2298 } 2299 }; 2300 } 2301 2302 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 2303 llvm::Function *Fn, 2304 const FunctionArgList &Args) { 2305 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) 2306 // Naked functions don't have prologues. 2307 return; 2308 2309 // If this is an implicit-return-zero function, go ahead and 2310 // initialize the return value. TODO: it might be nice to have 2311 // a more general mechanism for this that didn't require synthesized 2312 // return statements. 2313 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) { 2314 if (FD->hasImplicitReturnZero()) { 2315 QualType RetTy = FD->getReturnType().getUnqualifiedType(); 2316 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 2317 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 2318 Builder.CreateStore(Zero, ReturnValue); 2319 } 2320 } 2321 2322 // FIXME: We no longer need the types from FunctionArgList; lift up and 2323 // simplify. 2324 2325 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI); 2326 assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs()); 2327 2328 // If we're using inalloca, all the memory arguments are GEPs off of the last 2329 // parameter, which is a pointer to the complete memory area. 2330 Address ArgStruct = Address::invalid(); 2331 if (IRFunctionArgs.hasInallocaArg()) { 2332 ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()), 2333 FI.getArgStructAlignment()); 2334 2335 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo()); 2336 } 2337 2338 // Name the struct return parameter. 2339 if (IRFunctionArgs.hasSRetArg()) { 2340 auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo()); 2341 AI->setName("agg.result"); 2342 AI->addAttr(llvm::Attribute::NoAlias); 2343 } 2344 2345 // Track if we received the parameter as a pointer (indirect, byval, or 2346 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it 2347 // into a local alloca for us. 2348 SmallVector<ParamValue, 16> ArgVals; 2349 ArgVals.reserve(Args.size()); 2350 2351 // Create a pointer value for every parameter declaration. This usually 2352 // entails copying one or more LLVM IR arguments into an alloca. Don't push 2353 // any cleanups or do anything that might unwind. We do that separately, so 2354 // we can push the cleanups in the correct order for the ABI. 2355 assert(FI.arg_size() == Args.size() && 2356 "Mismatch between function signature & arguments."); 2357 unsigned ArgNo = 0; 2358 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 2359 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 2360 i != e; ++i, ++info_it, ++ArgNo) { 2361 const VarDecl *Arg = *i; 2362 const ABIArgInfo &ArgI = info_it->info; 2363 2364 bool isPromoted = 2365 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted(); 2366 // We are converting from ABIArgInfo type to VarDecl type directly, unless 2367 // the parameter is promoted. In this case we convert to 2368 // CGFunctionInfo::ArgInfo type with subsequent argument demotion. 2369 QualType Ty = isPromoted ? info_it->type : Arg->getType(); 2370 assert(hasScalarEvaluationKind(Ty) == 2371 hasScalarEvaluationKind(Arg->getType())); 2372 2373 unsigned FirstIRArg, NumIRArgs; 2374 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2375 2376 switch (ArgI.getKind()) { 2377 case ABIArgInfo::InAlloca: { 2378 assert(NumIRArgs == 0); 2379 auto FieldIndex = ArgI.getInAllocaFieldIndex(); 2380 Address V = 2381 Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName()); 2382 if (ArgI.getInAllocaIndirect()) 2383 V = Address(Builder.CreateLoad(V), 2384 getContext().getTypeAlignInChars(Ty)); 2385 ArgVals.push_back(ParamValue::forIndirect(V)); 2386 break; 2387 } 2388 2389 case ABIArgInfo::Indirect: { 2390 assert(NumIRArgs == 1); 2391 Address ParamAddr = 2392 Address(Fn->getArg(FirstIRArg), ArgI.getIndirectAlign()); 2393 2394 if (!hasScalarEvaluationKind(Ty)) { 2395 // Aggregates and complex variables are accessed by reference. All we 2396 // need to do is realign the value, if requested. 2397 Address V = ParamAddr; 2398 if (ArgI.getIndirectRealign()) { 2399 Address AlignedTemp = CreateMemTemp(Ty, "coerce"); 2400 2401 // Copy from the incoming argument pointer to the temporary with the 2402 // appropriate alignment. 2403 // 2404 // FIXME: We should have a common utility for generating an aggregate 2405 // copy. 2406 CharUnits Size = getContext().getTypeSizeInChars(Ty); 2407 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()); 2408 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy); 2409 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy); 2410 Builder.CreateMemCpy(Dst, Src, SizeVal, false); 2411 V = AlignedTemp; 2412 } 2413 ArgVals.push_back(ParamValue::forIndirect(V)); 2414 } else { 2415 // Load scalar value from indirect argument. 2416 llvm::Value *V = 2417 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc()); 2418 2419 if (isPromoted) 2420 V = emitArgumentDemotion(*this, Arg, V); 2421 ArgVals.push_back(ParamValue::forDirect(V)); 2422 } 2423 break; 2424 } 2425 2426 case ABIArgInfo::Extend: 2427 case ABIArgInfo::Direct: { 2428 auto AI = Fn->getArg(FirstIRArg); 2429 llvm::Type *LTy = ConvertType(Arg->getType()); 2430 2431 // Prepare parameter attributes. So far, only attributes for pointer 2432 // parameters are prepared. See 2433 // http://llvm.org/docs/LangRef.html#paramattrs. 2434 if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() && 2435 ArgI.getCoerceToType()->isPointerTy()) { 2436 assert(NumIRArgs == 1); 2437 2438 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) { 2439 // Set `nonnull` attribute if any. 2440 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(), 2441 PVD->getFunctionScopeIndex()) && 2442 !CGM.getCodeGenOpts().NullPointerIsValid) 2443 AI->addAttr(llvm::Attribute::NonNull); 2444 2445 QualType OTy = PVD->getOriginalType(); 2446 if (const auto *ArrTy = 2447 getContext().getAsConstantArrayType(OTy)) { 2448 // A C99 array parameter declaration with the static keyword also 2449 // indicates dereferenceability, and if the size is constant we can 2450 // use the dereferenceable attribute (which requires the size in 2451 // bytes). 2452 if (ArrTy->getSizeModifier() == ArrayType::Static) { 2453 QualType ETy = ArrTy->getElementType(); 2454 uint64_t ArrSize = ArrTy->getSize().getZExtValue(); 2455 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() && 2456 ArrSize) { 2457 llvm::AttrBuilder Attrs; 2458 Attrs.addDereferenceableAttr( 2459 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize); 2460 AI->addAttrs(Attrs); 2461 } else if (getContext().getTargetAddressSpace(ETy) == 0 && 2462 !CGM.getCodeGenOpts().NullPointerIsValid) { 2463 AI->addAttr(llvm::Attribute::NonNull); 2464 } 2465 } 2466 } else if (const auto *ArrTy = 2467 getContext().getAsVariableArrayType(OTy)) { 2468 // For C99 VLAs with the static keyword, we don't know the size so 2469 // we can't use the dereferenceable attribute, but in addrspace(0) 2470 // we know that it must be nonnull. 2471 if (ArrTy->getSizeModifier() == VariableArrayType::Static && 2472 !getContext().getTargetAddressSpace(ArrTy->getElementType()) && 2473 !CGM.getCodeGenOpts().NullPointerIsValid) 2474 AI->addAttr(llvm::Attribute::NonNull); 2475 } 2476 2477 // Set `align` attribute if any. 2478 const auto *AVAttr = PVD->getAttr<AlignValueAttr>(); 2479 if (!AVAttr) 2480 if (const auto *TOTy = dyn_cast<TypedefType>(OTy)) 2481 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>(); 2482 if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) { 2483 // If alignment-assumption sanitizer is enabled, we do *not* add 2484 // alignment attribute here, but emit normal alignment assumption, 2485 // so the UBSAN check could function. 2486 llvm::Value *AlignmentValue = 2487 EmitScalarExpr(AVAttr->getAlignment()); 2488 llvm::ConstantInt *AlignmentCI = 2489 cast<llvm::ConstantInt>(AlignmentValue); 2490 AI->addAttrs(llvm::AttrBuilder().addAlignmentAttr(llvm::MaybeAlign( 2491 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)))); 2492 } 2493 } 2494 2495 // Set 'noalias' if an argument type has the `restrict` qualifier. 2496 if (Arg->getType().isRestrictQualified()) 2497 AI->addAttr(llvm::Attribute::NoAlias); 2498 } 2499 2500 // Prepare the argument value. If we have the trivial case, handle it 2501 // with no muss and fuss. 2502 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) && 2503 ArgI.getCoerceToType() == ConvertType(Ty) && 2504 ArgI.getDirectOffset() == 0) { 2505 assert(NumIRArgs == 1); 2506 2507 // LLVM expects swifterror parameters to be used in very restricted 2508 // ways. Copy the value into a less-restricted temporary. 2509 llvm::Value *V = AI; 2510 if (FI.getExtParameterInfo(ArgNo).getABI() 2511 == ParameterABI::SwiftErrorResult) { 2512 QualType pointeeTy = Ty->getPointeeType(); 2513 assert(pointeeTy->isPointerType()); 2514 Address temp = 2515 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 2516 Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy)); 2517 llvm::Value *incomingErrorValue = Builder.CreateLoad(arg); 2518 Builder.CreateStore(incomingErrorValue, temp); 2519 V = temp.getPointer(); 2520 2521 // Push a cleanup to copy the value back at the end of the function. 2522 // The convention does not guarantee that the value will be written 2523 // back if the function exits with an unwind exception. 2524 EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg); 2525 } 2526 2527 // Ensure the argument is the correct type. 2528 if (V->getType() != ArgI.getCoerceToType()) 2529 V = Builder.CreateBitCast(V, ArgI.getCoerceToType()); 2530 2531 if (isPromoted) 2532 V = emitArgumentDemotion(*this, Arg, V); 2533 2534 // Because of merging of function types from multiple decls it is 2535 // possible for the type of an argument to not match the corresponding 2536 // type in the function type. Since we are codegening the callee 2537 // in here, add a cast to the argument type. 2538 llvm::Type *LTy = ConvertType(Arg->getType()); 2539 if (V->getType() != LTy) 2540 V = Builder.CreateBitCast(V, LTy); 2541 2542 ArgVals.push_back(ParamValue::forDirect(V)); 2543 break; 2544 } 2545 2546 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg), 2547 Arg->getName()); 2548 2549 // Pointer to store into. 2550 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI); 2551 2552 // Fast-isel and the optimizer generally like scalar values better than 2553 // FCAs, so we flatten them if this is safe to do for this argument. 2554 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType()); 2555 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy && 2556 STy->getNumElements() > 1) { 2557 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy); 2558 llvm::Type *DstTy = Ptr.getElementType(); 2559 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy); 2560 2561 Address AddrToStoreInto = Address::invalid(); 2562 if (SrcSize <= DstSize) { 2563 AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy); 2564 } else { 2565 AddrToStoreInto = 2566 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce"); 2567 } 2568 2569 assert(STy->getNumElements() == NumIRArgs); 2570 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2571 auto AI = Fn->getArg(FirstIRArg + i); 2572 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 2573 Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i); 2574 Builder.CreateStore(AI, EltPtr); 2575 } 2576 2577 if (SrcSize > DstSize) { 2578 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize); 2579 } 2580 2581 } else { 2582 // Simple case, just do a coerced store of the argument into the alloca. 2583 assert(NumIRArgs == 1); 2584 auto AI = Fn->getArg(FirstIRArg); 2585 AI->setName(Arg->getName() + ".coerce"); 2586 CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this); 2587 } 2588 2589 // Match to what EmitParmDecl is expecting for this type. 2590 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) { 2591 llvm::Value *V = 2592 EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc()); 2593 if (isPromoted) 2594 V = emitArgumentDemotion(*this, Arg, V); 2595 ArgVals.push_back(ParamValue::forDirect(V)); 2596 } else { 2597 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2598 } 2599 break; 2600 } 2601 2602 case ABIArgInfo::CoerceAndExpand: { 2603 // Reconstruct into a temporary. 2604 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2605 ArgVals.push_back(ParamValue::forIndirect(alloca)); 2606 2607 auto coercionType = ArgI.getCoerceAndExpandType(); 2608 alloca = Builder.CreateElementBitCast(alloca, coercionType); 2609 2610 unsigned argIndex = FirstIRArg; 2611 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 2612 llvm::Type *eltType = coercionType->getElementType(i); 2613 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) 2614 continue; 2615 2616 auto eltAddr = Builder.CreateStructGEP(alloca, i); 2617 auto elt = Fn->getArg(argIndex++); 2618 Builder.CreateStore(elt, eltAddr); 2619 } 2620 assert(argIndex == FirstIRArg + NumIRArgs); 2621 break; 2622 } 2623 2624 case ABIArgInfo::Expand: { 2625 // If this structure was expanded into multiple arguments then 2626 // we need to create a temporary and reconstruct it from the 2627 // arguments. 2628 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2629 LValue LV = MakeAddrLValue(Alloca, Ty); 2630 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2631 2632 auto FnArgIter = Fn->arg_begin() + FirstIRArg; 2633 ExpandTypeFromArgs(Ty, LV, FnArgIter); 2634 assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs); 2635 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) { 2636 auto AI = Fn->getArg(FirstIRArg + i); 2637 AI->setName(Arg->getName() + "." + Twine(i)); 2638 } 2639 break; 2640 } 2641 2642 case ABIArgInfo::Ignore: 2643 assert(NumIRArgs == 0); 2644 // Initialize the local variable appropriately. 2645 if (!hasScalarEvaluationKind(Ty)) { 2646 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty))); 2647 } else { 2648 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType())); 2649 ArgVals.push_back(ParamValue::forDirect(U)); 2650 } 2651 break; 2652 } 2653 } 2654 2655 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2656 for (int I = Args.size() - 1; I >= 0; --I) 2657 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2658 } else { 2659 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2660 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2661 } 2662 } 2663 2664 static void eraseUnusedBitCasts(llvm::Instruction *insn) { 2665 while (insn->use_empty()) { 2666 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn); 2667 if (!bitcast) return; 2668 2669 // This is "safe" because we would have used a ConstantExpr otherwise. 2670 insn = cast<llvm::Instruction>(bitcast->getOperand(0)); 2671 bitcast->eraseFromParent(); 2672 } 2673 } 2674 2675 /// Try to emit a fused autorelease of a return result. 2676 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, 2677 llvm::Value *result) { 2678 // We must be immediately followed the cast. 2679 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock(); 2680 if (BB->empty()) return nullptr; 2681 if (&BB->back() != result) return nullptr; 2682 2683 llvm::Type *resultType = result->getType(); 2684 2685 // result is in a BasicBlock and is therefore an Instruction. 2686 llvm::Instruction *generator = cast<llvm::Instruction>(result); 2687 2688 SmallVector<llvm::Instruction *, 4> InstsToKill; 2689 2690 // Look for: 2691 // %generator = bitcast %type1* %generator2 to %type2* 2692 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) { 2693 // We would have emitted this as a constant if the operand weren't 2694 // an Instruction. 2695 generator = cast<llvm::Instruction>(bitcast->getOperand(0)); 2696 2697 // Require the generator to be immediately followed by the cast. 2698 if (generator->getNextNode() != bitcast) 2699 return nullptr; 2700 2701 InstsToKill.push_back(bitcast); 2702 } 2703 2704 // Look for: 2705 // %generator = call i8* @objc_retain(i8* %originalResult) 2706 // or 2707 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult) 2708 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator); 2709 if (!call) return nullptr; 2710 2711 bool doRetainAutorelease; 2712 2713 if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) { 2714 doRetainAutorelease = true; 2715 } else if (call->getCalledOperand() == 2716 CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) { 2717 doRetainAutorelease = false; 2718 2719 // If we emitted an assembly marker for this call (and the 2720 // ARCEntrypoints field should have been set if so), go looking 2721 // for that call. If we can't find it, we can't do this 2722 // optimization. But it should always be the immediately previous 2723 // instruction, unless we needed bitcasts around the call. 2724 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) { 2725 llvm::Instruction *prev = call->getPrevNode(); 2726 assert(prev); 2727 if (isa<llvm::BitCastInst>(prev)) { 2728 prev = prev->getPrevNode(); 2729 assert(prev); 2730 } 2731 assert(isa<llvm::CallInst>(prev)); 2732 assert(cast<llvm::CallInst>(prev)->getCalledOperand() == 2733 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker); 2734 InstsToKill.push_back(prev); 2735 } 2736 } else { 2737 return nullptr; 2738 } 2739 2740 result = call->getArgOperand(0); 2741 InstsToKill.push_back(call); 2742 2743 // Keep killing bitcasts, for sanity. Note that we no longer care 2744 // about precise ordering as long as there's exactly one use. 2745 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) { 2746 if (!bitcast->hasOneUse()) break; 2747 InstsToKill.push_back(bitcast); 2748 result = bitcast->getOperand(0); 2749 } 2750 2751 // Delete all the unnecessary instructions, from latest to earliest. 2752 for (auto *I : InstsToKill) 2753 I->eraseFromParent(); 2754 2755 // Do the fused retain/autorelease if we were asked to. 2756 if (doRetainAutorelease) 2757 result = CGF.EmitARCRetainAutoreleaseReturnValue(result); 2758 2759 // Cast back to the result type. 2760 return CGF.Builder.CreateBitCast(result, resultType); 2761 } 2762 2763 /// If this is a +1 of the value of an immutable 'self', remove it. 2764 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, 2765 llvm::Value *result) { 2766 // This is only applicable to a method with an immutable 'self'. 2767 const ObjCMethodDecl *method = 2768 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl); 2769 if (!method) return nullptr; 2770 const VarDecl *self = method->getSelfDecl(); 2771 if (!self->getType().isConstQualified()) return nullptr; 2772 2773 // Look for a retain call. 2774 llvm::CallInst *retainCall = 2775 dyn_cast<llvm::CallInst>(result->stripPointerCasts()); 2776 if (!retainCall || retainCall->getCalledOperand() != 2777 CGF.CGM.getObjCEntrypoints().objc_retain) 2778 return nullptr; 2779 2780 // Look for an ordinary load of 'self'. 2781 llvm::Value *retainedValue = retainCall->getArgOperand(0); 2782 llvm::LoadInst *load = 2783 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); 2784 if (!load || load->isAtomic() || load->isVolatile() || 2785 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) 2786 return nullptr; 2787 2788 // Okay! Burn it all down. This relies for correctness on the 2789 // assumption that the retain is emitted as part of the return and 2790 // that thereafter everything is used "linearly". 2791 llvm::Type *resultType = result->getType(); 2792 eraseUnusedBitCasts(cast<llvm::Instruction>(result)); 2793 assert(retainCall->use_empty()); 2794 retainCall->eraseFromParent(); 2795 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue)); 2796 2797 return CGF.Builder.CreateBitCast(load, resultType); 2798 } 2799 2800 /// Emit an ARC autorelease of the result of a function. 2801 /// 2802 /// \return the value to actually return from the function 2803 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF, 2804 llvm::Value *result) { 2805 // If we're returning 'self', kill the initial retain. This is a 2806 // heuristic attempt to "encourage correctness" in the really unfortunate 2807 // case where we have a return of self during a dealloc and we desperately 2808 // need to avoid the possible autorelease. 2809 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result)) 2810 return self; 2811 2812 // At -O0, try to emit a fused retain/autorelease. 2813 if (CGF.shouldUseFusedARCCalls()) 2814 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result)) 2815 return fused; 2816 2817 return CGF.EmitARCAutoreleaseReturnValue(result); 2818 } 2819 2820 /// Heuristically search for a dominating store to the return-value slot. 2821 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) { 2822 // Check if a User is a store which pointerOperand is the ReturnValue. 2823 // We are looking for stores to the ReturnValue, not for stores of the 2824 // ReturnValue to some other location. 2825 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * { 2826 auto *SI = dyn_cast<llvm::StoreInst>(U); 2827 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer()) 2828 return nullptr; 2829 // These aren't actually possible for non-coerced returns, and we 2830 // only care about non-coerced returns on this code path. 2831 assert(!SI->isAtomic() && !SI->isVolatile()); 2832 return SI; 2833 }; 2834 // If there are multiple uses of the return-value slot, just check 2835 // for something immediately preceding the IP. Sometimes this can 2836 // happen with how we generate implicit-returns; it can also happen 2837 // with noreturn cleanups. 2838 if (!CGF.ReturnValue.getPointer()->hasOneUse()) { 2839 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2840 if (IP->empty()) return nullptr; 2841 llvm::Instruction *I = &IP->back(); 2842 2843 // Skip lifetime markers 2844 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(), 2845 IE = IP->rend(); 2846 II != IE; ++II) { 2847 if (llvm::IntrinsicInst *Intrinsic = 2848 dyn_cast<llvm::IntrinsicInst>(&*II)) { 2849 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) { 2850 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1); 2851 ++II; 2852 if (II == IE) 2853 break; 2854 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II)) 2855 continue; 2856 } 2857 } 2858 I = &*II; 2859 break; 2860 } 2861 2862 return GetStoreIfValid(I); 2863 } 2864 2865 llvm::StoreInst *store = 2866 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back()); 2867 if (!store) return nullptr; 2868 2869 // Now do a first-and-dirty dominance check: just walk up the 2870 // single-predecessors chain from the current insertion point. 2871 llvm::BasicBlock *StoreBB = store->getParent(); 2872 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2873 while (IP != StoreBB) { 2874 if (!(IP = IP->getSinglePredecessor())) 2875 return nullptr; 2876 } 2877 2878 // Okay, the store's basic block dominates the insertion point; we 2879 // can do our thing. 2880 return store; 2881 } 2882 2883 // Helper functions for EmitCMSEClearRecord 2884 2885 // Set the bits corresponding to a field having width `BitWidth` and located at 2886 // offset `BitOffset` (from the least significant bit) within a storage unit of 2887 // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte. 2888 // Use little-endian layout, i.e.`Bits[0]` is the LSB. 2889 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset, 2890 int BitWidth, int CharWidth) { 2891 assert(CharWidth <= 64); 2892 assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth); 2893 2894 int Pos = 0; 2895 if (BitOffset >= CharWidth) { 2896 Pos += BitOffset / CharWidth; 2897 BitOffset = BitOffset % CharWidth; 2898 } 2899 2900 const uint64_t Used = (uint64_t(1) << CharWidth) - 1; 2901 if (BitOffset + BitWidth >= CharWidth) { 2902 Bits[Pos++] |= (Used << BitOffset) & Used; 2903 BitWidth -= CharWidth - BitOffset; 2904 BitOffset = 0; 2905 } 2906 2907 while (BitWidth >= CharWidth) { 2908 Bits[Pos++] = Used; 2909 BitWidth -= CharWidth; 2910 } 2911 2912 if (BitWidth > 0) 2913 Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset; 2914 } 2915 2916 // Set the bits corresponding to a field having width `BitWidth` and located at 2917 // offset `BitOffset` (from the least significant bit) within a storage unit of 2918 // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of 2919 // `Bits` corresponds to one target byte. Use target endian layout. 2920 static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset, 2921 int StorageSize, int BitOffset, int BitWidth, 2922 int CharWidth, bool BigEndian) { 2923 2924 SmallVector<uint64_t, 8> TmpBits(StorageSize); 2925 setBitRange(TmpBits, BitOffset, BitWidth, CharWidth); 2926 2927 if (BigEndian) 2928 std::reverse(TmpBits.begin(), TmpBits.end()); 2929 2930 for (uint64_t V : TmpBits) 2931 Bits[StorageOffset++] |= V; 2932 } 2933 2934 static void setUsedBits(CodeGenModule &, QualType, int, 2935 SmallVectorImpl<uint64_t> &); 2936 2937 // Set the bits in `Bits`, which correspond to the value representations of 2938 // the actual members of the record type `RTy`. Note that this function does 2939 // not handle base classes, virtual tables, etc, since they cannot happen in 2940 // CMSE function arguments or return. The bit mask corresponds to the target 2941 // memory layout, i.e. it's endian dependent. 2942 static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset, 2943 SmallVectorImpl<uint64_t> &Bits) { 2944 ASTContext &Context = CGM.getContext(); 2945 int CharWidth = Context.getCharWidth(); 2946 const RecordDecl *RD = RTy->getDecl()->getDefinition(); 2947 const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD); 2948 const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD); 2949 2950 int Idx = 0; 2951 for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) { 2952 const FieldDecl *F = *I; 2953 2954 if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) || 2955 F->getType()->isIncompleteArrayType()) 2956 continue; 2957 2958 if (F->isBitField()) { 2959 const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F); 2960 setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(), 2961 BFI.StorageSize / CharWidth, BFI.Offset, 2962 BFI.Size, CharWidth, 2963 CGM.getDataLayout().isBigEndian()); 2964 continue; 2965 } 2966 2967 setUsedBits(CGM, F->getType(), 2968 Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits); 2969 } 2970 } 2971 2972 // Set the bits in `Bits`, which correspond to the value representations of 2973 // the elements of an array type `ATy`. 2974 static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy, 2975 int Offset, SmallVectorImpl<uint64_t> &Bits) { 2976 const ASTContext &Context = CGM.getContext(); 2977 2978 QualType ETy = Context.getBaseElementType(ATy); 2979 int Size = Context.getTypeSizeInChars(ETy).getQuantity(); 2980 SmallVector<uint64_t, 4> TmpBits(Size); 2981 setUsedBits(CGM, ETy, 0, TmpBits); 2982 2983 for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) { 2984 auto Src = TmpBits.begin(); 2985 auto Dst = Bits.begin() + Offset + I * Size; 2986 for (int J = 0; J < Size; ++J) 2987 *Dst++ |= *Src++; 2988 } 2989 } 2990 2991 // Set the bits in `Bits`, which correspond to the value representations of 2992 // the type `QTy`. 2993 static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset, 2994 SmallVectorImpl<uint64_t> &Bits) { 2995 if (const auto *RTy = QTy->getAs<RecordType>()) 2996 return setUsedBits(CGM, RTy, Offset, Bits); 2997 2998 ASTContext &Context = CGM.getContext(); 2999 if (const auto *ATy = Context.getAsConstantArrayType(QTy)) 3000 return setUsedBits(CGM, ATy, Offset, Bits); 3001 3002 int Size = Context.getTypeSizeInChars(QTy).getQuantity(); 3003 if (Size <= 0) 3004 return; 3005 3006 std::fill_n(Bits.begin() + Offset, Size, 3007 (uint64_t(1) << Context.getCharWidth()) - 1); 3008 } 3009 3010 static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits, 3011 int Pos, int Size, int CharWidth, 3012 bool BigEndian) { 3013 assert(Size > 0); 3014 uint64_t Mask = 0; 3015 if (BigEndian) { 3016 for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E; 3017 ++P) 3018 Mask = (Mask << CharWidth) | *P; 3019 } else { 3020 auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos; 3021 do 3022 Mask = (Mask << CharWidth) | *--P; 3023 while (P != End); 3024 } 3025 return Mask; 3026 } 3027 3028 // Emit code to clear the bits in a record, which aren't a part of any user 3029 // declared member, when the record is a function return. 3030 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src, 3031 llvm::IntegerType *ITy, 3032 QualType QTy) { 3033 assert(Src->getType() == ITy); 3034 assert(ITy->getScalarSizeInBits() <= 64); 3035 3036 const llvm::DataLayout &DataLayout = CGM.getDataLayout(); 3037 int Size = DataLayout.getTypeStoreSize(ITy); 3038 SmallVector<uint64_t, 4> Bits(Size); 3039 setUsedBits(CGM, QTy->getAs<RecordType>(), 0, Bits); 3040 3041 int CharWidth = CGM.getContext().getCharWidth(); 3042 uint64_t Mask = 3043 buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian()); 3044 3045 return Builder.CreateAnd(Src, Mask, "cmse.clear"); 3046 } 3047 3048 // Emit code to clear the bits in a record, which aren't a part of any user 3049 // declared member, when the record is a function argument. 3050 llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src, 3051 llvm::ArrayType *ATy, 3052 QualType QTy) { 3053 const llvm::DataLayout &DataLayout = CGM.getDataLayout(); 3054 int Size = DataLayout.getTypeStoreSize(ATy); 3055 SmallVector<uint64_t, 16> Bits(Size); 3056 setUsedBits(CGM, QTy->getAs<RecordType>(), 0, Bits); 3057 3058 // Clear each element of the LLVM array. 3059 int CharWidth = CGM.getContext().getCharWidth(); 3060 int CharsPerElt = 3061 ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth; 3062 int MaskIndex = 0; 3063 llvm::Value *R = llvm::UndefValue::get(ATy); 3064 for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) { 3065 uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth, 3066 DataLayout.isBigEndian()); 3067 MaskIndex += CharsPerElt; 3068 llvm::Value *T0 = Builder.CreateExtractValue(Src, I); 3069 llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear"); 3070 R = Builder.CreateInsertValue(R, T1, I); 3071 } 3072 3073 return R; 3074 } 3075 3076 // Emit code to clear the padding bits when returning or passing as an argument 3077 // a 16-bit floating-point value. 3078 llvm::Value *CodeGenFunction::EmitCMSEClearFP16(llvm::Value *Src) { 3079 llvm::Type *RetTy = Src->getType(); 3080 assert(RetTy->isFloatTy() || 3081 (RetTy->isIntegerTy() && RetTy->getIntegerBitWidth() == 32)); 3082 if (RetTy->isFloatTy()) { 3083 llvm::Value *T0 = Builder.CreateBitCast(Src, Builder.getIntNTy(32)); 3084 llvm::Value *T1 = Builder.CreateAnd(T0, 0xffff, "cmse.clear"); 3085 return Builder.CreateBitCast(T1, RetTy); 3086 } 3087 return Builder.CreateAnd(Src, 0xffff, "cmse.clear"); 3088 } 3089 3090 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 3091 bool EmitRetDbgLoc, 3092 SourceLocation EndLoc) { 3093 if (FI.isNoReturn()) { 3094 // Noreturn functions don't return. 3095 EmitUnreachable(EndLoc); 3096 return; 3097 } 3098 3099 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) { 3100 // Naked functions don't have epilogues. 3101 Builder.CreateUnreachable(); 3102 return; 3103 } 3104 3105 // Functions with no result always return void. 3106 if (!ReturnValue.isValid()) { 3107 Builder.CreateRetVoid(); 3108 return; 3109 } 3110 3111 llvm::DebugLoc RetDbgLoc; 3112 llvm::Value *RV = nullptr; 3113 QualType RetTy = FI.getReturnType(); 3114 const ABIArgInfo &RetAI = FI.getReturnInfo(); 3115 3116 switch (RetAI.getKind()) { 3117 case ABIArgInfo::InAlloca: 3118 // Aggregrates get evaluated directly into the destination. Sometimes we 3119 // need to return the sret value in a register, though. 3120 assert(hasAggregateEvaluationKind(RetTy)); 3121 if (RetAI.getInAllocaSRet()) { 3122 llvm::Function::arg_iterator EI = CurFn->arg_end(); 3123 --EI; 3124 llvm::Value *ArgStruct = &*EI; 3125 llvm::Value *SRet = Builder.CreateStructGEP( 3126 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex()); 3127 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret"); 3128 } 3129 break; 3130 3131 case ABIArgInfo::Indirect: { 3132 auto AI = CurFn->arg_begin(); 3133 if (RetAI.isSRetAfterThis()) 3134 ++AI; 3135 switch (getEvaluationKind(RetTy)) { 3136 case TEK_Complex: { 3137 ComplexPairTy RT = 3138 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc); 3139 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy), 3140 /*isInit*/ true); 3141 break; 3142 } 3143 case TEK_Aggregate: 3144 // Do nothing; aggregrates get evaluated directly into the destination. 3145 break; 3146 case TEK_Scalar: 3147 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), 3148 MakeNaturalAlignAddrLValue(&*AI, RetTy), 3149 /*isInit*/ true); 3150 break; 3151 } 3152 break; 3153 } 3154 3155 case ABIArgInfo::Extend: 3156 case ABIArgInfo::Direct: 3157 if (RetAI.getCoerceToType() == ConvertType(RetTy) && 3158 RetAI.getDirectOffset() == 0) { 3159 // The internal return value temp always will have pointer-to-return-type 3160 // type, just do a load. 3161 3162 // If there is a dominating store to ReturnValue, we can elide 3163 // the load, zap the store, and usually zap the alloca. 3164 if (llvm::StoreInst *SI = 3165 findDominatingStoreToReturnValue(*this)) { 3166 // Reuse the debug location from the store unless there is 3167 // cleanup code to be emitted between the store and return 3168 // instruction. 3169 if (EmitRetDbgLoc && !AutoreleaseResult) 3170 RetDbgLoc = SI->getDebugLoc(); 3171 // Get the stored value and nuke the now-dead store. 3172 RV = SI->getValueOperand(); 3173 SI->eraseFromParent(); 3174 3175 // Otherwise, we have to do a simple load. 3176 } else { 3177 RV = Builder.CreateLoad(ReturnValue); 3178 } 3179 } else { 3180 // If the value is offset in memory, apply the offset now. 3181 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI); 3182 3183 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this); 3184 } 3185 3186 // In ARC, end functions that return a retainable type with a call 3187 // to objc_autoreleaseReturnValue. 3188 if (AutoreleaseResult) { 3189 #ifndef NDEBUG 3190 // Type::isObjCRetainabletype has to be called on a QualType that hasn't 3191 // been stripped of the typedefs, so we cannot use RetTy here. Get the 3192 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from 3193 // CurCodeDecl or BlockInfo. 3194 QualType RT; 3195 3196 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl)) 3197 RT = FD->getReturnType(); 3198 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl)) 3199 RT = MD->getReturnType(); 3200 else if (isa<BlockDecl>(CurCodeDecl)) 3201 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType(); 3202 else 3203 llvm_unreachable("Unexpected function/method type"); 3204 3205 assert(getLangOpts().ObjCAutoRefCount && 3206 !FI.isReturnsRetained() && 3207 RT->isObjCRetainableType()); 3208 #endif 3209 RV = emitAutoreleaseOfResult(*this, RV); 3210 } 3211 3212 break; 3213 3214 case ABIArgInfo::Ignore: 3215 break; 3216 3217 case ABIArgInfo::CoerceAndExpand: { 3218 auto coercionType = RetAI.getCoerceAndExpandType(); 3219 3220 // Load all of the coerced elements out into results. 3221 llvm::SmallVector<llvm::Value*, 4> results; 3222 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType); 3223 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 3224 auto coercedEltType = coercionType->getElementType(i); 3225 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType)) 3226 continue; 3227 3228 auto eltAddr = Builder.CreateStructGEP(addr, i); 3229 auto elt = Builder.CreateLoad(eltAddr); 3230 results.push_back(elt); 3231 } 3232 3233 // If we have one result, it's the single direct result type. 3234 if (results.size() == 1) { 3235 RV = results[0]; 3236 3237 // Otherwise, we need to make a first-class aggregate. 3238 } else { 3239 // Construct a return type that lacks padding elements. 3240 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType(); 3241 3242 RV = llvm::UndefValue::get(returnType); 3243 for (unsigned i = 0, e = results.size(); i != e; ++i) { 3244 RV = Builder.CreateInsertValue(RV, results[i], i); 3245 } 3246 } 3247 break; 3248 } 3249 3250 case ABIArgInfo::Expand: 3251 llvm_unreachable("Invalid ABI kind for return argument"); 3252 } 3253 3254 llvm::Instruction *Ret; 3255 if (RV) { 3256 if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) { 3257 // For certain return types, clear padding bits, as they may reveal 3258 // sensitive information. 3259 const Type *RTy = RetTy.getCanonicalType().getTypePtr(); 3260 if (RTy->isFloat16Type() || RTy->isHalfType()) { 3261 // 16-bit floating-point types are passed in a 32-bit integer or float, 3262 // with unspecified upper bits. 3263 RV = EmitCMSEClearFP16(RV); 3264 } else { 3265 // Small struct/union types are passed as integers. 3266 auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType()); 3267 if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType())) 3268 RV = EmitCMSEClearRecord(RV, ITy, RetTy); 3269 } 3270 } 3271 EmitReturnValueCheck(RV); 3272 Ret = Builder.CreateRet(RV); 3273 } else { 3274 Ret = Builder.CreateRetVoid(); 3275 } 3276 3277 if (RetDbgLoc) 3278 Ret->setDebugLoc(std::move(RetDbgLoc)); 3279 } 3280 3281 void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) { 3282 // A current decl may not be available when emitting vtable thunks. 3283 if (!CurCodeDecl) 3284 return; 3285 3286 // If the return block isn't reachable, neither is this check, so don't emit 3287 // it. 3288 if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty()) 3289 return; 3290 3291 ReturnsNonNullAttr *RetNNAttr = nullptr; 3292 if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) 3293 RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>(); 3294 3295 if (!RetNNAttr && !requiresReturnValueNullabilityCheck()) 3296 return; 3297 3298 // Prefer the returns_nonnull attribute if it's present. 3299 SourceLocation AttrLoc; 3300 SanitizerMask CheckKind; 3301 SanitizerHandler Handler; 3302 if (RetNNAttr) { 3303 assert(!requiresReturnValueNullabilityCheck() && 3304 "Cannot check nullability and the nonnull attribute"); 3305 AttrLoc = RetNNAttr->getLocation(); 3306 CheckKind = SanitizerKind::ReturnsNonnullAttribute; 3307 Handler = SanitizerHandler::NonnullReturn; 3308 } else { 3309 if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl)) 3310 if (auto *TSI = DD->getTypeSourceInfo()) 3311 if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>()) 3312 AttrLoc = FTL.getReturnLoc().findNullabilityLoc(); 3313 CheckKind = SanitizerKind::NullabilityReturn; 3314 Handler = SanitizerHandler::NullabilityReturn; 3315 } 3316 3317 SanitizerScope SanScope(this); 3318 3319 // Make sure the "return" source location is valid. If we're checking a 3320 // nullability annotation, make sure the preconditions for the check are met. 3321 llvm::BasicBlock *Check = createBasicBlock("nullcheck"); 3322 llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck"); 3323 llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load"); 3324 llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr); 3325 if (requiresReturnValueNullabilityCheck()) 3326 CanNullCheck = 3327 Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition); 3328 Builder.CreateCondBr(CanNullCheck, Check, NoCheck); 3329 EmitBlock(Check); 3330 3331 // Now do the null check. 3332 llvm::Value *Cond = Builder.CreateIsNotNull(RV); 3333 llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)}; 3334 llvm::Value *DynamicData[] = {SLocPtr}; 3335 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData); 3336 3337 EmitBlock(NoCheck); 3338 3339 #ifndef NDEBUG 3340 // The return location should not be used after the check has been emitted. 3341 ReturnLocation = Address::invalid(); 3342 #endif 3343 } 3344 3345 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) { 3346 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 3347 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory; 3348 } 3349 3350 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, 3351 QualType Ty) { 3352 // FIXME: Generate IR in one pass, rather than going back and fixing up these 3353 // placeholders. 3354 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty); 3355 llvm::Type *IRPtrTy = IRTy->getPointerTo(); 3356 llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo()); 3357 3358 // FIXME: When we generate this IR in one pass, we shouldn't need 3359 // this win32-specific alignment hack. 3360 CharUnits Align = CharUnits::fromQuantity(4); 3361 Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align); 3362 3363 return AggValueSlot::forAddr(Address(Placeholder, Align), 3364 Ty.getQualifiers(), 3365 AggValueSlot::IsNotDestructed, 3366 AggValueSlot::DoesNotNeedGCBarriers, 3367 AggValueSlot::IsNotAliased, 3368 AggValueSlot::DoesNotOverlap); 3369 } 3370 3371 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args, 3372 const VarDecl *param, 3373 SourceLocation loc) { 3374 // StartFunction converted the ABI-lowered parameter(s) into a 3375 // local alloca. We need to turn that into an r-value suitable 3376 // for EmitCall. 3377 Address local = GetAddrOfLocalVar(param); 3378 3379 QualType type = param->getType(); 3380 3381 if (isInAllocaArgument(CGM.getCXXABI(), type)) { 3382 CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter"); 3383 } 3384 3385 // GetAddrOfLocalVar returns a pointer-to-pointer for references, 3386 // but the argument needs to be the original pointer. 3387 if (type->isReferenceType()) { 3388 args.add(RValue::get(Builder.CreateLoad(local)), type); 3389 3390 // In ARC, move out of consumed arguments so that the release cleanup 3391 // entered by StartFunction doesn't cause an over-release. This isn't 3392 // optimal -O0 code generation, but it should get cleaned up when 3393 // optimization is enabled. This also assumes that delegate calls are 3394 // performed exactly once for a set of arguments, but that should be safe. 3395 } else if (getLangOpts().ObjCAutoRefCount && 3396 param->hasAttr<NSConsumedAttr>() && 3397 type->isObjCRetainableType()) { 3398 llvm::Value *ptr = Builder.CreateLoad(local); 3399 auto null = 3400 llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType())); 3401 Builder.CreateStore(null, local); 3402 args.add(RValue::get(ptr), type); 3403 3404 // For the most part, we just need to load the alloca, except that 3405 // aggregate r-values are actually pointers to temporaries. 3406 } else { 3407 args.add(convertTempToRValue(local, type, loc), type); 3408 } 3409 3410 // Deactivate the cleanup for the callee-destructed param that was pushed. 3411 if (hasAggregateEvaluationKind(type) && !CurFuncIsThunk && 3412 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() && 3413 param->needsDestruction(getContext())) { 3414 EHScopeStack::stable_iterator cleanup = 3415 CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param)); 3416 assert(cleanup.isValid() && 3417 "cleanup for callee-destructed param not recorded"); 3418 // This unreachable is a temporary marker which will be removed later. 3419 llvm::Instruction *isActive = Builder.CreateUnreachable(); 3420 args.addArgCleanupDeactivation(cleanup, isActive); 3421 } 3422 } 3423 3424 static bool isProvablyNull(llvm::Value *addr) { 3425 return isa<llvm::ConstantPointerNull>(addr); 3426 } 3427 3428 /// Emit the actual writing-back of a writeback. 3429 static void emitWriteback(CodeGenFunction &CGF, 3430 const CallArgList::Writeback &writeback) { 3431 const LValue &srcLV = writeback.Source; 3432 Address srcAddr = srcLV.getAddress(CGF); 3433 assert(!isProvablyNull(srcAddr.getPointer()) && 3434 "shouldn't have writeback for provably null argument"); 3435 3436 llvm::BasicBlock *contBB = nullptr; 3437 3438 // If the argument wasn't provably non-null, we need to null check 3439 // before doing the store. 3440 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3441 CGF.CGM.getDataLayout()); 3442 if (!provablyNonNull) { 3443 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback"); 3444 contBB = CGF.createBasicBlock("icr.done"); 3445 3446 llvm::Value *isNull = 3447 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3448 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB); 3449 CGF.EmitBlock(writebackBB); 3450 } 3451 3452 // Load the value to writeback. 3453 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary); 3454 3455 // Cast it back, in case we're writing an id to a Foo* or something. 3456 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), 3457 "icr.writeback-cast"); 3458 3459 // Perform the writeback. 3460 3461 // If we have a "to use" value, it's something we need to emit a use 3462 // of. This has to be carefully threaded in: if it's done after the 3463 // release it's potentially undefined behavior (and the optimizer 3464 // will ignore it), and if it happens before the retain then the 3465 // optimizer could move the release there. 3466 if (writeback.ToUse) { 3467 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong); 3468 3469 // Retain the new value. No need to block-copy here: the block's 3470 // being passed up the stack. 3471 value = CGF.EmitARCRetainNonBlock(value); 3472 3473 // Emit the intrinsic use here. 3474 CGF.EmitARCIntrinsicUse(writeback.ToUse); 3475 3476 // Load the old value (primitively). 3477 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation()); 3478 3479 // Put the new value in place (primitively). 3480 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false); 3481 3482 // Release the old value. 3483 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime()); 3484 3485 // Otherwise, we can just do a normal lvalue store. 3486 } else { 3487 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV); 3488 } 3489 3490 // Jump to the continuation block. 3491 if (!provablyNonNull) 3492 CGF.EmitBlock(contBB); 3493 } 3494 3495 static void emitWritebacks(CodeGenFunction &CGF, 3496 const CallArgList &args) { 3497 for (const auto &I : args.writebacks()) 3498 emitWriteback(CGF, I); 3499 } 3500 3501 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, 3502 const CallArgList &CallArgs) { 3503 ArrayRef<CallArgList::CallArgCleanup> Cleanups = 3504 CallArgs.getCleanupsToDeactivate(); 3505 // Iterate in reverse to increase the likelihood of popping the cleanup. 3506 for (const auto &I : llvm::reverse(Cleanups)) { 3507 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP); 3508 I.IsActiveIP->eraseFromParent(); 3509 } 3510 } 3511 3512 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) { 3513 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens())) 3514 if (uop->getOpcode() == UO_AddrOf) 3515 return uop->getSubExpr(); 3516 return nullptr; 3517 } 3518 3519 /// Emit an argument that's being passed call-by-writeback. That is, 3520 /// we are passing the address of an __autoreleased temporary; it 3521 /// might be copy-initialized with the current value of the given 3522 /// address, but it will definitely be copied out of after the call. 3523 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, 3524 const ObjCIndirectCopyRestoreExpr *CRE) { 3525 LValue srcLV; 3526 3527 // Make an optimistic effort to emit the address as an l-value. 3528 // This can fail if the argument expression is more complicated. 3529 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) { 3530 srcLV = CGF.EmitLValue(lvExpr); 3531 3532 // Otherwise, just emit it as a scalar. 3533 } else { 3534 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr()); 3535 3536 QualType srcAddrType = 3537 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 3538 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType); 3539 } 3540 Address srcAddr = srcLV.getAddress(CGF); 3541 3542 // The dest and src types don't necessarily match in LLVM terms 3543 // because of the crazy ObjC compatibility rules. 3544 3545 llvm::PointerType *destType = 3546 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType())); 3547 3548 // If the address is a constant null, just pass the appropriate null. 3549 if (isProvablyNull(srcAddr.getPointer())) { 3550 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)), 3551 CRE->getType()); 3552 return; 3553 } 3554 3555 // Create the temporary. 3556 Address temp = CGF.CreateTempAlloca(destType->getElementType(), 3557 CGF.getPointerAlign(), 3558 "icr.temp"); 3559 // Loading an l-value can introduce a cleanup if the l-value is __weak, 3560 // and that cleanup will be conditional if we can't prove that the l-value 3561 // isn't null, so we need to register a dominating point so that the cleanups 3562 // system will make valid IR. 3563 CodeGenFunction::ConditionalEvaluation condEval(CGF); 3564 3565 // Zero-initialize it if we're not doing a copy-initialization. 3566 bool shouldCopy = CRE->shouldCopy(); 3567 if (!shouldCopy) { 3568 llvm::Value *null = 3569 llvm::ConstantPointerNull::get( 3570 cast<llvm::PointerType>(destType->getElementType())); 3571 CGF.Builder.CreateStore(null, temp); 3572 } 3573 3574 llvm::BasicBlock *contBB = nullptr; 3575 llvm::BasicBlock *originBB = nullptr; 3576 3577 // If the address is *not* known to be non-null, we need to switch. 3578 llvm::Value *finalArgument; 3579 3580 bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(), 3581 CGF.CGM.getDataLayout()); 3582 if (provablyNonNull) { 3583 finalArgument = temp.getPointer(); 3584 } else { 3585 llvm::Value *isNull = 3586 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 3587 3588 finalArgument = CGF.Builder.CreateSelect(isNull, 3589 llvm::ConstantPointerNull::get(destType), 3590 temp.getPointer(), "icr.argument"); 3591 3592 // If we need to copy, then the load has to be conditional, which 3593 // means we need control flow. 3594 if (shouldCopy) { 3595 originBB = CGF.Builder.GetInsertBlock(); 3596 contBB = CGF.createBasicBlock("icr.cont"); 3597 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy"); 3598 CGF.Builder.CreateCondBr(isNull, contBB, copyBB); 3599 CGF.EmitBlock(copyBB); 3600 condEval.begin(CGF); 3601 } 3602 } 3603 3604 llvm::Value *valueToUse = nullptr; 3605 3606 // Perform a copy if necessary. 3607 if (shouldCopy) { 3608 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation()); 3609 assert(srcRV.isScalar()); 3610 3611 llvm::Value *src = srcRV.getScalarVal(); 3612 src = CGF.Builder.CreateBitCast(src, destType->getElementType(), 3613 "icr.cast"); 3614 3615 // Use an ordinary store, not a store-to-lvalue. 3616 CGF.Builder.CreateStore(src, temp); 3617 3618 // If optimization is enabled, and the value was held in a 3619 // __strong variable, we need to tell the optimizer that this 3620 // value has to stay alive until we're doing the store back. 3621 // This is because the temporary is effectively unretained, 3622 // and so otherwise we can violate the high-level semantics. 3623 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 && 3624 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) { 3625 valueToUse = src; 3626 } 3627 } 3628 3629 // Finish the control flow if we needed it. 3630 if (shouldCopy && !provablyNonNull) { 3631 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); 3632 CGF.EmitBlock(contBB); 3633 3634 // Make a phi for the value to intrinsically use. 3635 if (valueToUse) { 3636 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2, 3637 "icr.to-use"); 3638 phiToUse->addIncoming(valueToUse, copyBB); 3639 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()), 3640 originBB); 3641 valueToUse = phiToUse; 3642 } 3643 3644 condEval.end(CGF); 3645 } 3646 3647 args.addWriteback(srcLV, temp, valueToUse); 3648 args.add(RValue::get(finalArgument), CRE->getType()); 3649 } 3650 3651 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) { 3652 assert(!StackBase); 3653 3654 // Save the stack. 3655 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave); 3656 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save"); 3657 } 3658 3659 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const { 3660 if (StackBase) { 3661 // Restore the stack after the call. 3662 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 3663 CGF.Builder.CreateCall(F, StackBase); 3664 } 3665 } 3666 3667 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, 3668 SourceLocation ArgLoc, 3669 AbstractCallee AC, 3670 unsigned ParmNum) { 3671 if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) || 3672 SanOpts.has(SanitizerKind::NullabilityArg))) 3673 return; 3674 3675 // The param decl may be missing in a variadic function. 3676 auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr; 3677 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; 3678 3679 // Prefer the nonnull attribute if it's present. 3680 const NonNullAttr *NNAttr = nullptr; 3681 if (SanOpts.has(SanitizerKind::NonnullAttribute)) 3682 NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo); 3683 3684 bool CanCheckNullability = false; 3685 if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) { 3686 auto Nullability = PVD->getType()->getNullability(getContext()); 3687 CanCheckNullability = Nullability && 3688 *Nullability == NullabilityKind::NonNull && 3689 PVD->getTypeSourceInfo(); 3690 } 3691 3692 if (!NNAttr && !CanCheckNullability) 3693 return; 3694 3695 SourceLocation AttrLoc; 3696 SanitizerMask CheckKind; 3697 SanitizerHandler Handler; 3698 if (NNAttr) { 3699 AttrLoc = NNAttr->getLocation(); 3700 CheckKind = SanitizerKind::NonnullAttribute; 3701 Handler = SanitizerHandler::NonnullArg; 3702 } else { 3703 AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc(); 3704 CheckKind = SanitizerKind::NullabilityArg; 3705 Handler = SanitizerHandler::NullabilityArg; 3706 } 3707 3708 SanitizerScope SanScope(this); 3709 assert(RV.isScalar()); 3710 llvm::Value *V = RV.getScalarVal(); 3711 llvm::Value *Cond = 3712 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType())); 3713 llvm::Constant *StaticData[] = { 3714 EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc), 3715 llvm::ConstantInt::get(Int32Ty, ArgNo + 1), 3716 }; 3717 EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None); 3718 } 3719 3720 void CodeGenFunction::EmitCallArgs( 3721 CallArgList &Args, ArrayRef<QualType> ArgTypes, 3722 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3723 AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) { 3724 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())); 3725 3726 // We *have* to evaluate arguments from right to left in the MS C++ ABI, 3727 // because arguments are destroyed left to right in the callee. As a special 3728 // case, there are certain language constructs that require left-to-right 3729 // evaluation, and in those cases we consider the evaluation order requirement 3730 // to trump the "destruction order is reverse construction order" guarantee. 3731 bool LeftToRight = 3732 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee() 3733 ? Order == EvaluationOrder::ForceLeftToRight 3734 : Order != EvaluationOrder::ForceRightToLeft; 3735 3736 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg, 3737 RValue EmittedArg) { 3738 if (!AC.hasFunctionDecl() || I >= AC.getNumParams()) 3739 return; 3740 auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>(); 3741 if (PS == nullptr) 3742 return; 3743 3744 const auto &Context = getContext(); 3745 auto SizeTy = Context.getSizeType(); 3746 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy)); 3747 assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?"); 3748 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T, 3749 EmittedArg.getScalarVal(), 3750 PS->isDynamic()); 3751 Args.add(RValue::get(V), SizeTy); 3752 // If we're emitting args in reverse, be sure to do so with 3753 // pass_object_size, as well. 3754 if (!LeftToRight) 3755 std::swap(Args.back(), *(&Args.back() - 1)); 3756 }; 3757 3758 // Insert a stack save if we're going to need any inalloca args. 3759 bool HasInAllocaArgs = false; 3760 if (CGM.getTarget().getCXXABI().isMicrosoft()) { 3761 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end(); 3762 I != E && !HasInAllocaArgs; ++I) 3763 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I); 3764 if (HasInAllocaArgs) { 3765 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 3766 Args.allocateArgumentMemory(*this); 3767 } 3768 } 3769 3770 // Evaluate each argument in the appropriate order. 3771 size_t CallArgsStart = Args.size(); 3772 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) { 3773 unsigned Idx = LeftToRight ? I : E - I - 1; 3774 CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx; 3775 unsigned InitialArgSize = Args.size(); 3776 // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of 3777 // the argument and parameter match or the objc method is parameterized. 3778 assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) || 3779 getContext().hasSameUnqualifiedType((*Arg)->getType(), 3780 ArgTypes[Idx]) || 3781 (isa<ObjCMethodDecl>(AC.getDecl()) && 3782 isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) && 3783 "Argument and parameter types don't match"); 3784 EmitCallArg(Args, *Arg, ArgTypes[Idx]); 3785 // In particular, we depend on it being the last arg in Args, and the 3786 // objectsize bits depend on there only being one arg if !LeftToRight. 3787 assert(InitialArgSize + 1 == Args.size() && 3788 "The code below depends on only adding one arg per EmitCallArg"); 3789 (void)InitialArgSize; 3790 // Since pointer argument are never emitted as LValue, it is safe to emit 3791 // non-null argument check for r-value only. 3792 if (!Args.back().hasLValue()) { 3793 RValue RVArg = Args.back().getKnownRValue(); 3794 EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC, 3795 ParamsToSkip + Idx); 3796 // @llvm.objectsize should never have side-effects and shouldn't need 3797 // destruction/cleanups, so we can safely "emit" it after its arg, 3798 // regardless of right-to-leftness 3799 MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg); 3800 } 3801 } 3802 3803 if (!LeftToRight) { 3804 // Un-reverse the arguments we just evaluated so they match up with the LLVM 3805 // IR function. 3806 std::reverse(Args.begin() + CallArgsStart, Args.end()); 3807 } 3808 } 3809 3810 namespace { 3811 3812 struct DestroyUnpassedArg final : EHScopeStack::Cleanup { 3813 DestroyUnpassedArg(Address Addr, QualType Ty) 3814 : Addr(Addr), Ty(Ty) {} 3815 3816 Address Addr; 3817 QualType Ty; 3818 3819 void Emit(CodeGenFunction &CGF, Flags flags) override { 3820 QualType::DestructionKind DtorKind = Ty.isDestructedType(); 3821 if (DtorKind == QualType::DK_cxx_destructor) { 3822 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 3823 assert(!Dtor->isTrivial()); 3824 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false, 3825 /*Delegating=*/false, Addr, Ty); 3826 } else { 3827 CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty)); 3828 } 3829 } 3830 }; 3831 3832 struct DisableDebugLocationUpdates { 3833 CodeGenFunction &CGF; 3834 bool disabledDebugInfo; 3835 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) { 3836 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo())) 3837 CGF.disableDebugInfo(); 3838 } 3839 ~DisableDebugLocationUpdates() { 3840 if (disabledDebugInfo) 3841 CGF.enableDebugInfo(); 3842 } 3843 }; 3844 3845 } // end anonymous namespace 3846 3847 RValue CallArg::getRValue(CodeGenFunction &CGF) const { 3848 if (!HasLV) 3849 return RV; 3850 LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty); 3851 CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap, 3852 LV.isVolatile()); 3853 IsUsed = true; 3854 return RValue::getAggregate(Copy.getAddress(CGF)); 3855 } 3856 3857 void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const { 3858 LValue Dst = CGF.MakeAddrLValue(Addr, Ty); 3859 if (!HasLV && RV.isScalar()) 3860 CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true); 3861 else if (!HasLV && RV.isComplex()) 3862 CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true); 3863 else { 3864 auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress(); 3865 LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty); 3866 // We assume that call args are never copied into subobjects. 3867 CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap, 3868 HasLV ? LV.isVolatileQualified() 3869 : RV.isVolatileQualified()); 3870 } 3871 IsUsed = true; 3872 } 3873 3874 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, 3875 QualType type) { 3876 DisableDebugLocationUpdates Dis(*this, E); 3877 if (const ObjCIndirectCopyRestoreExpr *CRE 3878 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { 3879 assert(getLangOpts().ObjCAutoRefCount); 3880 return emitWritebackArg(*this, args, CRE); 3881 } 3882 3883 assert(type->isReferenceType() == E->isGLValue() && 3884 "reference binding to unmaterialized r-value!"); 3885 3886 if (E->isGLValue()) { 3887 assert(E->getObjectKind() == OK_Ordinary); 3888 return args.add(EmitReferenceBindingToExpr(E), type); 3889 } 3890 3891 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type); 3892 3893 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee. 3894 // However, we still have to push an EH-only cleanup in case we unwind before 3895 // we make it to the call. 3896 if (HasAggregateEvalKind && 3897 type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) { 3898 // If we're using inalloca, use the argument memory. Otherwise, use a 3899 // temporary. 3900 AggValueSlot Slot; 3901 if (args.isUsingInAlloca()) 3902 Slot = createPlaceholderSlot(*this, type); 3903 else 3904 Slot = CreateAggTemp(type, "agg.tmp"); 3905 3906 bool DestroyedInCallee = true, NeedsEHCleanup = true; 3907 if (const auto *RD = type->getAsCXXRecordDecl()) 3908 DestroyedInCallee = RD->hasNonTrivialDestructor(); 3909 else 3910 NeedsEHCleanup = needsEHCleanup(type.isDestructedType()); 3911 3912 if (DestroyedInCallee) 3913 Slot.setExternallyDestructed(); 3914 3915 EmitAggExpr(E, Slot); 3916 RValue RV = Slot.asRValue(); 3917 args.add(RV, type); 3918 3919 if (DestroyedInCallee && NeedsEHCleanup) { 3920 // Create a no-op GEP between the placeholder and the cleanup so we can 3921 // RAUW it successfully. It also serves as a marker of the first 3922 // instruction where the cleanup is active. 3923 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(), 3924 type); 3925 // This unreachable is a temporary marker which will be removed later. 3926 llvm::Instruction *IsActive = Builder.CreateUnreachable(); 3927 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive); 3928 } 3929 return; 3930 } 3931 3932 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) && 3933 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 3934 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 3935 assert(L.isSimple()); 3936 args.addUncopiedAggregate(L, type); 3937 return; 3938 } 3939 3940 args.add(EmitAnyExprToTemp(E), type); 3941 } 3942 3943 QualType CodeGenFunction::getVarArgType(const Expr *Arg) { 3944 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC 3945 // implicitly widens null pointer constants that are arguments to varargs 3946 // functions to pointer-sized ints. 3947 if (!getTarget().getTriple().isOSWindows()) 3948 return Arg->getType(); 3949 3950 if (Arg->getType()->isIntegerType() && 3951 getContext().getTypeSize(Arg->getType()) < 3952 getContext().getTargetInfo().getPointerWidth(0) && 3953 Arg->isNullPointerConstant(getContext(), 3954 Expr::NPC_ValueDependentIsNotNull)) { 3955 return getContext().getIntPtrType(); 3956 } 3957 3958 return Arg->getType(); 3959 } 3960 3961 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3962 // optimizer it can aggressively ignore unwind edges. 3963 void 3964 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 3965 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 3966 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 3967 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 3968 CGM.getNoObjCARCExceptionsMetadata()); 3969 } 3970 3971 /// Emits a call to the given no-arguments nounwind runtime function. 3972 llvm::CallInst * 3973 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3974 const llvm::Twine &name) { 3975 return EmitNounwindRuntimeCall(callee, None, name); 3976 } 3977 3978 /// Emits a call to the given nounwind runtime function. 3979 llvm::CallInst * 3980 CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee, 3981 ArrayRef<llvm::Value *> args, 3982 const llvm::Twine &name) { 3983 llvm::CallInst *call = EmitRuntimeCall(callee, args, name); 3984 call->setDoesNotThrow(); 3985 return call; 3986 } 3987 3988 /// Emits a simple call (never an invoke) to the given no-arguments 3989 /// runtime function. 3990 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 3991 const llvm::Twine &name) { 3992 return EmitRuntimeCall(callee, None, name); 3993 } 3994 3995 // Calls which may throw must have operand bundles indicating which funclet 3996 // they are nested within. 3997 SmallVector<llvm::OperandBundleDef, 1> 3998 CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) { 3999 SmallVector<llvm::OperandBundleDef, 1> BundleList; 4000 // There is no need for a funclet operand bundle if we aren't inside a 4001 // funclet. 4002 if (!CurrentFuncletPad) 4003 return BundleList; 4004 4005 // Skip intrinsics which cannot throw. 4006 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts()); 4007 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) 4008 return BundleList; 4009 4010 BundleList.emplace_back("funclet", CurrentFuncletPad); 4011 return BundleList; 4012 } 4013 4014 /// Emits a simple call (never an invoke) to the given runtime function. 4015 llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee, 4016 ArrayRef<llvm::Value *> args, 4017 const llvm::Twine &name) { 4018 llvm::CallInst *call = Builder.CreateCall( 4019 callee, args, getBundlesForFunclet(callee.getCallee()), name); 4020 call->setCallingConv(getRuntimeCC()); 4021 return call; 4022 } 4023 4024 /// Emits a call or invoke to the given noreturn runtime function. 4025 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke( 4026 llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) { 4027 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4028 getBundlesForFunclet(callee.getCallee()); 4029 4030 if (getInvokeDest()) { 4031 llvm::InvokeInst *invoke = 4032 Builder.CreateInvoke(callee, 4033 getUnreachableBlock(), 4034 getInvokeDest(), 4035 args, 4036 BundleList); 4037 invoke->setDoesNotReturn(); 4038 invoke->setCallingConv(getRuntimeCC()); 4039 } else { 4040 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList); 4041 call->setDoesNotReturn(); 4042 call->setCallingConv(getRuntimeCC()); 4043 Builder.CreateUnreachable(); 4044 } 4045 } 4046 4047 /// Emits a call or invoke instruction to the given nullary runtime function. 4048 llvm::CallBase * 4049 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 4050 const Twine &name) { 4051 return EmitRuntimeCallOrInvoke(callee, None, name); 4052 } 4053 4054 /// Emits a call or invoke instruction to the given runtime function. 4055 llvm::CallBase * 4056 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, 4057 ArrayRef<llvm::Value *> args, 4058 const Twine &name) { 4059 llvm::CallBase *call = EmitCallOrInvoke(callee, args, name); 4060 call->setCallingConv(getRuntimeCC()); 4061 return call; 4062 } 4063 4064 /// Emits a call or invoke instruction to the given function, depending 4065 /// on the current state of the EH stack. 4066 llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee, 4067 ArrayRef<llvm::Value *> Args, 4068 const Twine &Name) { 4069 llvm::BasicBlock *InvokeDest = getInvokeDest(); 4070 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4071 getBundlesForFunclet(Callee.getCallee()); 4072 4073 llvm::CallBase *Inst; 4074 if (!InvokeDest) 4075 Inst = Builder.CreateCall(Callee, Args, BundleList, Name); 4076 else { 4077 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 4078 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList, 4079 Name); 4080 EmitBlock(ContBB); 4081 } 4082 4083 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 4084 // optimizer it can aggressively ignore unwind edges. 4085 if (CGM.getLangOpts().ObjCAutoRefCount) 4086 AddObjCARCExceptionMetadata(Inst); 4087 4088 return Inst; 4089 } 4090 4091 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old, 4092 llvm::Value *New) { 4093 DeferredReplacements.push_back(std::make_pair(Old, New)); 4094 } 4095 4096 namespace { 4097 4098 /// Specify given \p NewAlign as the alignment of return value attribute. If 4099 /// such attribute already exists, re-set it to the maximal one of two options. 4100 LLVM_NODISCARD llvm::AttributeList 4101 maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx, 4102 const llvm::AttributeList &Attrs, 4103 llvm::Align NewAlign) { 4104 llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne(); 4105 if (CurAlign >= NewAlign) 4106 return Attrs; 4107 llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign); 4108 return Attrs 4109 .removeAttribute(Ctx, llvm::AttributeList::ReturnIndex, 4110 llvm::Attribute::AttrKind::Alignment) 4111 .addAttribute(Ctx, llvm::AttributeList::ReturnIndex, AlignAttr); 4112 } 4113 4114 template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter { 4115 protected: 4116 CodeGenFunction &CGF; 4117 4118 /// We do nothing if this is, or becomes, nullptr. 4119 const AlignedAttrTy *AA = nullptr; 4120 4121 llvm::Value *Alignment = nullptr; // May or may not be a constant. 4122 llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero. 4123 4124 AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl) 4125 : CGF(CGF_) { 4126 if (!FuncDecl) 4127 return; 4128 AA = FuncDecl->getAttr<AlignedAttrTy>(); 4129 } 4130 4131 public: 4132 /// If we can, materialize the alignment as an attribute on return value. 4133 LLVM_NODISCARD llvm::AttributeList 4134 TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) { 4135 if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment)) 4136 return Attrs; 4137 const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment); 4138 if (!AlignmentCI) 4139 return Attrs; 4140 // We may legitimately have non-power-of-2 alignment here. 4141 // If so, this is UB land, emit it via `@llvm.assume` instead. 4142 if (!AlignmentCI->getValue().isPowerOf2()) 4143 return Attrs; 4144 llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute( 4145 CGF.getLLVMContext(), Attrs, 4146 llvm::Align( 4147 AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment))); 4148 AA = nullptr; // We're done. Disallow doing anything else. 4149 return NewAttrs; 4150 } 4151 4152 /// Emit alignment assumption. 4153 /// This is a general fallback that we take if either there is an offset, 4154 /// or the alignment is variable or we are sanitizing for alignment. 4155 void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) { 4156 if (!AA) 4157 return; 4158 CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc, 4159 AA->getLocation(), Alignment, OffsetCI); 4160 AA = nullptr; // We're done. Disallow doing anything else. 4161 } 4162 }; 4163 4164 /// Helper data structure to emit `AssumeAlignedAttr`. 4165 class AssumeAlignedAttrEmitter final 4166 : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> { 4167 public: 4168 AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl) 4169 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) { 4170 if (!AA) 4171 return; 4172 // It is guaranteed that the alignment/offset are constants. 4173 Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment())); 4174 if (Expr *Offset = AA->getOffset()) { 4175 OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset)); 4176 if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset. 4177 OffsetCI = nullptr; 4178 } 4179 } 4180 }; 4181 4182 /// Helper data structure to emit `AllocAlignAttr`. 4183 class AllocAlignAttrEmitter final 4184 : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> { 4185 public: 4186 AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl, 4187 const CallArgList &CallArgs) 4188 : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) { 4189 if (!AA) 4190 return; 4191 // Alignment may or may not be a constant, and that is okay. 4192 Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()] 4193 .getRValue(CGF) 4194 .getScalarVal(); 4195 } 4196 }; 4197 4198 } // namespace 4199 4200 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 4201 const CGCallee &Callee, 4202 ReturnValueSlot ReturnValue, 4203 const CallArgList &CallArgs, 4204 llvm::CallBase **callOrInvoke, 4205 SourceLocation Loc) { 4206 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 4207 4208 assert(Callee.isOrdinary() || Callee.isVirtual()); 4209 4210 // Handle struct-return functions by passing a pointer to the 4211 // location that we would like to return into. 4212 QualType RetTy = CallInfo.getReturnType(); 4213 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 4214 4215 llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo); 4216 4217 const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl(); 4218 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) 4219 // We can only guarantee that a function is called from the correct 4220 // context/function based on the appropriate target attributes, 4221 // so only check in the case where we have both always_inline and target 4222 // since otherwise we could be making a conditional call after a check for 4223 // the proper cpu features (and it won't cause code generation issues due to 4224 // function based code generation). 4225 if (TargetDecl->hasAttr<AlwaysInlineAttr>() && 4226 TargetDecl->hasAttr<TargetAttr>()) 4227 checkTargetFeatures(Loc, FD); 4228 4229 #ifndef NDEBUG 4230 if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) { 4231 // For an inalloca varargs function, we don't expect CallInfo to match the 4232 // function pointer's type, because the inalloca struct a will have extra 4233 // fields in it for the varargs parameters. Code later in this function 4234 // bitcasts the function pointer to the type derived from CallInfo. 4235 // 4236 // In other cases, we assert that the types match up (until pointers stop 4237 // having pointee types). 4238 llvm::Type *TypeFromVal; 4239 if (Callee.isVirtual()) 4240 TypeFromVal = Callee.getVirtualFunctionType(); 4241 else 4242 TypeFromVal = 4243 Callee.getFunctionPointer()->getType()->getPointerElementType(); 4244 assert(IRFuncTy == TypeFromVal); 4245 } 4246 #endif 4247 4248 // 1. Set up the arguments. 4249 4250 // If we're using inalloca, insert the allocation after the stack save. 4251 // FIXME: Do this earlier rather than hacking it in here! 4252 Address ArgMemory = Address::invalid(); 4253 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) { 4254 const llvm::DataLayout &DL = CGM.getDataLayout(); 4255 llvm::Instruction *IP = CallArgs.getStackBase(); 4256 llvm::AllocaInst *AI; 4257 if (IP) { 4258 IP = IP->getNextNode(); 4259 AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(), 4260 "argmem", IP); 4261 } else { 4262 AI = CreateTempAlloca(ArgStruct, "argmem"); 4263 } 4264 auto Align = CallInfo.getArgStructAlignment(); 4265 AI->setAlignment(Align.getAsAlign()); 4266 AI->setUsedWithInAlloca(true); 4267 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca()); 4268 ArgMemory = Address(AI, Align); 4269 } 4270 4271 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo); 4272 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs()); 4273 4274 // If the call returns a temporary with struct return, create a temporary 4275 // alloca to hold the result, unless one is given to us. 4276 Address SRetPtr = Address::invalid(); 4277 Address SRetAlloca = Address::invalid(); 4278 llvm::Value *UnusedReturnSizePtr = nullptr; 4279 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) { 4280 if (!ReturnValue.isNull()) { 4281 SRetPtr = ReturnValue.getValue(); 4282 } else { 4283 SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca); 4284 if (HaveInsertPoint() && ReturnValue.isUnused()) { 4285 uint64_t size = 4286 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); 4287 UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer()); 4288 } 4289 } 4290 if (IRFunctionArgs.hasSRetArg()) { 4291 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer(); 4292 } else if (RetAI.isInAlloca()) { 4293 Address Addr = 4294 Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex()); 4295 Builder.CreateStore(SRetPtr.getPointer(), Addr); 4296 } 4297 } 4298 4299 Address swiftErrorTemp = Address::invalid(); 4300 Address swiftErrorArg = Address::invalid(); 4301 4302 // When passing arguments using temporary allocas, we need to add the 4303 // appropriate lifetime markers. This vector keeps track of all the lifetime 4304 // markers that need to be ended right after the call. 4305 SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall; 4306 4307 // Translate all of the arguments as necessary to match the IR lowering. 4308 assert(CallInfo.arg_size() == CallArgs.size() && 4309 "Mismatch between function signature & arguments."); 4310 unsigned ArgNo = 0; 4311 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 4312 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 4313 I != E; ++I, ++info_it, ++ArgNo) { 4314 const ABIArgInfo &ArgInfo = info_it->info; 4315 4316 // Insert a padding argument to ensure proper alignment. 4317 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 4318 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 4319 llvm::UndefValue::get(ArgInfo.getPaddingType()); 4320 4321 unsigned FirstIRArg, NumIRArgs; 4322 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 4323 4324 switch (ArgInfo.getKind()) { 4325 case ABIArgInfo::InAlloca: { 4326 assert(NumIRArgs == 0); 4327 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 4328 if (I->isAggregate()) { 4329 Address Addr = I->hasLValue() 4330 ? I->getKnownLValue().getAddress(*this) 4331 : I->getKnownRValue().getAggregateAddress(); 4332 llvm::Instruction *Placeholder = 4333 cast<llvm::Instruction>(Addr.getPointer()); 4334 4335 if (!ArgInfo.getInAllocaIndirect()) { 4336 // Replace the placeholder with the appropriate argument slot GEP. 4337 CGBuilderTy::InsertPoint IP = Builder.saveIP(); 4338 Builder.SetInsertPoint(Placeholder); 4339 Addr = Builder.CreateStructGEP(ArgMemory, 4340 ArgInfo.getInAllocaFieldIndex()); 4341 Builder.restoreIP(IP); 4342 } else { 4343 // For indirect things such as overaligned structs, replace the 4344 // placeholder with a regular aggregate temporary alloca. Store the 4345 // address of this alloca into the struct. 4346 Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp"); 4347 Address ArgSlot = Builder.CreateStructGEP( 4348 ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4349 Builder.CreateStore(Addr.getPointer(), ArgSlot); 4350 } 4351 deferPlaceholderReplacement(Placeholder, Addr.getPointer()); 4352 } else if (ArgInfo.getInAllocaIndirect()) { 4353 // Make a temporary alloca and store the address of it into the argument 4354 // struct. 4355 Address Addr = CreateMemTempWithoutCast( 4356 I->Ty, getContext().getTypeAlignInChars(I->Ty), 4357 "indirect-arg-temp"); 4358 I->copyInto(*this, Addr); 4359 Address ArgSlot = 4360 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4361 Builder.CreateStore(Addr.getPointer(), ArgSlot); 4362 } else { 4363 // Store the RValue into the argument struct. 4364 Address Addr = 4365 Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex()); 4366 unsigned AS = Addr.getType()->getPointerAddressSpace(); 4367 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS); 4368 // There are some cases where a trivial bitcast is not avoidable. The 4369 // definition of a type later in a translation unit may change it's type 4370 // from {}* to (%struct.foo*)*. 4371 if (Addr.getType() != MemType) 4372 Addr = Builder.CreateBitCast(Addr, MemType); 4373 I->copyInto(*this, Addr); 4374 } 4375 break; 4376 } 4377 4378 case ABIArgInfo::Indirect: { 4379 assert(NumIRArgs == 1); 4380 if (!I->isAggregate()) { 4381 // Make a temporary alloca to pass the argument. 4382 Address Addr = CreateMemTempWithoutCast( 4383 I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp"); 4384 IRCallArgs[FirstIRArg] = Addr.getPointer(); 4385 4386 I->copyInto(*this, Addr); 4387 } else { 4388 // We want to avoid creating an unnecessary temporary+copy here; 4389 // however, we need one in three cases: 4390 // 1. If the argument is not byval, and we are required to copy the 4391 // source. (This case doesn't occur on any common architecture.) 4392 // 2. If the argument is byval, RV is not sufficiently aligned, and 4393 // we cannot force it to be sufficiently aligned. 4394 // 3. If the argument is byval, but RV is not located in default 4395 // or alloca address space. 4396 Address Addr = I->hasLValue() 4397 ? I->getKnownLValue().getAddress(*this) 4398 : I->getKnownRValue().getAggregateAddress(); 4399 llvm::Value *V = Addr.getPointer(); 4400 CharUnits Align = ArgInfo.getIndirectAlign(); 4401 const llvm::DataLayout *TD = &CGM.getDataLayout(); 4402 4403 assert((FirstIRArg >= IRFuncTy->getNumParams() || 4404 IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() == 4405 TD->getAllocaAddrSpace()) && 4406 "indirect argument must be in alloca address space"); 4407 4408 bool NeedCopy = false; 4409 4410 if (Addr.getAlignment() < Align && 4411 llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) < 4412 Align.getAsAlign()) { 4413 NeedCopy = true; 4414 } else if (I->hasLValue()) { 4415 auto LV = I->getKnownLValue(); 4416 auto AS = LV.getAddressSpace(); 4417 4418 if (!ArgInfo.getIndirectByVal() || 4419 (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) { 4420 NeedCopy = true; 4421 } 4422 if (!getLangOpts().OpenCL) { 4423 if ((ArgInfo.getIndirectByVal() && 4424 (AS != LangAS::Default && 4425 AS != CGM.getASTAllocaAddressSpace()))) { 4426 NeedCopy = true; 4427 } 4428 } 4429 // For OpenCL even if RV is located in default or alloca address space 4430 // we don't want to perform address space cast for it. 4431 else if ((ArgInfo.getIndirectByVal() && 4432 Addr.getType()->getAddressSpace() != IRFuncTy-> 4433 getParamType(FirstIRArg)->getPointerAddressSpace())) { 4434 NeedCopy = true; 4435 } 4436 } 4437 4438 if (NeedCopy) { 4439 // Create an aligned temporary, and copy to it. 4440 Address AI = CreateMemTempWithoutCast( 4441 I->Ty, ArgInfo.getIndirectAlign(), "byval-temp"); 4442 IRCallArgs[FirstIRArg] = AI.getPointer(); 4443 4444 // Emit lifetime markers for the temporary alloca. 4445 uint64_t ByvalTempElementSize = 4446 CGM.getDataLayout().getTypeAllocSize(AI.getElementType()); 4447 llvm::Value *LifetimeSize = 4448 EmitLifetimeStart(ByvalTempElementSize, AI.getPointer()); 4449 4450 // Add cleanup code to emit the end lifetime marker after the call. 4451 if (LifetimeSize) // In case we disabled lifetime markers. 4452 CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize); 4453 4454 // Generate the copy. 4455 I->copyInto(*this, AI); 4456 } else { 4457 // Skip the extra memcpy call. 4458 auto *T = V->getType()->getPointerElementType()->getPointerTo( 4459 CGM.getDataLayout().getAllocaAddrSpace()); 4460 IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast( 4461 *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T, 4462 true); 4463 } 4464 } 4465 break; 4466 } 4467 4468 case ABIArgInfo::Ignore: 4469 assert(NumIRArgs == 0); 4470 break; 4471 4472 case ABIArgInfo::Extend: 4473 case ABIArgInfo::Direct: { 4474 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 4475 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 4476 ArgInfo.getDirectOffset() == 0) { 4477 assert(NumIRArgs == 1); 4478 llvm::Value *V; 4479 if (!I->isAggregate()) 4480 V = I->getKnownRValue().getScalarVal(); 4481 else 4482 V = Builder.CreateLoad( 4483 I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4484 : I->getKnownRValue().getAggregateAddress()); 4485 4486 // Implement swifterror by copying into a new swifterror argument. 4487 // We'll write back in the normal path out of the call. 4488 if (CallInfo.getExtParameterInfo(ArgNo).getABI() 4489 == ParameterABI::SwiftErrorResult) { 4490 assert(!swiftErrorTemp.isValid() && "multiple swifterror args"); 4491 4492 QualType pointeeTy = I->Ty->getPointeeType(); 4493 swiftErrorArg = 4494 Address(V, getContext().getTypeAlignInChars(pointeeTy)); 4495 4496 swiftErrorTemp = 4497 CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp"); 4498 V = swiftErrorTemp.getPointer(); 4499 cast<llvm::AllocaInst>(V)->setSwiftError(true); 4500 4501 llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg); 4502 Builder.CreateStore(errorValue, swiftErrorTemp); 4503 } 4504 4505 // We might have to widen integers, but we should never truncate. 4506 if (ArgInfo.getCoerceToType() != V->getType() && 4507 V->getType()->isIntegerTy()) 4508 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType()); 4509 4510 // If the argument doesn't match, perform a bitcast to coerce it. This 4511 // can happen due to trivial type mismatches. 4512 if (FirstIRArg < IRFuncTy->getNumParams() && 4513 V->getType() != IRFuncTy->getParamType(FirstIRArg)) 4514 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg)); 4515 4516 IRCallArgs[FirstIRArg] = V; 4517 break; 4518 } 4519 4520 // FIXME: Avoid the conversion through memory if possible. 4521 Address Src = Address::invalid(); 4522 if (!I->isAggregate()) { 4523 Src = CreateMemTemp(I->Ty, "coerce"); 4524 I->copyInto(*this, Src); 4525 } else { 4526 Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4527 : I->getKnownRValue().getAggregateAddress(); 4528 } 4529 4530 // If the value is offset in memory, apply the offset now. 4531 Src = emitAddressAtOffset(*this, Src, ArgInfo); 4532 4533 // Fast-isel and the optimizer generally like scalar values better than 4534 // FCAs, so we flatten them if this is safe to do for this argument. 4535 llvm::StructType *STy = 4536 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType()); 4537 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 4538 llvm::Type *SrcTy = Src.getElementType(); 4539 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy); 4540 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy); 4541 4542 // If the source type is smaller than the destination type of the 4543 // coerce-to logic, copy the source value into a temp alloca the size 4544 // of the destination type to allow loading all of it. The bits past 4545 // the source value are left undef. 4546 if (SrcSize < DstSize) { 4547 Address TempAlloca 4548 = CreateTempAlloca(STy, Src.getAlignment(), 4549 Src.getName() + ".coerce"); 4550 Builder.CreateMemCpy(TempAlloca, Src, SrcSize); 4551 Src = TempAlloca; 4552 } else { 4553 Src = Builder.CreateBitCast(Src, 4554 STy->getPointerTo(Src.getAddressSpace())); 4555 } 4556 4557 assert(NumIRArgs == STy->getNumElements()); 4558 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 4559 Address EltPtr = Builder.CreateStructGEP(Src, i); 4560 llvm::Value *LI = Builder.CreateLoad(EltPtr); 4561 IRCallArgs[FirstIRArg + i] = LI; 4562 } 4563 } else { 4564 // In the simple case, just pass the coerced loaded value. 4565 assert(NumIRArgs == 1); 4566 llvm::Value *Load = 4567 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this); 4568 4569 if (CallInfo.isCmseNSCall()) { 4570 // For certain parameter types, clear padding bits, as they may reveal 4571 // sensitive information. 4572 const Type *PTy = I->Ty.getCanonicalType().getTypePtr(); 4573 // 16-bit floating-point types are passed in a 32-bit integer or 4574 // float, with unspecified upper bits. 4575 if (PTy->isFloat16Type() || PTy->isHalfType()) { 4576 Load = EmitCMSEClearFP16(Load); 4577 } else { 4578 // Small struct/union types are passed as integer arrays. 4579 auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType()); 4580 if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType())) 4581 Load = EmitCMSEClearRecord(Load, ATy, I->Ty); 4582 } 4583 } 4584 IRCallArgs[FirstIRArg] = Load; 4585 } 4586 4587 break; 4588 } 4589 4590 case ABIArgInfo::CoerceAndExpand: { 4591 auto coercionType = ArgInfo.getCoerceAndExpandType(); 4592 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 4593 4594 llvm::Value *tempSize = nullptr; 4595 Address addr = Address::invalid(); 4596 Address AllocaAddr = Address::invalid(); 4597 if (I->isAggregate()) { 4598 addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this) 4599 : I->getKnownRValue().getAggregateAddress(); 4600 4601 } else { 4602 RValue RV = I->getKnownRValue(); 4603 assert(RV.isScalar()); // complex should always just be direct 4604 4605 llvm::Type *scalarType = RV.getScalarVal()->getType(); 4606 auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType); 4607 auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType); 4608 4609 // Materialize to a temporary. 4610 addr = CreateTempAlloca( 4611 RV.getScalarVal()->getType(), 4612 CharUnits::fromQuantity(std::max( 4613 (unsigned)layout->getAlignment().value(), scalarAlign)), 4614 "tmp", 4615 /*ArraySize=*/nullptr, &AllocaAddr); 4616 tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer()); 4617 4618 Builder.CreateStore(RV.getScalarVal(), addr); 4619 } 4620 4621 addr = Builder.CreateElementBitCast(addr, coercionType); 4622 4623 unsigned IRArgPos = FirstIRArg; 4624 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4625 llvm::Type *eltType = coercionType->getElementType(i); 4626 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4627 Address eltAddr = Builder.CreateStructGEP(addr, i); 4628 llvm::Value *elt = Builder.CreateLoad(eltAddr); 4629 IRCallArgs[IRArgPos++] = elt; 4630 } 4631 assert(IRArgPos == FirstIRArg + NumIRArgs); 4632 4633 if (tempSize) { 4634 EmitLifetimeEnd(tempSize, AllocaAddr.getPointer()); 4635 } 4636 4637 break; 4638 } 4639 4640 case ABIArgInfo::Expand: 4641 unsigned IRArgPos = FirstIRArg; 4642 ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos); 4643 assert(IRArgPos == FirstIRArg + NumIRArgs); 4644 break; 4645 } 4646 } 4647 4648 const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this); 4649 llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer(); 4650 4651 // If we're using inalloca, set up that argument. 4652 if (ArgMemory.isValid()) { 4653 llvm::Value *Arg = ArgMemory.getPointer(); 4654 if (CallInfo.isVariadic()) { 4655 // When passing non-POD arguments by value to variadic functions, we will 4656 // end up with a variadic prototype and an inalloca call site. In such 4657 // cases, we can't do any parameter mismatch checks. Give up and bitcast 4658 // the callee. 4659 unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace(); 4660 CalleePtr = 4661 Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS)); 4662 } else { 4663 llvm::Type *LastParamTy = 4664 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1); 4665 if (Arg->getType() != LastParamTy) { 4666 #ifndef NDEBUG 4667 // Assert that these structs have equivalent element types. 4668 llvm::StructType *FullTy = CallInfo.getArgStruct(); 4669 llvm::StructType *DeclaredTy = cast<llvm::StructType>( 4670 cast<llvm::PointerType>(LastParamTy)->getElementType()); 4671 assert(DeclaredTy->getNumElements() == FullTy->getNumElements()); 4672 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(), 4673 DE = DeclaredTy->element_end(), 4674 FI = FullTy->element_begin(); 4675 DI != DE; ++DI, ++FI) 4676 assert(*DI == *FI); 4677 #endif 4678 Arg = Builder.CreateBitCast(Arg, LastParamTy); 4679 } 4680 } 4681 assert(IRFunctionArgs.hasInallocaArg()); 4682 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg; 4683 } 4684 4685 // 2. Prepare the function pointer. 4686 4687 // If the callee is a bitcast of a non-variadic function to have a 4688 // variadic function pointer type, check to see if we can remove the 4689 // bitcast. This comes up with unprototyped functions. 4690 // 4691 // This makes the IR nicer, but more importantly it ensures that we 4692 // can inline the function at -O0 if it is marked always_inline. 4693 auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT, 4694 llvm::Value *Ptr) -> llvm::Function * { 4695 if (!CalleeFT->isVarArg()) 4696 return nullptr; 4697 4698 // Get underlying value if it's a bitcast 4699 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) { 4700 if (CE->getOpcode() == llvm::Instruction::BitCast) 4701 Ptr = CE->getOperand(0); 4702 } 4703 4704 llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr); 4705 if (!OrigFn) 4706 return nullptr; 4707 4708 llvm::FunctionType *OrigFT = OrigFn->getFunctionType(); 4709 4710 // If the original type is variadic, or if any of the component types 4711 // disagree, we cannot remove the cast. 4712 if (OrigFT->isVarArg() || 4713 OrigFT->getNumParams() != CalleeFT->getNumParams() || 4714 OrigFT->getReturnType() != CalleeFT->getReturnType()) 4715 return nullptr; 4716 4717 for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i) 4718 if (OrigFT->getParamType(i) != CalleeFT->getParamType(i)) 4719 return nullptr; 4720 4721 return OrigFn; 4722 }; 4723 4724 if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) { 4725 CalleePtr = OrigFn; 4726 IRFuncTy = OrigFn->getFunctionType(); 4727 } 4728 4729 // 3. Perform the actual call. 4730 4731 // Deactivate any cleanups that we're supposed to do immediately before 4732 // the call. 4733 if (!CallArgs.getCleanupsToDeactivate().empty()) 4734 deactivateArgCleanupsBeforeCall(*this, CallArgs); 4735 4736 // Assert that the arguments we computed match up. The IR verifier 4737 // will catch this, but this is a common enough source of problems 4738 // during IRGen changes that it's way better for debugging to catch 4739 // it ourselves here. 4740 #ifndef NDEBUG 4741 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()); 4742 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4743 // Inalloca argument can have different type. 4744 if (IRFunctionArgs.hasInallocaArg() && 4745 i == IRFunctionArgs.getInallocaArgNo()) 4746 continue; 4747 if (i < IRFuncTy->getNumParams()) 4748 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)); 4749 } 4750 #endif 4751 4752 // Update the largest vector width if any arguments have vector types. 4753 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 4754 if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType())) 4755 LargestVectorWidth = 4756 std::max((uint64_t)LargestVectorWidth, 4757 VT->getPrimitiveSizeInBits().getKnownMinSize()); 4758 } 4759 4760 // Compute the calling convention and attributes. 4761 unsigned CallingConv; 4762 llvm::AttributeList Attrs; 4763 CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo, 4764 Callee.getAbstractInfo(), Attrs, CallingConv, 4765 /*AttrOnCallSite=*/true); 4766 4767 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 4768 if (FD->usesFPIntrin()) 4769 // All calls within a strictfp function are marked strictfp 4770 Attrs = 4771 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4772 llvm::Attribute::StrictFP); 4773 4774 // Apply some call-site-specific attributes. 4775 // TODO: work this into building the attribute set. 4776 4777 // Apply always_inline to all calls within flatten functions. 4778 // FIXME: should this really take priority over __try, below? 4779 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() && 4780 !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) { 4781 Attrs = 4782 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4783 llvm::Attribute::AlwaysInline); 4784 } 4785 4786 // Disable inlining inside SEH __try blocks. 4787 if (isSEHTryScope()) { 4788 Attrs = 4789 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4790 llvm::Attribute::NoInline); 4791 } 4792 4793 // Decide whether to use a call or an invoke. 4794 bool CannotThrow; 4795 if (currentFunctionUsesSEHTry()) { 4796 // SEH cares about asynchronous exceptions, so everything can "throw." 4797 CannotThrow = false; 4798 } else if (isCleanupPadScope() && 4799 EHPersonality::get(*this).isMSVCXXPersonality()) { 4800 // The MSVC++ personality will implicitly terminate the program if an 4801 // exception is thrown during a cleanup outside of a try/catch. 4802 // We don't need to model anything in IR to get this behavior. 4803 CannotThrow = true; 4804 } else { 4805 // Otherwise, nounwind call sites will never throw. 4806 CannotThrow = Attrs.hasAttribute(llvm::AttributeList::FunctionIndex, 4807 llvm::Attribute::NoUnwind); 4808 } 4809 4810 // If we made a temporary, be sure to clean up after ourselves. Note that we 4811 // can't depend on being inside of an ExprWithCleanups, so we need to manually 4812 // pop this cleanup later on. Being eager about this is OK, since this 4813 // temporary is 'invisible' outside of the callee. 4814 if (UnusedReturnSizePtr) 4815 pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca, 4816 UnusedReturnSizePtr); 4817 4818 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); 4819 4820 SmallVector<llvm::OperandBundleDef, 1> BundleList = 4821 getBundlesForFunclet(CalleePtr); 4822 4823 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) 4824 if (FD->usesFPIntrin()) 4825 // All calls within a strictfp function are marked strictfp 4826 Attrs = 4827 Attrs.addAttribute(getLLVMContext(), llvm::AttributeList::FunctionIndex, 4828 llvm::Attribute::StrictFP); 4829 4830 AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl); 4831 Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs); 4832 4833 AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs); 4834 Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs); 4835 4836 // Emit the actual call/invoke instruction. 4837 llvm::CallBase *CI; 4838 if (!InvokeDest) { 4839 CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList); 4840 } else { 4841 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 4842 CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs, 4843 BundleList); 4844 EmitBlock(Cont); 4845 } 4846 if (callOrInvoke) 4847 *callOrInvoke = CI; 4848 4849 // If this is within a function that has the guard(nocf) attribute and is an 4850 // indirect call, add the "guard_nocf" attribute to this call to indicate that 4851 // Control Flow Guard checks should not be added, even if the call is inlined. 4852 if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) { 4853 if (const auto *A = FD->getAttr<CFGuardAttr>()) { 4854 if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction()) 4855 Attrs = Attrs.addAttribute( 4856 getLLVMContext(), llvm::AttributeList::FunctionIndex, "guard_nocf"); 4857 } 4858 } 4859 4860 // Apply the attributes and calling convention. 4861 CI->setAttributes(Attrs); 4862 CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 4863 4864 // Apply various metadata. 4865 4866 if (!CI->getType()->isVoidTy()) 4867 CI->setName("call"); 4868 4869 // Update largest vector width from the return type. 4870 if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType())) 4871 LargestVectorWidth = 4872 std::max((uint64_t)LargestVectorWidth, 4873 VT->getPrimitiveSizeInBits().getKnownMinSize()); 4874 4875 // Insert instrumentation or attach profile metadata at indirect call sites. 4876 // For more details, see the comment before the definition of 4877 // IPVK_IndirectCallTarget in InstrProfData.inc. 4878 if (!CI->getCalledFunction()) 4879 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget, 4880 CI, CalleePtr); 4881 4882 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 4883 // optimizer it can aggressively ignore unwind edges. 4884 if (CGM.getLangOpts().ObjCAutoRefCount) 4885 AddObjCARCExceptionMetadata(CI); 4886 4887 // Suppress tail calls if requested. 4888 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) { 4889 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>()) 4890 Call->setTailCallKind(llvm::CallInst::TCK_NoTail); 4891 } 4892 4893 // Add metadata for calls to MSAllocator functions 4894 if (getDebugInfo() && TargetDecl && 4895 TargetDecl->hasAttr<MSAllocatorAttr>()) 4896 getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy, Loc); 4897 4898 // 4. Finish the call. 4899 4900 // If the call doesn't return, finish the basic block and clear the 4901 // insertion point; this allows the rest of IRGen to discard 4902 // unreachable code. 4903 if (CI->doesNotReturn()) { 4904 if (UnusedReturnSizePtr) 4905 PopCleanupBlock(); 4906 4907 // Strip away the noreturn attribute to better diagnose unreachable UB. 4908 if (SanOpts.has(SanitizerKind::Unreachable)) { 4909 // Also remove from function since CallBase::hasFnAttr additionally checks 4910 // attributes of the called function. 4911 if (auto *F = CI->getCalledFunction()) 4912 F->removeFnAttr(llvm::Attribute::NoReturn); 4913 CI->removeAttribute(llvm::AttributeList::FunctionIndex, 4914 llvm::Attribute::NoReturn); 4915 4916 // Avoid incompatibility with ASan which relies on the `noreturn` 4917 // attribute to insert handler calls. 4918 if (SanOpts.hasOneOf(SanitizerKind::Address | 4919 SanitizerKind::KernelAddress)) { 4920 SanitizerScope SanScope(this); 4921 llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder); 4922 Builder.SetInsertPoint(CI); 4923 auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false); 4924 llvm::FunctionCallee Fn = 4925 CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return"); 4926 EmitNounwindRuntimeCall(Fn); 4927 } 4928 } 4929 4930 EmitUnreachable(Loc); 4931 Builder.ClearInsertionPoint(); 4932 4933 // FIXME: For now, emit a dummy basic block because expr emitters in 4934 // generally are not ready to handle emitting expressions at unreachable 4935 // points. 4936 EnsureInsertPoint(); 4937 4938 // Return a reasonable RValue. 4939 return GetUndefRValue(RetTy); 4940 } 4941 4942 // Perform the swifterror writeback. 4943 if (swiftErrorTemp.isValid()) { 4944 llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp); 4945 Builder.CreateStore(errorResult, swiftErrorArg); 4946 } 4947 4948 // Emit any call-associated writebacks immediately. Arguably this 4949 // should happen after any return-value munging. 4950 if (CallArgs.hasWritebacks()) 4951 emitWritebacks(*this, CallArgs); 4952 4953 // The stack cleanup for inalloca arguments has to run out of the normal 4954 // lexical order, so deactivate it and run it manually here. 4955 CallArgs.freeArgumentMemory(*this); 4956 4957 // Extract the return value. 4958 RValue Ret = [&] { 4959 switch (RetAI.getKind()) { 4960 case ABIArgInfo::CoerceAndExpand: { 4961 auto coercionType = RetAI.getCoerceAndExpandType(); 4962 4963 Address addr = SRetPtr; 4964 addr = Builder.CreateElementBitCast(addr, coercionType); 4965 4966 assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType()); 4967 bool requiresExtract = isa<llvm::StructType>(CI->getType()); 4968 4969 unsigned unpaddedIndex = 0; 4970 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 4971 llvm::Type *eltType = coercionType->getElementType(i); 4972 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 4973 Address eltAddr = Builder.CreateStructGEP(addr, i); 4974 llvm::Value *elt = CI; 4975 if (requiresExtract) 4976 elt = Builder.CreateExtractValue(elt, unpaddedIndex++); 4977 else 4978 assert(unpaddedIndex == 0); 4979 Builder.CreateStore(elt, eltAddr); 4980 } 4981 // FALLTHROUGH 4982 LLVM_FALLTHROUGH; 4983 } 4984 4985 case ABIArgInfo::InAlloca: 4986 case ABIArgInfo::Indirect: { 4987 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); 4988 if (UnusedReturnSizePtr) 4989 PopCleanupBlock(); 4990 return ret; 4991 } 4992 4993 case ABIArgInfo::Ignore: 4994 // If we are ignoring an argument that had a result, make sure to 4995 // construct the appropriate return value for our caller. 4996 return GetUndefRValue(RetTy); 4997 4998 case ABIArgInfo::Extend: 4999 case ABIArgInfo::Direct: { 5000 llvm::Type *RetIRTy = ConvertType(RetTy); 5001 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 5002 switch (getEvaluationKind(RetTy)) { 5003 case TEK_Complex: { 5004 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 5005 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 5006 return RValue::getComplex(std::make_pair(Real, Imag)); 5007 } 5008 case TEK_Aggregate: { 5009 Address DestPtr = ReturnValue.getValue(); 5010 bool DestIsVolatile = ReturnValue.isVolatile(); 5011 5012 if (!DestPtr.isValid()) { 5013 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 5014 DestIsVolatile = false; 5015 } 5016 BuildAggStore(*this, CI, DestPtr, DestIsVolatile); 5017 return RValue::getAggregate(DestPtr); 5018 } 5019 case TEK_Scalar: { 5020 // If the argument doesn't match, perform a bitcast to coerce it. This 5021 // can happen due to trivial type mismatches. 5022 llvm::Value *V = CI; 5023 if (V->getType() != RetIRTy) 5024 V = Builder.CreateBitCast(V, RetIRTy); 5025 return RValue::get(V); 5026 } 5027 } 5028 llvm_unreachable("bad evaluation kind"); 5029 } 5030 5031 Address DestPtr = ReturnValue.getValue(); 5032 bool DestIsVolatile = ReturnValue.isVolatile(); 5033 5034 if (!DestPtr.isValid()) { 5035 DestPtr = CreateMemTemp(RetTy, "coerce"); 5036 DestIsVolatile = false; 5037 } 5038 5039 // If the value is offset in memory, apply the offset now. 5040 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI); 5041 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 5042 5043 return convertTempToRValue(DestPtr, RetTy, SourceLocation()); 5044 } 5045 5046 case ABIArgInfo::Expand: 5047 llvm_unreachable("Invalid ABI kind for return argument"); 5048 } 5049 5050 llvm_unreachable("Unhandled ABIArgInfo::Kind"); 5051 } (); 5052 5053 // Emit the assume_aligned check on the return value. 5054 if (Ret.isScalar() && TargetDecl) { 5055 AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret); 5056 AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret); 5057 } 5058 5059 // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though 5060 // we can't use the full cleanup mechanism. 5061 for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall) 5062 LifetimeEnd.Emit(*this, /*Flags=*/{}); 5063 5064 if (!ReturnValue.isExternallyDestructed() && 5065 RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct) 5066 pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(), 5067 RetTy); 5068 5069 return Ret; 5070 } 5071 5072 CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const { 5073 if (isVirtual()) { 5074 const CallExpr *CE = getVirtualCallExpr(); 5075 return CGF.CGM.getCXXABI().getVirtualFunctionPointer( 5076 CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(), 5077 CE ? CE->getBeginLoc() : SourceLocation()); 5078 } 5079 5080 return *this; 5081 } 5082 5083 /* VarArg handling */ 5084 5085 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) { 5086 VAListAddr = VE->isMicrosoftABI() 5087 ? EmitMSVAListRef(VE->getSubExpr()) 5088 : EmitVAListRef(VE->getSubExpr()); 5089 QualType Ty = VE->getType(); 5090 if (VE->isMicrosoftABI()) 5091 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty); 5092 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty); 5093 } 5094