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