1 //===--- CGCall.cpp - Encapsulate calling convention details --------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // These classes wrap the information about a call or function 11 // definition used to handle ABI compliancy. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "CGCall.h" 16 #include "ABIInfo.h" 17 #include "CGBlocks.h" 18 #include "CGCXXABI.h" 19 #include "CGCleanup.h" 20 #include "CodeGenFunction.h" 21 #include "CodeGenModule.h" 22 #include "TargetInfo.h" 23 #include "clang/AST/Decl.h" 24 #include "clang/AST/DeclCXX.h" 25 #include "clang/AST/DeclObjC.h" 26 #include "clang/Basic/TargetBuiltins.h" 27 #include "clang/Basic/TargetInfo.h" 28 #include "clang/CodeGen/CGFunctionInfo.h" 29 #include "clang/Frontend/CodeGenOptions.h" 30 #include "llvm/ADT/StringExtras.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/CallSite.h" 33 #include "llvm/IR/DataLayout.h" 34 #include "llvm/IR/InlineAsm.h" 35 #include "llvm/IR/Intrinsics.h" 36 #include "llvm/IR/IntrinsicInst.h" 37 #include "llvm/Transforms/Utils/Local.h" 38 using namespace clang; 39 using namespace CodeGen; 40 41 /***/ 42 43 static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) { 44 switch (CC) { 45 default: return llvm::CallingConv::C; 46 case CC_X86StdCall: return llvm::CallingConv::X86_StdCall; 47 case CC_X86FastCall: return llvm::CallingConv::X86_FastCall; 48 case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall; 49 case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64; 50 case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV; 51 case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS; 52 case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP; 53 case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI; 54 // TODO: Add support for __pascal to LLVM. 55 case CC_X86Pascal: return llvm::CallingConv::C; 56 // TODO: Add support for __vectorcall to LLVM. 57 case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall; 58 case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC; 59 case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL; 60 case CC_PreserveMost: return llvm::CallingConv::PreserveMost; 61 case CC_PreserveAll: return llvm::CallingConv::PreserveAll; 62 } 63 } 64 65 /// Derives the 'this' type for codegen purposes, i.e. ignoring method 66 /// qualification. 67 /// FIXME: address space qualification? 68 static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) { 69 QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal(); 70 return Context.getPointerType(CanQualType::CreateUnsafe(RecTy)); 71 } 72 73 /// Returns the canonical formal type of the given C++ method. 74 static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) { 75 return MD->getType()->getCanonicalTypeUnqualified() 76 .getAs<FunctionProtoType>(); 77 } 78 79 /// Returns the "extra-canonicalized" return type, which discards 80 /// qualifiers on the return type. Codegen doesn't care about them, 81 /// and it makes ABI code a little easier to be able to assume that 82 /// all parameter and return types are top-level unqualified. 83 static CanQualType GetReturnType(QualType RetTy) { 84 return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType(); 85 } 86 87 /// Arrange the argument and result information for a value of the given 88 /// unprototyped freestanding function type. 89 const CGFunctionInfo & 90 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) { 91 // When translating an unprototyped function type, always use a 92 // variadic type. 93 return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(), 94 /*instanceMethod=*/false, 95 /*chainCall=*/false, None, 96 FTNP->getExtInfo(), {}, RequiredArgs(0)); 97 } 98 99 /// Adds the formal paramaters in FPT to the given prefix. If any parameter in 100 /// FPT has pass_object_size attrs, then we'll add parameters for those, too. 101 static void appendParameterTypes(const CodeGenTypes &CGT, 102 SmallVectorImpl<CanQualType> &prefix, 103 SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos, 104 CanQual<FunctionProtoType> FPT, 105 const FunctionDecl *FD) { 106 // Fill out paramInfos. 107 if (FPT->hasExtParameterInfos() || !paramInfos.empty()) { 108 assert(paramInfos.size() <= prefix.size()); 109 auto protoParamInfos = FPT->getExtParameterInfos(); 110 paramInfos.reserve(prefix.size() + protoParamInfos.size()); 111 paramInfos.resize(prefix.size()); 112 paramInfos.append(paramInfos.begin(), paramInfos.end()); 113 } 114 115 // Fast path: unknown target. 116 if (FD == nullptr) { 117 prefix.append(FPT->param_type_begin(), FPT->param_type_end()); 118 return; 119 } 120 121 // In the vast majority cases, we'll have precisely FPT->getNumParams() 122 // parameters; the only thing that can change this is the presence of 123 // pass_object_size. So, we preallocate for the common case. 124 prefix.reserve(prefix.size() + FPT->getNumParams()); 125 126 assert(FD->getNumParams() == FPT->getNumParams()); 127 for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) { 128 prefix.push_back(FPT->getParamType(I)); 129 if (FD->getParamDecl(I)->hasAttr<PassObjectSizeAttr>()) 130 prefix.push_back(CGT.getContext().getSizeType()); 131 } 132 } 133 134 /// Arrange the LLVM function layout for a value of the given function 135 /// type, on top of any implicit parameters already stored. 136 static const CGFunctionInfo & 137 arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod, 138 SmallVectorImpl<CanQualType> &prefix, 139 CanQual<FunctionProtoType> FTP, 140 const FunctionDecl *FD) { 141 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 142 RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size()); 143 // FIXME: Kill copy. 144 appendParameterTypes(CGT, prefix, paramInfos, FTP, FD); 145 CanQualType resultType = FTP->getReturnType().getUnqualifiedType(); 146 147 return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod, 148 /*chainCall=*/false, prefix, 149 FTP->getExtInfo(), paramInfos, 150 required); 151 } 152 153 /// Arrange the argument and result information for a value of the 154 /// given freestanding function type. 155 const CGFunctionInfo & 156 CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP, 157 const FunctionDecl *FD) { 158 SmallVector<CanQualType, 16> argTypes; 159 return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes, 160 FTP, FD); 161 } 162 163 static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) { 164 // Set the appropriate calling convention for the Function. 165 if (D->hasAttr<StdCallAttr>()) 166 return CC_X86StdCall; 167 168 if (D->hasAttr<FastCallAttr>()) 169 return CC_X86FastCall; 170 171 if (D->hasAttr<ThisCallAttr>()) 172 return CC_X86ThisCall; 173 174 if (D->hasAttr<VectorCallAttr>()) 175 return CC_X86VectorCall; 176 177 if (D->hasAttr<PascalAttr>()) 178 return CC_X86Pascal; 179 180 if (PcsAttr *PCS = D->getAttr<PcsAttr>()) 181 return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP); 182 183 if (D->hasAttr<IntelOclBiccAttr>()) 184 return CC_IntelOclBicc; 185 186 if (D->hasAttr<MSABIAttr>()) 187 return IsWindows ? CC_C : CC_X86_64Win64; 188 189 if (D->hasAttr<SysVABIAttr>()) 190 return IsWindows ? CC_X86_64SysV : CC_C; 191 192 if (D->hasAttr<PreserveMostAttr>()) 193 return CC_PreserveMost; 194 195 if (D->hasAttr<PreserveAllAttr>()) 196 return CC_PreserveAll; 197 198 return CC_C; 199 } 200 201 /// Arrange the argument and result information for a call to an 202 /// unknown C++ non-static member function of the given abstract type. 203 /// (Zero value of RD means we don't have any meaningful "this" argument type, 204 /// so fall back to a generic pointer type). 205 /// The member function must be an ordinary function, i.e. not a 206 /// constructor or destructor. 207 const CGFunctionInfo & 208 CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD, 209 const FunctionProtoType *FTP, 210 const CXXMethodDecl *MD) { 211 SmallVector<CanQualType, 16> argTypes; 212 213 // Add the 'this' pointer. 214 if (RD) 215 argTypes.push_back(GetThisType(Context, RD)); 216 else 217 argTypes.push_back(Context.VoidPtrTy); 218 219 return ::arrangeLLVMFunctionInfo( 220 *this, true, argTypes, 221 FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>(), MD); 222 } 223 224 /// Arrange the argument and result information for a declaration or 225 /// definition of the given C++ non-static member function. The 226 /// member function must be an ordinary function, i.e. not a 227 /// constructor or destructor. 228 const CGFunctionInfo & 229 CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) { 230 assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!"); 231 assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!"); 232 233 CanQual<FunctionProtoType> prototype = GetFormalType(MD); 234 235 if (MD->isInstance()) { 236 // The abstract case is perfectly fine. 237 const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD); 238 return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD); 239 } 240 241 return arrangeFreeFunctionType(prototype, MD); 242 } 243 244 const CGFunctionInfo & 245 CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD, 246 StructorType Type) { 247 248 SmallVector<CanQualType, 16> argTypes; 249 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 250 argTypes.push_back(GetThisType(Context, MD->getParent())); 251 252 GlobalDecl GD; 253 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 254 GD = GlobalDecl(CD, toCXXCtorType(Type)); 255 } else { 256 auto *DD = dyn_cast<CXXDestructorDecl>(MD); 257 GD = GlobalDecl(DD, toCXXDtorType(Type)); 258 } 259 260 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 261 262 // Add the formal parameters. 263 appendParameterTypes(*this, argTypes, paramInfos, FTP, MD); 264 265 TheCXXABI.buildStructorSignature(MD, Type, argTypes); 266 267 RequiredArgs required = 268 (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All); 269 270 FunctionType::ExtInfo extInfo = FTP->getExtInfo(); 271 CanQualType resultType = TheCXXABI.HasThisReturn(GD) 272 ? argTypes.front() 273 : TheCXXABI.hasMostDerivedReturn(GD) 274 ? CGM.getContext().VoidPtrTy 275 : Context.VoidTy; 276 return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true, 277 /*chainCall=*/false, argTypes, extInfo, 278 paramInfos, required); 279 } 280 281 static SmallVector<CanQualType, 16> 282 getArgTypesForCall(ASTContext &ctx, const CallArgList &args) { 283 SmallVector<CanQualType, 16> argTypes; 284 for (auto &arg : args) 285 argTypes.push_back(ctx.getCanonicalParamType(arg.Ty)); 286 return argTypes; 287 } 288 289 static SmallVector<CanQualType, 16> 290 getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) { 291 SmallVector<CanQualType, 16> argTypes; 292 for (auto &arg : args) 293 argTypes.push_back(ctx.getCanonicalParamType(arg->getType())); 294 return argTypes; 295 } 296 297 static void addExtParameterInfosForCall( 298 llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> ¶mInfos, 299 const FunctionProtoType *proto, 300 unsigned prefixArgs, 301 unsigned totalArgs) { 302 assert(proto->hasExtParameterInfos()); 303 assert(paramInfos.size() <= prefixArgs); 304 assert(proto->getNumParams() + prefixArgs <= totalArgs); 305 306 // Add default infos for any prefix args that don't already have infos. 307 paramInfos.resize(prefixArgs); 308 309 // Add infos for the prototype. 310 auto protoInfos = proto->getExtParameterInfos(); 311 paramInfos.append(protoInfos.begin(), protoInfos.end()); 312 313 // Add default infos for the variadic arguments. 314 paramInfos.resize(totalArgs); 315 } 316 317 static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> 318 getExtParameterInfosForCall(const FunctionProtoType *proto, 319 unsigned prefixArgs, unsigned totalArgs) { 320 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result; 321 if (proto->hasExtParameterInfos()) { 322 addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs); 323 } 324 return result; 325 } 326 327 /// Arrange a call to a C++ method, passing the given arguments. 328 const CGFunctionInfo & 329 CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args, 330 const CXXConstructorDecl *D, 331 CXXCtorType CtorKind, 332 unsigned ExtraArgs) { 333 // FIXME: Kill copy. 334 SmallVector<CanQualType, 16> ArgTypes; 335 for (const auto &Arg : args) 336 ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 337 338 CanQual<FunctionProtoType> FPT = GetFormalType(D); 339 RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs); 340 GlobalDecl GD(D, CtorKind); 341 CanQualType ResultType = TheCXXABI.HasThisReturn(GD) 342 ? ArgTypes.front() 343 : TheCXXABI.hasMostDerivedReturn(GD) 344 ? CGM.getContext().VoidPtrTy 345 : Context.VoidTy; 346 347 FunctionType::ExtInfo Info = FPT->getExtInfo(); 348 auto ParamInfos = getExtParameterInfosForCall(FPT.getTypePtr(), 1 + ExtraArgs, 349 ArgTypes.size()); 350 return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true, 351 /*chainCall=*/false, ArgTypes, Info, 352 ParamInfos, Required); 353 } 354 355 /// Arrange the argument and result information for the declaration or 356 /// definition of the given function. 357 const CGFunctionInfo & 358 CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) { 359 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) 360 if (MD->isInstance()) 361 return arrangeCXXMethodDeclaration(MD); 362 363 CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified(); 364 365 assert(isa<FunctionType>(FTy)); 366 367 // When declaring a function without a prototype, always use a 368 // non-variadic type. 369 if (isa<FunctionNoProtoType>(FTy)) { 370 CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>(); 371 return arrangeLLVMFunctionInfo( 372 noProto->getReturnType(), /*instanceMethod=*/false, 373 /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All); 374 } 375 376 assert(isa<FunctionProtoType>(FTy)); 377 return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>(), FD); 378 } 379 380 /// Arrange the argument and result information for the declaration or 381 /// definition of an Objective-C method. 382 const CGFunctionInfo & 383 CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) { 384 // It happens that this is the same as a call with no optional 385 // arguments, except also using the formal 'self' type. 386 return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType()); 387 } 388 389 /// Arrange the argument and result information for the function type 390 /// through which to perform a send to the given Objective-C method, 391 /// using the given receiver type. The receiver type is not always 392 /// the 'self' type of the method or even an Objective-C pointer type. 393 /// This is *not* the right method for actually performing such a 394 /// message send, due to the possibility of optional arguments. 395 const CGFunctionInfo & 396 CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD, 397 QualType receiverType) { 398 SmallVector<CanQualType, 16> argTys; 399 argTys.push_back(Context.getCanonicalParamType(receiverType)); 400 argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType())); 401 // FIXME: Kill copy? 402 for (const auto *I : MD->params()) { 403 argTys.push_back(Context.getCanonicalParamType(I->getType())); 404 } 405 406 FunctionType::ExtInfo einfo; 407 bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows(); 408 einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows)); 409 410 if (getContext().getLangOpts().ObjCAutoRefCount && 411 MD->hasAttr<NSReturnsRetainedAttr>()) 412 einfo = einfo.withProducesResult(true); 413 414 RequiredArgs required = 415 (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All); 416 417 return arrangeLLVMFunctionInfo( 418 GetReturnType(MD->getReturnType()), /*instanceMethod=*/false, 419 /*chainCall=*/false, argTys, einfo, {}, required); 420 } 421 422 const CGFunctionInfo & 423 CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType, 424 const CallArgList &args) { 425 auto argTypes = getArgTypesForCall(Context, args); 426 FunctionType::ExtInfo einfo; 427 428 return arrangeLLVMFunctionInfo( 429 GetReturnType(returnType), /*instanceMethod=*/false, 430 /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All); 431 } 432 433 const CGFunctionInfo & 434 CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) { 435 // FIXME: Do we need to handle ObjCMethodDecl? 436 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 437 438 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) 439 return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType())); 440 441 if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) 442 return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType())); 443 444 return arrangeFunctionDeclaration(FD); 445 } 446 447 /// Arrange a thunk that takes 'this' as the first parameter followed by 448 /// varargs. Return a void pointer, regardless of the actual return type. 449 /// The body of the thunk will end in a musttail call to a function of the 450 /// correct type, and the caller will bitcast the function to the correct 451 /// prototype. 452 const CGFunctionInfo & 453 CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) { 454 assert(MD->isVirtual() && "only virtual memptrs have thunks"); 455 CanQual<FunctionProtoType> FTP = GetFormalType(MD); 456 CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) }; 457 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false, 458 /*chainCall=*/false, ArgTys, 459 FTP->getExtInfo(), {}, RequiredArgs(1)); 460 } 461 462 const CGFunctionInfo & 463 CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD, 464 CXXCtorType CT) { 465 assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure); 466 467 CanQual<FunctionProtoType> FTP = GetFormalType(CD); 468 SmallVector<CanQualType, 2> ArgTys; 469 const CXXRecordDecl *RD = CD->getParent(); 470 ArgTys.push_back(GetThisType(Context, RD)); 471 if (CT == Ctor_CopyingClosure) 472 ArgTys.push_back(*FTP->param_type_begin()); 473 if (RD->getNumVBases() > 0) 474 ArgTys.push_back(Context.IntTy); 475 CallingConv CC = Context.getDefaultCallingConvention( 476 /*IsVariadic=*/false, /*IsCXXMethod=*/true); 477 return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true, 478 /*chainCall=*/false, ArgTys, 479 FunctionType::ExtInfo(CC), {}, 480 RequiredArgs::All); 481 } 482 483 /// Arrange a call as unto a free function, except possibly with an 484 /// additional number of formal parameters considered required. 485 static const CGFunctionInfo & 486 arrangeFreeFunctionLikeCall(CodeGenTypes &CGT, 487 CodeGenModule &CGM, 488 const CallArgList &args, 489 const FunctionType *fnType, 490 unsigned numExtraRequiredArgs, 491 bool chainCall) { 492 assert(args.size() >= numExtraRequiredArgs); 493 494 llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 495 496 // In most cases, there are no optional arguments. 497 RequiredArgs required = RequiredArgs::All; 498 499 // If we have a variadic prototype, the required arguments are the 500 // extra prefix plus the arguments in the prototype. 501 if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) { 502 if (proto->isVariadic()) 503 required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs); 504 505 if (proto->hasExtParameterInfos()) 506 addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs, 507 args.size()); 508 509 // If we don't have a prototype at all, but we're supposed to 510 // explicitly use the variadic convention for unprototyped calls, 511 // treat all of the arguments as required but preserve the nominal 512 // possibility of variadics. 513 } else if (CGM.getTargetCodeGenInfo() 514 .isNoProtoCallVariadic(args, 515 cast<FunctionNoProtoType>(fnType))) { 516 required = RequiredArgs(args.size()); 517 } 518 519 // FIXME: Kill copy. 520 SmallVector<CanQualType, 16> argTypes; 521 for (const auto &arg : args) 522 argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty)); 523 return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()), 524 /*instanceMethod=*/false, chainCall, 525 argTypes, fnType->getExtInfo(), paramInfos, 526 required); 527 } 528 529 /// Figure out the rules for calling a function with the given formal 530 /// type using the given arguments. The arguments are necessary 531 /// because the function might be unprototyped, in which case it's 532 /// target-dependent in crazy ways. 533 const CGFunctionInfo & 534 CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args, 535 const FunctionType *fnType, 536 bool chainCall) { 537 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 538 chainCall ? 1 : 0, chainCall); 539 } 540 541 /// A block function is essentially a free function with an 542 /// extra implicit argument. 543 const CGFunctionInfo & 544 CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args, 545 const FunctionType *fnType) { 546 return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1, 547 /*chainCall=*/false); 548 } 549 550 const CGFunctionInfo & 551 CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto, 552 const FunctionArgList ¶ms) { 553 auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size()); 554 auto argTypes = getArgTypesForDeclaration(Context, params); 555 556 return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()), 557 /*instanceMethod*/ false, /*chainCall*/ false, 558 argTypes, proto->getExtInfo(), paramInfos, 559 RequiredArgs::forPrototypePlus(proto, 1)); 560 } 561 562 const CGFunctionInfo & 563 CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType, 564 const CallArgList &args) { 565 // FIXME: Kill copy. 566 SmallVector<CanQualType, 16> argTypes; 567 for (const auto &Arg : args) 568 argTypes.push_back(Context.getCanonicalParamType(Arg.Ty)); 569 return arrangeLLVMFunctionInfo( 570 GetReturnType(resultType), /*instanceMethod=*/false, 571 /*chainCall=*/false, argTypes, FunctionType::ExtInfo(), 572 /*paramInfos=*/ {}, RequiredArgs::All); 573 } 574 575 const CGFunctionInfo & 576 CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType, 577 const FunctionArgList &args) { 578 auto argTypes = getArgTypesForDeclaration(Context, args); 579 580 return arrangeLLVMFunctionInfo( 581 GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false, 582 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All); 583 } 584 585 const CGFunctionInfo & 586 CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType, 587 ArrayRef<CanQualType> argTypes) { 588 return arrangeLLVMFunctionInfo( 589 resultType, /*instanceMethod=*/false, /*chainCall=*/false, 590 argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All); 591 } 592 593 594 /// Arrange a call to a C++ method, passing the given arguments. 595 const CGFunctionInfo & 596 CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args, 597 const FunctionProtoType *proto, 598 RequiredArgs required) { 599 unsigned numRequiredArgs = 600 (proto->isVariadic() ? required.getNumRequiredArgs() : args.size()); 601 unsigned numPrefixArgs = numRequiredArgs - proto->getNumParams(); 602 auto paramInfos = 603 getExtParameterInfosForCall(proto, numPrefixArgs, args.size()); 604 605 // FIXME: Kill copy. 606 auto argTypes = getArgTypesForCall(Context, args); 607 608 FunctionType::ExtInfo info = proto->getExtInfo(); 609 return arrangeLLVMFunctionInfo( 610 GetReturnType(proto->getReturnType()), /*instanceMethod=*/true, 611 /*chainCall=*/false, argTypes, info, paramInfos, required); 612 } 613 614 const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() { 615 return arrangeLLVMFunctionInfo( 616 getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false, 617 None, FunctionType::ExtInfo(), {}, RequiredArgs::All); 618 } 619 620 const CGFunctionInfo & 621 CodeGenTypes::arrangeCall(const CGFunctionInfo &signature, 622 const CallArgList &args) { 623 assert(signature.arg_size() <= args.size()); 624 if (signature.arg_size() == args.size()) 625 return signature; 626 627 SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos; 628 auto sigParamInfos = signature.getExtParameterInfos(); 629 if (!sigParamInfos.empty()) { 630 paramInfos.append(sigParamInfos.begin(), sigParamInfos.end()); 631 paramInfos.resize(args.size()); 632 } 633 634 auto argTypes = getArgTypesForCall(Context, args); 635 636 assert(signature.getRequiredArgs().allowsOptionalArgs()); 637 return arrangeLLVMFunctionInfo(signature.getReturnType(), 638 signature.isInstanceMethod(), 639 signature.isChainCall(), 640 argTypes, 641 signature.getExtInfo(), 642 paramInfos, 643 signature.getRequiredArgs()); 644 } 645 646 /// Arrange the argument and result information for an abstract value 647 /// of a given function type. This is the method which all of the 648 /// above functions ultimately defer to. 649 const CGFunctionInfo & 650 CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType, 651 bool instanceMethod, 652 bool chainCall, 653 ArrayRef<CanQualType> argTypes, 654 FunctionType::ExtInfo info, 655 ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos, 656 RequiredArgs required) { 657 assert(std::all_of(argTypes.begin(), argTypes.end(), 658 std::mem_fun_ref(&CanQualType::isCanonicalAsParam))); 659 660 // Lookup or create unique function info. 661 llvm::FoldingSetNodeID ID; 662 CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos, 663 required, resultType, argTypes); 664 665 void *insertPos = nullptr; 666 CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos); 667 if (FI) 668 return *FI; 669 670 unsigned CC = ClangCallConvToLLVMCallConv(info.getCC()); 671 672 // Construct the function info. We co-allocate the ArgInfos. 673 FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info, 674 paramInfos, resultType, argTypes, required); 675 FunctionInfos.InsertNode(FI, insertPos); 676 677 bool inserted = FunctionsBeingProcessed.insert(FI).second; 678 (void)inserted; 679 assert(inserted && "Recursively being processed?"); 680 681 // Compute ABI information. 682 getABIInfo().computeInfo(*FI); 683 684 // Loop over all of the computed argument and return value info. If any of 685 // them are direct or extend without a specified coerce type, specify the 686 // default now. 687 ABIArgInfo &retInfo = FI->getReturnInfo(); 688 if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr) 689 retInfo.setCoerceToType(ConvertType(FI->getReturnType())); 690 691 for (auto &I : FI->arguments()) 692 if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr) 693 I.info.setCoerceToType(ConvertType(I.type)); 694 695 bool erased = FunctionsBeingProcessed.erase(FI); (void)erased; 696 assert(erased && "Not in set?"); 697 698 return *FI; 699 } 700 701 CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC, 702 bool instanceMethod, 703 bool chainCall, 704 const FunctionType::ExtInfo &info, 705 ArrayRef<ExtParameterInfo> paramInfos, 706 CanQualType resultType, 707 ArrayRef<CanQualType> argTypes, 708 RequiredArgs required) { 709 assert(paramInfos.empty() || paramInfos.size() == argTypes.size()); 710 711 void *buffer = 712 operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>( 713 argTypes.size() + 1, paramInfos.size())); 714 715 CGFunctionInfo *FI = new(buffer) CGFunctionInfo(); 716 FI->CallingConvention = llvmCC; 717 FI->EffectiveCallingConvention = llvmCC; 718 FI->ASTCallingConvention = info.getCC(); 719 FI->InstanceMethod = instanceMethod; 720 FI->ChainCall = chainCall; 721 FI->NoReturn = info.getNoReturn(); 722 FI->ReturnsRetained = info.getProducesResult(); 723 FI->Required = required; 724 FI->HasRegParm = info.getHasRegParm(); 725 FI->RegParm = info.getRegParm(); 726 FI->ArgStruct = nullptr; 727 FI->ArgStructAlign = 0; 728 FI->NumArgs = argTypes.size(); 729 FI->HasExtParameterInfos = !paramInfos.empty(); 730 FI->getArgsBuffer()[0].type = resultType; 731 for (unsigned i = 0, e = argTypes.size(); i != e; ++i) 732 FI->getArgsBuffer()[i + 1].type = argTypes[i]; 733 for (unsigned i = 0, e = paramInfos.size(); i != e; ++i) 734 FI->getExtParameterInfosBuffer()[i] = paramInfos[i]; 735 return FI; 736 } 737 738 /***/ 739 740 namespace { 741 // ABIArgInfo::Expand implementation. 742 743 // Specifies the way QualType passed as ABIArgInfo::Expand is expanded. 744 struct TypeExpansion { 745 enum TypeExpansionKind { 746 // Elements of constant arrays are expanded recursively. 747 TEK_ConstantArray, 748 // Record fields are expanded recursively (but if record is a union, only 749 // the field with the largest size is expanded). 750 TEK_Record, 751 // For complex types, real and imaginary parts are expanded recursively. 752 TEK_Complex, 753 // All other types are not expandable. 754 TEK_None 755 }; 756 757 const TypeExpansionKind Kind; 758 759 TypeExpansion(TypeExpansionKind K) : Kind(K) {} 760 virtual ~TypeExpansion() {} 761 }; 762 763 struct ConstantArrayExpansion : TypeExpansion { 764 QualType EltTy; 765 uint64_t NumElts; 766 767 ConstantArrayExpansion(QualType EltTy, uint64_t NumElts) 768 : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {} 769 static bool classof(const TypeExpansion *TE) { 770 return TE->Kind == TEK_ConstantArray; 771 } 772 }; 773 774 struct RecordExpansion : TypeExpansion { 775 SmallVector<const CXXBaseSpecifier *, 1> Bases; 776 777 SmallVector<const FieldDecl *, 1> Fields; 778 779 RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases, 780 SmallVector<const FieldDecl *, 1> &&Fields) 781 : TypeExpansion(TEK_Record), Bases(std::move(Bases)), 782 Fields(std::move(Fields)) {} 783 static bool classof(const TypeExpansion *TE) { 784 return TE->Kind == TEK_Record; 785 } 786 }; 787 788 struct ComplexExpansion : TypeExpansion { 789 QualType EltTy; 790 791 ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {} 792 static bool classof(const TypeExpansion *TE) { 793 return TE->Kind == TEK_Complex; 794 } 795 }; 796 797 struct NoExpansion : TypeExpansion { 798 NoExpansion() : TypeExpansion(TEK_None) {} 799 static bool classof(const TypeExpansion *TE) { 800 return TE->Kind == TEK_None; 801 } 802 }; 803 } // namespace 804 805 static std::unique_ptr<TypeExpansion> 806 getTypeExpansion(QualType Ty, const ASTContext &Context) { 807 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) { 808 return llvm::make_unique<ConstantArrayExpansion>( 809 AT->getElementType(), AT->getSize().getZExtValue()); 810 } 811 if (const RecordType *RT = Ty->getAs<RecordType>()) { 812 SmallVector<const CXXBaseSpecifier *, 1> Bases; 813 SmallVector<const FieldDecl *, 1> Fields; 814 const RecordDecl *RD = RT->getDecl(); 815 assert(!RD->hasFlexibleArrayMember() && 816 "Cannot expand structure with flexible array."); 817 if (RD->isUnion()) { 818 // Unions can be here only in degenerative cases - all the fields are same 819 // after flattening. Thus we have to use the "largest" field. 820 const FieldDecl *LargestFD = nullptr; 821 CharUnits UnionSize = CharUnits::Zero(); 822 823 for (const auto *FD : RD->fields()) { 824 // Skip zero length bitfields. 825 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0) 826 continue; 827 assert(!FD->isBitField() && 828 "Cannot expand structure with bit-field members."); 829 CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType()); 830 if (UnionSize < FieldSize) { 831 UnionSize = FieldSize; 832 LargestFD = FD; 833 } 834 } 835 if (LargestFD) 836 Fields.push_back(LargestFD); 837 } else { 838 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) { 839 assert(!CXXRD->isDynamicClass() && 840 "cannot expand vtable pointers in dynamic classes"); 841 for (const CXXBaseSpecifier &BS : CXXRD->bases()) 842 Bases.push_back(&BS); 843 } 844 845 for (const auto *FD : RD->fields()) { 846 // Skip zero length bitfields. 847 if (FD->isBitField() && FD->getBitWidthValue(Context) == 0) 848 continue; 849 assert(!FD->isBitField() && 850 "Cannot expand structure with bit-field members."); 851 Fields.push_back(FD); 852 } 853 } 854 return llvm::make_unique<RecordExpansion>(std::move(Bases), 855 std::move(Fields)); 856 } 857 if (const ComplexType *CT = Ty->getAs<ComplexType>()) { 858 return llvm::make_unique<ComplexExpansion>(CT->getElementType()); 859 } 860 return llvm::make_unique<NoExpansion>(); 861 } 862 863 static int getExpansionSize(QualType Ty, const ASTContext &Context) { 864 auto Exp = getTypeExpansion(Ty, Context); 865 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 866 return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context); 867 } 868 if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 869 int Res = 0; 870 for (auto BS : RExp->Bases) 871 Res += getExpansionSize(BS->getType(), Context); 872 for (auto FD : RExp->Fields) 873 Res += getExpansionSize(FD->getType(), Context); 874 return Res; 875 } 876 if (isa<ComplexExpansion>(Exp.get())) 877 return 2; 878 assert(isa<NoExpansion>(Exp.get())); 879 return 1; 880 } 881 882 void 883 CodeGenTypes::getExpandedTypes(QualType Ty, 884 SmallVectorImpl<llvm::Type *>::iterator &TI) { 885 auto Exp = getTypeExpansion(Ty, Context); 886 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 887 for (int i = 0, n = CAExp->NumElts; i < n; i++) { 888 getExpandedTypes(CAExp->EltTy, TI); 889 } 890 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 891 for (auto BS : RExp->Bases) 892 getExpandedTypes(BS->getType(), TI); 893 for (auto FD : RExp->Fields) 894 getExpandedTypes(FD->getType(), TI); 895 } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) { 896 llvm::Type *EltTy = ConvertType(CExp->EltTy); 897 *TI++ = EltTy; 898 *TI++ = EltTy; 899 } else { 900 assert(isa<NoExpansion>(Exp.get())); 901 *TI++ = ConvertType(Ty); 902 } 903 } 904 905 static void forConstantArrayExpansion(CodeGenFunction &CGF, 906 ConstantArrayExpansion *CAE, 907 Address BaseAddr, 908 llvm::function_ref<void(Address)> Fn) { 909 CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy); 910 CharUnits EltAlign = 911 BaseAddr.getAlignment().alignmentOfArrayElement(EltSize); 912 913 for (int i = 0, n = CAE->NumElts; i < n; i++) { 914 llvm::Value *EltAddr = 915 CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i); 916 Fn(Address(EltAddr, EltAlign)); 917 } 918 } 919 920 void CodeGenFunction::ExpandTypeFromArgs( 921 QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) { 922 assert(LV.isSimple() && 923 "Unexpected non-simple lvalue during struct expansion."); 924 925 auto Exp = getTypeExpansion(Ty, getContext()); 926 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 927 forConstantArrayExpansion(*this, CAExp, LV.getAddress(), 928 [&](Address EltAddr) { 929 LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy); 930 ExpandTypeFromArgs(CAExp->EltTy, LV, AI); 931 }); 932 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 933 Address This = LV.getAddress(); 934 for (const CXXBaseSpecifier *BS : RExp->Bases) { 935 // Perform a single step derived-to-base conversion. 936 Address Base = 937 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 938 /*NullCheckValue=*/false, SourceLocation()); 939 LValue SubLV = MakeAddrLValue(Base, BS->getType()); 940 941 // Recurse onto bases. 942 ExpandTypeFromArgs(BS->getType(), SubLV, AI); 943 } 944 for (auto FD : RExp->Fields) { 945 // FIXME: What are the right qualifiers here? 946 LValue SubLV = EmitLValueForField(LV, FD); 947 ExpandTypeFromArgs(FD->getType(), SubLV, AI); 948 } 949 } else if (isa<ComplexExpansion>(Exp.get())) { 950 auto realValue = *AI++; 951 auto imagValue = *AI++; 952 EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true); 953 } else { 954 assert(isa<NoExpansion>(Exp.get())); 955 EmitStoreThroughLValue(RValue::get(*AI++), LV); 956 } 957 } 958 959 void CodeGenFunction::ExpandTypeToArgs( 960 QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy, 961 SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) { 962 auto Exp = getTypeExpansion(Ty, getContext()); 963 if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) { 964 forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(), 965 [&](Address EltAddr) { 966 RValue EltRV = 967 convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()); 968 ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos); 969 }); 970 } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) { 971 Address This = RV.getAggregateAddress(); 972 for (const CXXBaseSpecifier *BS : RExp->Bases) { 973 // Perform a single step derived-to-base conversion. 974 Address Base = 975 GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1, 976 /*NullCheckValue=*/false, SourceLocation()); 977 RValue BaseRV = RValue::getAggregate(Base); 978 979 // Recurse onto bases. 980 ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs, 981 IRCallArgPos); 982 } 983 984 LValue LV = MakeAddrLValue(This, Ty); 985 for (auto FD : RExp->Fields) { 986 RValue FldRV = EmitRValueForField(LV, FD, SourceLocation()); 987 ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs, 988 IRCallArgPos); 989 } 990 } else if (isa<ComplexExpansion>(Exp.get())) { 991 ComplexPairTy CV = RV.getComplexVal(); 992 IRCallArgs[IRCallArgPos++] = CV.first; 993 IRCallArgs[IRCallArgPos++] = CV.second; 994 } else { 995 assert(isa<NoExpansion>(Exp.get())); 996 assert(RV.isScalar() && 997 "Unexpected non-scalar rvalue during struct expansion."); 998 999 // Insert a bitcast as needed. 1000 llvm::Value *V = RV.getScalarVal(); 1001 if (IRCallArgPos < IRFuncTy->getNumParams() && 1002 V->getType() != IRFuncTy->getParamType(IRCallArgPos)) 1003 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos)); 1004 1005 IRCallArgs[IRCallArgPos++] = V; 1006 } 1007 } 1008 1009 /// Create a temporary allocation for the purposes of coercion. 1010 static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty, 1011 CharUnits MinAlign) { 1012 // Don't use an alignment that's worse than what LLVM would prefer. 1013 auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty); 1014 CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign)); 1015 1016 return CGF.CreateTempAlloca(Ty, Align); 1017 } 1018 1019 /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are 1020 /// accessing some number of bytes out of it, try to gep into the struct to get 1021 /// at its inner goodness. Dive as deep as possible without entering an element 1022 /// with an in-memory size smaller than DstSize. 1023 static Address 1024 EnterStructPointerForCoercedAccess(Address SrcPtr, 1025 llvm::StructType *SrcSTy, 1026 uint64_t DstSize, CodeGenFunction &CGF) { 1027 // We can't dive into a zero-element struct. 1028 if (SrcSTy->getNumElements() == 0) return SrcPtr; 1029 1030 llvm::Type *FirstElt = SrcSTy->getElementType(0); 1031 1032 // If the first elt is at least as large as what we're looking for, or if the 1033 // first element is the same size as the whole struct, we can enter it. The 1034 // comparison must be made on the store size and not the alloca size. Using 1035 // the alloca size may overstate the size of the load. 1036 uint64_t FirstEltSize = 1037 CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt); 1038 if (FirstEltSize < DstSize && 1039 FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy)) 1040 return SrcPtr; 1041 1042 // GEP into the first element. 1043 SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive"); 1044 1045 // If the first element is a struct, recurse. 1046 llvm::Type *SrcTy = SrcPtr.getElementType(); 1047 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) 1048 return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF); 1049 1050 return SrcPtr; 1051 } 1052 1053 /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both 1054 /// are either integers or pointers. This does a truncation of the value if it 1055 /// is too large or a zero extension if it is too small. 1056 /// 1057 /// This behaves as if the value were coerced through memory, so on big-endian 1058 /// targets the high bits are preserved in a truncation, while little-endian 1059 /// targets preserve the low bits. 1060 static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val, 1061 llvm::Type *Ty, 1062 CodeGenFunction &CGF) { 1063 if (Val->getType() == Ty) 1064 return Val; 1065 1066 if (isa<llvm::PointerType>(Val->getType())) { 1067 // If this is Pointer->Pointer avoid conversion to and from int. 1068 if (isa<llvm::PointerType>(Ty)) 1069 return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val"); 1070 1071 // Convert the pointer to an integer so we can play with its width. 1072 Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi"); 1073 } 1074 1075 llvm::Type *DestIntTy = Ty; 1076 if (isa<llvm::PointerType>(DestIntTy)) 1077 DestIntTy = CGF.IntPtrTy; 1078 1079 if (Val->getType() != DestIntTy) { 1080 const llvm::DataLayout &DL = CGF.CGM.getDataLayout(); 1081 if (DL.isBigEndian()) { 1082 // Preserve the high bits on big-endian targets. 1083 // That is what memory coercion does. 1084 uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType()); 1085 uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy); 1086 1087 if (SrcSize > DstSize) { 1088 Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits"); 1089 Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii"); 1090 } else { 1091 Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii"); 1092 Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits"); 1093 } 1094 } else { 1095 // Little-endian targets preserve the low bits. No shifts required. 1096 Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii"); 1097 } 1098 } 1099 1100 if (isa<llvm::PointerType>(Ty)) 1101 Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip"); 1102 return Val; 1103 } 1104 1105 1106 1107 /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as 1108 /// a pointer to an object of type \arg Ty, known to be aligned to 1109 /// \arg SrcAlign bytes. 1110 /// 1111 /// This safely handles the case when the src type is smaller than the 1112 /// destination type; in this situation the values of bits which not 1113 /// present in the src are undefined. 1114 static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty, 1115 CodeGenFunction &CGF) { 1116 llvm::Type *SrcTy = Src.getElementType(); 1117 1118 // If SrcTy and Ty are the same, just do a load. 1119 if (SrcTy == Ty) 1120 return CGF.Builder.CreateLoad(Src); 1121 1122 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty); 1123 1124 if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) { 1125 Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF); 1126 SrcTy = Src.getType()->getElementType(); 1127 } 1128 1129 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1130 1131 // If the source and destination are integer or pointer types, just do an 1132 // extension or truncation to the desired type. 1133 if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) && 1134 (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) { 1135 llvm::Value *Load = CGF.Builder.CreateLoad(Src); 1136 return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF); 1137 } 1138 1139 // If load is legal, just bitcast the src pointer. 1140 if (SrcSize >= DstSize) { 1141 // Generally SrcSize is never greater than DstSize, since this means we are 1142 // losing bits. However, this can happen in cases where the structure has 1143 // additional padding, for example due to a user specified alignment. 1144 // 1145 // FIXME: Assert that we aren't truncating non-padding bits when have access 1146 // to that information. 1147 Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty)); 1148 return CGF.Builder.CreateLoad(Src); 1149 } 1150 1151 // Otherwise do coercion through memory. This is stupid, but simple. 1152 Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment()); 1153 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy); 1154 Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy); 1155 CGF.Builder.CreateMemCpy(Casted, SrcCasted, 1156 llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize), 1157 false); 1158 return CGF.Builder.CreateLoad(Tmp); 1159 } 1160 1161 // Function to store a first-class aggregate into memory. We prefer to 1162 // store the elements rather than the aggregate to be more friendly to 1163 // fast-isel. 1164 // FIXME: Do we need to recurse here? 1165 static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val, 1166 Address Dest, bool DestIsVolatile) { 1167 // Prefer scalar stores to first-class aggregate stores. 1168 if (llvm::StructType *STy = 1169 dyn_cast<llvm::StructType>(Val->getType())) { 1170 const llvm::StructLayout *Layout = 1171 CGF.CGM.getDataLayout().getStructLayout(STy); 1172 1173 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 1174 auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i)); 1175 Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset); 1176 llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i); 1177 CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile); 1178 } 1179 } else { 1180 CGF.Builder.CreateStore(Val, Dest, DestIsVolatile); 1181 } 1182 } 1183 1184 /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src, 1185 /// where the source and destination may have different types. The 1186 /// destination is known to be aligned to \arg DstAlign bytes. 1187 /// 1188 /// This safely handles the case when the src type is larger than the 1189 /// destination type; the upper bits of the src will be lost. 1190 static void CreateCoercedStore(llvm::Value *Src, 1191 Address Dst, 1192 bool DstIsVolatile, 1193 CodeGenFunction &CGF) { 1194 llvm::Type *SrcTy = Src->getType(); 1195 llvm::Type *DstTy = Dst.getType()->getElementType(); 1196 if (SrcTy == DstTy) { 1197 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1198 return; 1199 } 1200 1201 uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy); 1202 1203 if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) { 1204 Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF); 1205 DstTy = Dst.getType()->getElementType(); 1206 } 1207 1208 // If the source and destination are integer or pointer types, just do an 1209 // extension or truncation to the desired type. 1210 if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) && 1211 (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) { 1212 Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF); 1213 CGF.Builder.CreateStore(Src, Dst, DstIsVolatile); 1214 return; 1215 } 1216 1217 uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy); 1218 1219 // If store is legal, just bitcast the src pointer. 1220 if (SrcSize <= DstSize) { 1221 Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy)); 1222 BuildAggStore(CGF, Src, Dst, DstIsVolatile); 1223 } else { 1224 // Otherwise do coercion through memory. This is stupid, but 1225 // simple. 1226 1227 // Generally SrcSize is never greater than DstSize, since this means we are 1228 // losing bits. However, this can happen in cases where the structure has 1229 // additional padding, for example due to a user specified alignment. 1230 // 1231 // FIXME: Assert that we aren't truncating non-padding bits when have access 1232 // to that information. 1233 Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment()); 1234 CGF.Builder.CreateStore(Src, Tmp); 1235 Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy); 1236 Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy); 1237 CGF.Builder.CreateMemCpy(DstCasted, Casted, 1238 llvm::ConstantInt::get(CGF.IntPtrTy, DstSize), 1239 false); 1240 } 1241 } 1242 1243 static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr, 1244 const ABIArgInfo &info) { 1245 if (unsigned offset = info.getDirectOffset()) { 1246 addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty); 1247 addr = CGF.Builder.CreateConstInBoundsByteGEP(addr, 1248 CharUnits::fromQuantity(offset)); 1249 addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType()); 1250 } 1251 return addr; 1252 } 1253 1254 namespace { 1255 1256 /// Encapsulates information about the way function arguments from 1257 /// CGFunctionInfo should be passed to actual LLVM IR function. 1258 class ClangToLLVMArgMapping { 1259 static const unsigned InvalidIndex = ~0U; 1260 unsigned InallocaArgNo; 1261 unsigned SRetArgNo; 1262 unsigned TotalIRArgs; 1263 1264 /// Arguments of LLVM IR function corresponding to single Clang argument. 1265 struct IRArgs { 1266 unsigned PaddingArgIndex; 1267 // Argument is expanded to IR arguments at positions 1268 // [FirstArgIndex, FirstArgIndex + NumberOfArgs). 1269 unsigned FirstArgIndex; 1270 unsigned NumberOfArgs; 1271 1272 IRArgs() 1273 : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex), 1274 NumberOfArgs(0) {} 1275 }; 1276 1277 SmallVector<IRArgs, 8> ArgInfo; 1278 1279 public: 1280 ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI, 1281 bool OnlyRequiredArgs = false) 1282 : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0), 1283 ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) { 1284 construct(Context, FI, OnlyRequiredArgs); 1285 } 1286 1287 bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; } 1288 unsigned getInallocaArgNo() const { 1289 assert(hasInallocaArg()); 1290 return InallocaArgNo; 1291 } 1292 1293 bool hasSRetArg() const { return SRetArgNo != InvalidIndex; } 1294 unsigned getSRetArgNo() const { 1295 assert(hasSRetArg()); 1296 return SRetArgNo; 1297 } 1298 1299 unsigned totalIRArgs() const { return TotalIRArgs; } 1300 1301 bool hasPaddingArg(unsigned ArgNo) const { 1302 assert(ArgNo < ArgInfo.size()); 1303 return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex; 1304 } 1305 unsigned getPaddingArgNo(unsigned ArgNo) const { 1306 assert(hasPaddingArg(ArgNo)); 1307 return ArgInfo[ArgNo].PaddingArgIndex; 1308 } 1309 1310 /// Returns index of first IR argument corresponding to ArgNo, and their 1311 /// quantity. 1312 std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const { 1313 assert(ArgNo < ArgInfo.size()); 1314 return std::make_pair(ArgInfo[ArgNo].FirstArgIndex, 1315 ArgInfo[ArgNo].NumberOfArgs); 1316 } 1317 1318 private: 1319 void construct(const ASTContext &Context, const CGFunctionInfo &FI, 1320 bool OnlyRequiredArgs); 1321 }; 1322 1323 void ClangToLLVMArgMapping::construct(const ASTContext &Context, 1324 const CGFunctionInfo &FI, 1325 bool OnlyRequiredArgs) { 1326 unsigned IRArgNo = 0; 1327 bool SwapThisWithSRet = false; 1328 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1329 1330 if (RetAI.getKind() == ABIArgInfo::Indirect) { 1331 SwapThisWithSRet = RetAI.isSRetAfterThis(); 1332 SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++; 1333 } 1334 1335 unsigned ArgNo = 0; 1336 unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size(); 1337 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs; 1338 ++I, ++ArgNo) { 1339 assert(I != FI.arg_end()); 1340 QualType ArgType = I->type; 1341 const ABIArgInfo &AI = I->info; 1342 // Collect data about IR arguments corresponding to Clang argument ArgNo. 1343 auto &IRArgs = ArgInfo[ArgNo]; 1344 1345 if (AI.getPaddingType()) 1346 IRArgs.PaddingArgIndex = IRArgNo++; 1347 1348 switch (AI.getKind()) { 1349 case ABIArgInfo::Extend: 1350 case ABIArgInfo::Direct: { 1351 // FIXME: handle sseregparm someday... 1352 llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType()); 1353 if (AI.isDirect() && AI.getCanBeFlattened() && STy) { 1354 IRArgs.NumberOfArgs = STy->getNumElements(); 1355 } else { 1356 IRArgs.NumberOfArgs = 1; 1357 } 1358 break; 1359 } 1360 case ABIArgInfo::Indirect: 1361 IRArgs.NumberOfArgs = 1; 1362 break; 1363 case ABIArgInfo::Ignore: 1364 case ABIArgInfo::InAlloca: 1365 // ignore and inalloca doesn't have matching LLVM parameters. 1366 IRArgs.NumberOfArgs = 0; 1367 break; 1368 case ABIArgInfo::CoerceAndExpand: 1369 IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size(); 1370 break; 1371 case ABIArgInfo::Expand: 1372 IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context); 1373 break; 1374 } 1375 1376 if (IRArgs.NumberOfArgs > 0) { 1377 IRArgs.FirstArgIndex = IRArgNo; 1378 IRArgNo += IRArgs.NumberOfArgs; 1379 } 1380 1381 // Skip over the sret parameter when it comes second. We already handled it 1382 // above. 1383 if (IRArgNo == 1 && SwapThisWithSRet) 1384 IRArgNo++; 1385 } 1386 assert(ArgNo == ArgInfo.size()); 1387 1388 if (FI.usesInAlloca()) 1389 InallocaArgNo = IRArgNo++; 1390 1391 TotalIRArgs = IRArgNo; 1392 } 1393 } // namespace 1394 1395 /***/ 1396 1397 bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) { 1398 return FI.getReturnInfo().isIndirect(); 1399 } 1400 1401 bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) { 1402 return ReturnTypeUsesSRet(FI) && 1403 getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs(); 1404 } 1405 1406 bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) { 1407 if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) { 1408 switch (BT->getKind()) { 1409 default: 1410 return false; 1411 case BuiltinType::Float: 1412 return getTarget().useObjCFPRetForRealType(TargetInfo::Float); 1413 case BuiltinType::Double: 1414 return getTarget().useObjCFPRetForRealType(TargetInfo::Double); 1415 case BuiltinType::LongDouble: 1416 return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble); 1417 } 1418 } 1419 1420 return false; 1421 } 1422 1423 bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) { 1424 if (const ComplexType *CT = ResultType->getAs<ComplexType>()) { 1425 if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) { 1426 if (BT->getKind() == BuiltinType::LongDouble) 1427 return getTarget().useObjCFP2RetForComplexLongDouble(); 1428 } 1429 } 1430 1431 return false; 1432 } 1433 1434 llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) { 1435 const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD); 1436 return GetFunctionType(FI); 1437 } 1438 1439 llvm::FunctionType * 1440 CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) { 1441 1442 bool Inserted = FunctionsBeingProcessed.insert(&FI).second; 1443 (void)Inserted; 1444 assert(Inserted && "Recursively being processed?"); 1445 1446 llvm::Type *resultType = nullptr; 1447 const ABIArgInfo &retAI = FI.getReturnInfo(); 1448 switch (retAI.getKind()) { 1449 case ABIArgInfo::Expand: 1450 llvm_unreachable("Invalid ABI kind for return argument"); 1451 1452 case ABIArgInfo::Extend: 1453 case ABIArgInfo::Direct: 1454 resultType = retAI.getCoerceToType(); 1455 break; 1456 1457 case ABIArgInfo::InAlloca: 1458 if (retAI.getInAllocaSRet()) { 1459 // sret things on win32 aren't void, they return the sret pointer. 1460 QualType ret = FI.getReturnType(); 1461 llvm::Type *ty = ConvertType(ret); 1462 unsigned addressSpace = Context.getTargetAddressSpace(ret); 1463 resultType = llvm::PointerType::get(ty, addressSpace); 1464 } else { 1465 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1466 } 1467 break; 1468 1469 case ABIArgInfo::Indirect: 1470 case ABIArgInfo::Ignore: 1471 resultType = llvm::Type::getVoidTy(getLLVMContext()); 1472 break; 1473 1474 case ABIArgInfo::CoerceAndExpand: 1475 resultType = retAI.getUnpaddedCoerceAndExpandType(); 1476 break; 1477 } 1478 1479 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true); 1480 SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs()); 1481 1482 // Add type for sret argument. 1483 if (IRFunctionArgs.hasSRetArg()) { 1484 QualType Ret = FI.getReturnType(); 1485 llvm::Type *Ty = ConvertType(Ret); 1486 unsigned AddressSpace = Context.getTargetAddressSpace(Ret); 1487 ArgTypes[IRFunctionArgs.getSRetArgNo()] = 1488 llvm::PointerType::get(Ty, AddressSpace); 1489 } 1490 1491 // Add type for inalloca argument. 1492 if (IRFunctionArgs.hasInallocaArg()) { 1493 auto ArgStruct = FI.getArgStruct(); 1494 assert(ArgStruct); 1495 ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo(); 1496 } 1497 1498 // Add in all of the required arguments. 1499 unsigned ArgNo = 0; 1500 CGFunctionInfo::const_arg_iterator it = FI.arg_begin(), 1501 ie = it + FI.getNumRequiredArgs(); 1502 for (; it != ie; ++it, ++ArgNo) { 1503 const ABIArgInfo &ArgInfo = it->info; 1504 1505 // Insert a padding type to ensure proper alignment. 1506 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 1507 ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 1508 ArgInfo.getPaddingType(); 1509 1510 unsigned FirstIRArg, NumIRArgs; 1511 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1512 1513 switch (ArgInfo.getKind()) { 1514 case ABIArgInfo::Ignore: 1515 case ABIArgInfo::InAlloca: 1516 assert(NumIRArgs == 0); 1517 break; 1518 1519 case ABIArgInfo::Indirect: { 1520 assert(NumIRArgs == 1); 1521 // indirect arguments are always on the stack, which is addr space #0. 1522 llvm::Type *LTy = ConvertTypeForMem(it->type); 1523 ArgTypes[FirstIRArg] = LTy->getPointerTo(); 1524 break; 1525 } 1526 1527 case ABIArgInfo::Extend: 1528 case ABIArgInfo::Direct: { 1529 // Fast-isel and the optimizer generally like scalar values better than 1530 // FCAs, so we flatten them if this is safe to do for this argument. 1531 llvm::Type *argType = ArgInfo.getCoerceToType(); 1532 llvm::StructType *st = dyn_cast<llvm::StructType>(argType); 1533 if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 1534 assert(NumIRArgs == st->getNumElements()); 1535 for (unsigned i = 0, e = st->getNumElements(); i != e; ++i) 1536 ArgTypes[FirstIRArg + i] = st->getElementType(i); 1537 } else { 1538 assert(NumIRArgs == 1); 1539 ArgTypes[FirstIRArg] = argType; 1540 } 1541 break; 1542 } 1543 1544 case ABIArgInfo::CoerceAndExpand: { 1545 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1546 for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) { 1547 *ArgTypesIter++ = EltTy; 1548 } 1549 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1550 break; 1551 } 1552 1553 case ABIArgInfo::Expand: 1554 auto ArgTypesIter = ArgTypes.begin() + FirstIRArg; 1555 getExpandedTypes(it->type, ArgTypesIter); 1556 assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs); 1557 break; 1558 } 1559 } 1560 1561 bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased; 1562 assert(Erased && "Not in set?"); 1563 1564 return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic()); 1565 } 1566 1567 llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) { 1568 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1569 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1570 1571 if (!isFuncTypeConvertible(FPT)) 1572 return llvm::StructType::get(getLLVMContext()); 1573 1574 const CGFunctionInfo *Info; 1575 if (isa<CXXDestructorDecl>(MD)) 1576 Info = 1577 &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType())); 1578 else 1579 Info = &arrangeCXXMethodDeclaration(MD); 1580 return GetFunctionType(*Info); 1581 } 1582 1583 static void AddAttributesFromFunctionProtoType(ASTContext &Ctx, 1584 llvm::AttrBuilder &FuncAttrs, 1585 const FunctionProtoType *FPT) { 1586 if (!FPT) 1587 return; 1588 1589 if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) && 1590 FPT->isNothrow(Ctx)) 1591 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1592 } 1593 1594 void CodeGenModule::ConstructAttributeList( 1595 StringRef Name, const CGFunctionInfo &FI, CGCalleeInfo CalleeInfo, 1596 AttributeListType &PAL, unsigned &CallingConv, bool AttrOnCallSite) { 1597 llvm::AttrBuilder FuncAttrs; 1598 llvm::AttrBuilder RetAttrs; 1599 bool HasOptnone = false; 1600 1601 CallingConv = FI.getEffectiveCallingConvention(); 1602 1603 if (FI.isNoReturn()) 1604 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1605 1606 // If we have information about the function prototype, we can learn 1607 // attributes form there. 1608 AddAttributesFromFunctionProtoType(getContext(), FuncAttrs, 1609 CalleeInfo.getCalleeFunctionProtoType()); 1610 1611 const Decl *TargetDecl = CalleeInfo.getCalleeDecl(); 1612 1613 bool HasAnyX86InterruptAttr = false; 1614 // FIXME: handle sseregparm someday... 1615 if (TargetDecl) { 1616 if (TargetDecl->hasAttr<ReturnsTwiceAttr>()) 1617 FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice); 1618 if (TargetDecl->hasAttr<NoThrowAttr>()) 1619 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1620 if (TargetDecl->hasAttr<NoReturnAttr>()) 1621 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1622 if (TargetDecl->hasAttr<NoDuplicateAttr>()) 1623 FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate); 1624 1625 if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) { 1626 AddAttributesFromFunctionProtoType( 1627 getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>()); 1628 // Don't use [[noreturn]] or _Noreturn for a call to a virtual function. 1629 // These attributes are not inherited by overloads. 1630 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn); 1631 if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual())) 1632 FuncAttrs.addAttribute(llvm::Attribute::NoReturn); 1633 } 1634 1635 // 'const', 'pure' and 'noalias' attributed functions are also nounwind. 1636 if (TargetDecl->hasAttr<ConstAttr>()) { 1637 FuncAttrs.addAttribute(llvm::Attribute::ReadNone); 1638 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1639 } else if (TargetDecl->hasAttr<PureAttr>()) { 1640 FuncAttrs.addAttribute(llvm::Attribute::ReadOnly); 1641 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1642 } else if (TargetDecl->hasAttr<NoAliasAttr>()) { 1643 FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly); 1644 FuncAttrs.addAttribute(llvm::Attribute::NoUnwind); 1645 } 1646 if (TargetDecl->hasAttr<RestrictAttr>()) 1647 RetAttrs.addAttribute(llvm::Attribute::NoAlias); 1648 if (TargetDecl->hasAttr<ReturnsNonNullAttr>()) 1649 RetAttrs.addAttribute(llvm::Attribute::NonNull); 1650 1651 HasAnyX86InterruptAttr = TargetDecl->hasAttr<AnyX86InterruptAttr>(); 1652 HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>(); 1653 } 1654 1655 // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed. 1656 if (!HasOptnone) { 1657 if (CodeGenOpts.OptimizeSize) 1658 FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize); 1659 if (CodeGenOpts.OptimizeSize == 2) 1660 FuncAttrs.addAttribute(llvm::Attribute::MinSize); 1661 } 1662 1663 if (CodeGenOpts.DisableRedZone) 1664 FuncAttrs.addAttribute(llvm::Attribute::NoRedZone); 1665 if (CodeGenOpts.NoImplicitFloat) 1666 FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat); 1667 if (CodeGenOpts.EnableSegmentedStacks && 1668 !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>())) 1669 FuncAttrs.addAttribute("split-stack"); 1670 1671 if (AttrOnCallSite) { 1672 // Attributes that should go on the call site only. 1673 if (!CodeGenOpts.SimplifyLibCalls || 1674 CodeGenOpts.isNoBuiltinFunc(Name.data())) 1675 FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin); 1676 if (!CodeGenOpts.TrapFuncName.empty()) 1677 FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName); 1678 } else { 1679 // Attributes that should go on the function, but not the call site. 1680 if (!CodeGenOpts.DisableFPElim) { 1681 FuncAttrs.addAttribute("no-frame-pointer-elim", "false"); 1682 } else if (CodeGenOpts.OmitLeafFramePointer) { 1683 FuncAttrs.addAttribute("no-frame-pointer-elim", "false"); 1684 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf"); 1685 } else { 1686 FuncAttrs.addAttribute("no-frame-pointer-elim", "true"); 1687 FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf"); 1688 } 1689 1690 bool DisableTailCalls = 1691 CodeGenOpts.DisableTailCalls || HasAnyX86InterruptAttr || 1692 (TargetDecl && TargetDecl->hasAttr<DisableTailCallsAttr>()); 1693 FuncAttrs.addAttribute( 1694 "disable-tail-calls", 1695 llvm::toStringRef(DisableTailCalls)); 1696 1697 FuncAttrs.addAttribute("less-precise-fpmad", 1698 llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD)); 1699 FuncAttrs.addAttribute("no-infs-fp-math", 1700 llvm::toStringRef(CodeGenOpts.NoInfsFPMath)); 1701 FuncAttrs.addAttribute("no-nans-fp-math", 1702 llvm::toStringRef(CodeGenOpts.NoNaNsFPMath)); 1703 FuncAttrs.addAttribute("unsafe-fp-math", 1704 llvm::toStringRef(CodeGenOpts.UnsafeFPMath)); 1705 FuncAttrs.addAttribute("use-soft-float", 1706 llvm::toStringRef(CodeGenOpts.SoftFloat)); 1707 FuncAttrs.addAttribute("stack-protector-buffer-size", 1708 llvm::utostr(CodeGenOpts.SSPBufferSize)); 1709 1710 if (CodeGenOpts.StackRealignment) 1711 FuncAttrs.addAttribute("stackrealign"); 1712 1713 // Add target-cpu and target-features attributes to functions. If 1714 // we have a decl for the function and it has a target attribute then 1715 // parse that and add it to the feature set. 1716 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 1717 const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl); 1718 if (FD && FD->hasAttr<TargetAttr>()) { 1719 llvm::StringMap<bool> FeatureMap; 1720 getFunctionFeatureMap(FeatureMap, FD); 1721 1722 // Produce the canonical string for this set of features. 1723 std::vector<std::string> Features; 1724 for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(), 1725 ie = FeatureMap.end(); 1726 it != ie; ++it) 1727 Features.push_back((it->second ? "+" : "-") + it->first().str()); 1728 1729 // Now add the target-cpu and target-features to the function. 1730 // While we populated the feature map above, we still need to 1731 // get and parse the target attribute so we can get the cpu for 1732 // the function. 1733 const auto *TD = FD->getAttr<TargetAttr>(); 1734 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse(); 1735 if (ParsedAttr.second != "") 1736 TargetCPU = ParsedAttr.second; 1737 if (TargetCPU != "") 1738 FuncAttrs.addAttribute("target-cpu", TargetCPU); 1739 if (!Features.empty()) { 1740 std::sort(Features.begin(), Features.end()); 1741 FuncAttrs.addAttribute( 1742 "target-features", 1743 llvm::join(Features.begin(), Features.end(), ",")); 1744 } 1745 } else { 1746 // Otherwise just add the existing target cpu and target features to the 1747 // function. 1748 std::vector<std::string> &Features = getTarget().getTargetOpts().Features; 1749 if (TargetCPU != "") 1750 FuncAttrs.addAttribute("target-cpu", TargetCPU); 1751 if (!Features.empty()) { 1752 std::sort(Features.begin(), Features.end()); 1753 FuncAttrs.addAttribute( 1754 "target-features", 1755 llvm::join(Features.begin(), Features.end(), ",")); 1756 } 1757 } 1758 } 1759 1760 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) { 1761 // Conservatively, mark all functions and calls in CUDA as convergent 1762 // (meaning, they may call an intrinsically convergent op, such as 1763 // __syncthreads(), and so can't have certain optimizations applied around 1764 // them). LLVM will remove this attribute where it safely can. 1765 FuncAttrs.addAttribute(llvm::Attribute::Convergent); 1766 } 1767 1768 ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI); 1769 1770 QualType RetTy = FI.getReturnType(); 1771 const ABIArgInfo &RetAI = FI.getReturnInfo(); 1772 switch (RetAI.getKind()) { 1773 case ABIArgInfo::Extend: 1774 if (RetTy->hasSignedIntegerRepresentation()) 1775 RetAttrs.addAttribute(llvm::Attribute::SExt); 1776 else if (RetTy->hasUnsignedIntegerRepresentation()) 1777 RetAttrs.addAttribute(llvm::Attribute::ZExt); 1778 // FALL THROUGH 1779 case ABIArgInfo::Direct: 1780 if (RetAI.getInReg()) 1781 RetAttrs.addAttribute(llvm::Attribute::InReg); 1782 break; 1783 case ABIArgInfo::Ignore: 1784 break; 1785 1786 case ABIArgInfo::InAlloca: 1787 case ABIArgInfo::Indirect: { 1788 // inalloca and sret disable readnone and readonly 1789 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 1790 .removeAttribute(llvm::Attribute::ReadNone); 1791 break; 1792 } 1793 1794 case ABIArgInfo::CoerceAndExpand: 1795 break; 1796 1797 case ABIArgInfo::Expand: 1798 llvm_unreachable("Invalid ABI kind for return argument"); 1799 } 1800 1801 if (const auto *RefTy = RetTy->getAs<ReferenceType>()) { 1802 QualType PTy = RefTy->getPointeeType(); 1803 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 1804 RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy) 1805 .getQuantity()); 1806 else if (getContext().getTargetAddressSpace(PTy) == 0) 1807 RetAttrs.addAttribute(llvm::Attribute::NonNull); 1808 } 1809 1810 // Attach return attributes. 1811 if (RetAttrs.hasAttributes()) { 1812 PAL.push_back(llvm::AttributeSet::get( 1813 getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs)); 1814 } 1815 1816 // Attach attributes to sret. 1817 if (IRFunctionArgs.hasSRetArg()) { 1818 llvm::AttrBuilder SRETAttrs; 1819 SRETAttrs.addAttribute(llvm::Attribute::StructRet); 1820 if (RetAI.getInReg()) 1821 SRETAttrs.addAttribute(llvm::Attribute::InReg); 1822 PAL.push_back(llvm::AttributeSet::get( 1823 getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs)); 1824 } 1825 1826 // Attach attributes to inalloca argument. 1827 if (IRFunctionArgs.hasInallocaArg()) { 1828 llvm::AttrBuilder Attrs; 1829 Attrs.addAttribute(llvm::Attribute::InAlloca); 1830 PAL.push_back(llvm::AttributeSet::get( 1831 getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs)); 1832 } 1833 1834 unsigned ArgNo = 0; 1835 for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(), 1836 E = FI.arg_end(); 1837 I != E; ++I, ++ArgNo) { 1838 QualType ParamType = I->type; 1839 const ABIArgInfo &AI = I->info; 1840 llvm::AttrBuilder Attrs; 1841 1842 // Add attribute for padding argument, if necessary. 1843 if (IRFunctionArgs.hasPaddingArg(ArgNo)) { 1844 if (AI.getPaddingInReg()) 1845 PAL.push_back(llvm::AttributeSet::get( 1846 getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1, 1847 llvm::Attribute::InReg)); 1848 } 1849 1850 // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we 1851 // have the corresponding parameter variable. It doesn't make 1852 // sense to do it here because parameters are so messed up. 1853 switch (AI.getKind()) { 1854 case ABIArgInfo::Extend: 1855 if (ParamType->isSignedIntegerOrEnumerationType()) 1856 Attrs.addAttribute(llvm::Attribute::SExt); 1857 else if (ParamType->isUnsignedIntegerOrEnumerationType()) { 1858 if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType)) 1859 Attrs.addAttribute(llvm::Attribute::SExt); 1860 else 1861 Attrs.addAttribute(llvm::Attribute::ZExt); 1862 } 1863 // FALL THROUGH 1864 case ABIArgInfo::Direct: 1865 if (ArgNo == 0 && FI.isChainCall()) 1866 Attrs.addAttribute(llvm::Attribute::Nest); 1867 else if (AI.getInReg()) 1868 Attrs.addAttribute(llvm::Attribute::InReg); 1869 break; 1870 1871 case ABIArgInfo::Indirect: { 1872 if (AI.getInReg()) 1873 Attrs.addAttribute(llvm::Attribute::InReg); 1874 1875 if (AI.getIndirectByVal()) 1876 Attrs.addAttribute(llvm::Attribute::ByVal); 1877 1878 CharUnits Align = AI.getIndirectAlign(); 1879 1880 // In a byval argument, it is important that the required 1881 // alignment of the type is honored, as LLVM might be creating a 1882 // *new* stack object, and needs to know what alignment to give 1883 // it. (Sometimes it can deduce a sensible alignment on its own, 1884 // but not if clang decides it must emit a packed struct, or the 1885 // user specifies increased alignment requirements.) 1886 // 1887 // This is different from indirect *not* byval, where the object 1888 // exists already, and the align attribute is purely 1889 // informative. 1890 assert(!Align.isZero()); 1891 1892 // For now, only add this when we have a byval argument. 1893 // TODO: be less lazy about updating test cases. 1894 if (AI.getIndirectByVal()) 1895 Attrs.addAlignmentAttr(Align.getQuantity()); 1896 1897 // byval disables readnone and readonly. 1898 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 1899 .removeAttribute(llvm::Attribute::ReadNone); 1900 break; 1901 } 1902 case ABIArgInfo::Ignore: 1903 case ABIArgInfo::Expand: 1904 case ABIArgInfo::CoerceAndExpand: 1905 break; 1906 1907 case ABIArgInfo::InAlloca: 1908 // inalloca disables readnone and readonly. 1909 FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly) 1910 .removeAttribute(llvm::Attribute::ReadNone); 1911 continue; 1912 } 1913 1914 if (const auto *RefTy = ParamType->getAs<ReferenceType>()) { 1915 QualType PTy = RefTy->getPointeeType(); 1916 if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) 1917 Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy) 1918 .getQuantity()); 1919 else if (getContext().getTargetAddressSpace(PTy) == 0) 1920 Attrs.addAttribute(llvm::Attribute::NonNull); 1921 } 1922 1923 if (Attrs.hasAttributes()) { 1924 unsigned FirstIRArg, NumIRArgs; 1925 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 1926 for (unsigned i = 0; i < NumIRArgs; i++) 1927 PAL.push_back(llvm::AttributeSet::get(getLLVMContext(), 1928 FirstIRArg + i + 1, Attrs)); 1929 } 1930 } 1931 assert(ArgNo == FI.arg_size()); 1932 1933 if (FuncAttrs.hasAttributes()) 1934 PAL.push_back(llvm:: 1935 AttributeSet::get(getLLVMContext(), 1936 llvm::AttributeSet::FunctionIndex, 1937 FuncAttrs)); 1938 } 1939 1940 /// An argument came in as a promoted argument; demote it back to its 1941 /// declared type. 1942 static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF, 1943 const VarDecl *var, 1944 llvm::Value *value) { 1945 llvm::Type *varType = CGF.ConvertType(var->getType()); 1946 1947 // This can happen with promotions that actually don't change the 1948 // underlying type, like the enum promotions. 1949 if (value->getType() == varType) return value; 1950 1951 assert((varType->isIntegerTy() || varType->isFloatingPointTy()) 1952 && "unexpected promotion type"); 1953 1954 if (isa<llvm::IntegerType>(varType)) 1955 return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote"); 1956 1957 return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote"); 1958 } 1959 1960 /// Returns the attribute (either parameter attribute, or function 1961 /// attribute), which declares argument ArgNo to be non-null. 1962 static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD, 1963 QualType ArgType, unsigned ArgNo) { 1964 // FIXME: __attribute__((nonnull)) can also be applied to: 1965 // - references to pointers, where the pointee is known to be 1966 // nonnull (apparently a Clang extension) 1967 // - transparent unions containing pointers 1968 // In the former case, LLVM IR cannot represent the constraint. In 1969 // the latter case, we have no guarantee that the transparent union 1970 // is in fact passed as a pointer. 1971 if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType()) 1972 return nullptr; 1973 // First, check attribute on parameter itself. 1974 if (PVD) { 1975 if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>()) 1976 return ParmNNAttr; 1977 } 1978 // Check function attributes. 1979 if (!FD) 1980 return nullptr; 1981 for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) { 1982 if (NNAttr->isNonNull(ArgNo)) 1983 return NNAttr; 1984 } 1985 return nullptr; 1986 } 1987 1988 void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI, 1989 llvm::Function *Fn, 1990 const FunctionArgList &Args) { 1991 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) 1992 // Naked functions don't have prologues. 1993 return; 1994 1995 // If this is an implicit-return-zero function, go ahead and 1996 // initialize the return value. TODO: it might be nice to have 1997 // a more general mechanism for this that didn't require synthesized 1998 // return statements. 1999 if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) { 2000 if (FD->hasImplicitReturnZero()) { 2001 QualType RetTy = FD->getReturnType().getUnqualifiedType(); 2002 llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy); 2003 llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy); 2004 Builder.CreateStore(Zero, ReturnValue); 2005 } 2006 } 2007 2008 // FIXME: We no longer need the types from FunctionArgList; lift up and 2009 // simplify. 2010 2011 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI); 2012 // Flattened function arguments. 2013 SmallVector<llvm::Argument *, 16> FnArgs; 2014 FnArgs.reserve(IRFunctionArgs.totalIRArgs()); 2015 for (auto &Arg : Fn->args()) { 2016 FnArgs.push_back(&Arg); 2017 } 2018 assert(FnArgs.size() == IRFunctionArgs.totalIRArgs()); 2019 2020 // If we're using inalloca, all the memory arguments are GEPs off of the last 2021 // parameter, which is a pointer to the complete memory area. 2022 Address ArgStruct = Address::invalid(); 2023 const llvm::StructLayout *ArgStructLayout = nullptr; 2024 if (IRFunctionArgs.hasInallocaArg()) { 2025 ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct()); 2026 ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()], 2027 FI.getArgStructAlignment()); 2028 2029 assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo()); 2030 } 2031 2032 // Name the struct return parameter. 2033 if (IRFunctionArgs.hasSRetArg()) { 2034 auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()]; 2035 AI->setName("agg.result"); 2036 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1, 2037 llvm::Attribute::NoAlias)); 2038 } 2039 2040 // Track if we received the parameter as a pointer (indirect, byval, or 2041 // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it 2042 // into a local alloca for us. 2043 SmallVector<ParamValue, 16> ArgVals; 2044 ArgVals.reserve(Args.size()); 2045 2046 // Create a pointer value for every parameter declaration. This usually 2047 // entails copying one or more LLVM IR arguments into an alloca. Don't push 2048 // any cleanups or do anything that might unwind. We do that separately, so 2049 // we can push the cleanups in the correct order for the ABI. 2050 assert(FI.arg_size() == Args.size() && 2051 "Mismatch between function signature & arguments."); 2052 unsigned ArgNo = 0; 2053 CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin(); 2054 for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end(); 2055 i != e; ++i, ++info_it, ++ArgNo) { 2056 const VarDecl *Arg = *i; 2057 QualType Ty = info_it->type; 2058 const ABIArgInfo &ArgI = info_it->info; 2059 2060 bool isPromoted = 2061 isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted(); 2062 2063 unsigned FirstIRArg, NumIRArgs; 2064 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 2065 2066 switch (ArgI.getKind()) { 2067 case ABIArgInfo::InAlloca: { 2068 assert(NumIRArgs == 0); 2069 auto FieldIndex = ArgI.getInAllocaFieldIndex(); 2070 CharUnits FieldOffset = 2071 CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex)); 2072 Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset, 2073 Arg->getName()); 2074 ArgVals.push_back(ParamValue::forIndirect(V)); 2075 break; 2076 } 2077 2078 case ABIArgInfo::Indirect: { 2079 assert(NumIRArgs == 1); 2080 Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign()); 2081 2082 if (!hasScalarEvaluationKind(Ty)) { 2083 // Aggregates and complex variables are accessed by reference. All we 2084 // need to do is realign the value, if requested. 2085 Address V = ParamAddr; 2086 if (ArgI.getIndirectRealign()) { 2087 Address AlignedTemp = CreateMemTemp(Ty, "coerce"); 2088 2089 // Copy from the incoming argument pointer to the temporary with the 2090 // appropriate alignment. 2091 // 2092 // FIXME: We should have a common utility for generating an aggregate 2093 // copy. 2094 CharUnits Size = getContext().getTypeSizeInChars(Ty); 2095 auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()); 2096 Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy); 2097 Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy); 2098 Builder.CreateMemCpy(Dst, Src, SizeVal, false); 2099 V = AlignedTemp; 2100 } 2101 ArgVals.push_back(ParamValue::forIndirect(V)); 2102 } else { 2103 // Load scalar value from indirect argument. 2104 llvm::Value *V = 2105 EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart()); 2106 2107 if (isPromoted) 2108 V = emitArgumentDemotion(*this, Arg, V); 2109 ArgVals.push_back(ParamValue::forDirect(V)); 2110 } 2111 break; 2112 } 2113 2114 case ABIArgInfo::Extend: 2115 case ABIArgInfo::Direct: { 2116 2117 // If we have the trivial case, handle it with no muss and fuss. 2118 if (!isa<llvm::StructType>(ArgI.getCoerceToType()) && 2119 ArgI.getCoerceToType() == ConvertType(Ty) && 2120 ArgI.getDirectOffset() == 0) { 2121 assert(NumIRArgs == 1); 2122 auto AI = FnArgs[FirstIRArg]; 2123 llvm::Value *V = AI; 2124 2125 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) { 2126 if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(), 2127 PVD->getFunctionScopeIndex())) 2128 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2129 AI->getArgNo() + 1, 2130 llvm::Attribute::NonNull)); 2131 2132 QualType OTy = PVD->getOriginalType(); 2133 if (const auto *ArrTy = 2134 getContext().getAsConstantArrayType(OTy)) { 2135 // A C99 array parameter declaration with the static keyword also 2136 // indicates dereferenceability, and if the size is constant we can 2137 // use the dereferenceable attribute (which requires the size in 2138 // bytes). 2139 if (ArrTy->getSizeModifier() == ArrayType::Static) { 2140 QualType ETy = ArrTy->getElementType(); 2141 uint64_t ArrSize = ArrTy->getSize().getZExtValue(); 2142 if (!ETy->isIncompleteType() && ETy->isConstantSizeType() && 2143 ArrSize) { 2144 llvm::AttrBuilder Attrs; 2145 Attrs.addDereferenceableAttr( 2146 getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize); 2147 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2148 AI->getArgNo() + 1, Attrs)); 2149 } else if (getContext().getTargetAddressSpace(ETy) == 0) { 2150 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2151 AI->getArgNo() + 1, 2152 llvm::Attribute::NonNull)); 2153 } 2154 } 2155 } else if (const auto *ArrTy = 2156 getContext().getAsVariableArrayType(OTy)) { 2157 // For C99 VLAs with the static keyword, we don't know the size so 2158 // we can't use the dereferenceable attribute, but in addrspace(0) 2159 // we know that it must be nonnull. 2160 if (ArrTy->getSizeModifier() == VariableArrayType::Static && 2161 !getContext().getTargetAddressSpace(ArrTy->getElementType())) 2162 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2163 AI->getArgNo() + 1, 2164 llvm::Attribute::NonNull)); 2165 } 2166 2167 const auto *AVAttr = PVD->getAttr<AlignValueAttr>(); 2168 if (!AVAttr) 2169 if (const auto *TOTy = dyn_cast<TypedefType>(OTy)) 2170 AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>(); 2171 if (AVAttr) { 2172 llvm::Value *AlignmentValue = 2173 EmitScalarExpr(AVAttr->getAlignment()); 2174 llvm::ConstantInt *AlignmentCI = 2175 cast<llvm::ConstantInt>(AlignmentValue); 2176 unsigned Alignment = 2177 std::min((unsigned) AlignmentCI->getZExtValue(), 2178 +llvm::Value::MaximumAlignment); 2179 2180 llvm::AttrBuilder Attrs; 2181 Attrs.addAlignmentAttr(Alignment); 2182 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2183 AI->getArgNo() + 1, Attrs)); 2184 } 2185 } 2186 2187 if (Arg->getType().isRestrictQualified()) 2188 AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), 2189 AI->getArgNo() + 1, 2190 llvm::Attribute::NoAlias)); 2191 2192 // Ensure the argument is the correct type. 2193 if (V->getType() != ArgI.getCoerceToType()) 2194 V = Builder.CreateBitCast(V, ArgI.getCoerceToType()); 2195 2196 if (isPromoted) 2197 V = emitArgumentDemotion(*this, Arg, V); 2198 2199 if (const CXXMethodDecl *MD = 2200 dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) { 2201 if (MD->isVirtual() && Arg == CXXABIThisDecl) 2202 V = CGM.getCXXABI(). 2203 adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V); 2204 } 2205 2206 // Because of merging of function types from multiple decls it is 2207 // possible for the type of an argument to not match the corresponding 2208 // type in the function type. Since we are codegening the callee 2209 // in here, add a cast to the argument type. 2210 llvm::Type *LTy = ConvertType(Arg->getType()); 2211 if (V->getType() != LTy) 2212 V = Builder.CreateBitCast(V, LTy); 2213 2214 ArgVals.push_back(ParamValue::forDirect(V)); 2215 break; 2216 } 2217 2218 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg), 2219 Arg->getName()); 2220 2221 // Pointer to store into. 2222 Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI); 2223 2224 // Fast-isel and the optimizer generally like scalar values better than 2225 // FCAs, so we flatten them if this is safe to do for this argument. 2226 llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType()); 2227 if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy && 2228 STy->getNumElements() > 1) { 2229 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy); 2230 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy); 2231 llvm::Type *DstTy = Ptr.getElementType(); 2232 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy); 2233 2234 Address AddrToStoreInto = Address::invalid(); 2235 if (SrcSize <= DstSize) { 2236 AddrToStoreInto = 2237 Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy)); 2238 } else { 2239 AddrToStoreInto = 2240 CreateTempAlloca(STy, Alloca.getAlignment(), "coerce"); 2241 } 2242 2243 assert(STy->getNumElements() == NumIRArgs); 2244 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 2245 auto AI = FnArgs[FirstIRArg + i]; 2246 AI->setName(Arg->getName() + ".coerce" + Twine(i)); 2247 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i)); 2248 Address EltPtr = 2249 Builder.CreateStructGEP(AddrToStoreInto, i, Offset); 2250 Builder.CreateStore(AI, EltPtr); 2251 } 2252 2253 if (SrcSize > DstSize) { 2254 Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize); 2255 } 2256 2257 } else { 2258 // Simple case, just do a coerced store of the argument into the alloca. 2259 assert(NumIRArgs == 1); 2260 auto AI = FnArgs[FirstIRArg]; 2261 AI->setName(Arg->getName() + ".coerce"); 2262 CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this); 2263 } 2264 2265 // Match to what EmitParmDecl is expecting for this type. 2266 if (CodeGenFunction::hasScalarEvaluationKind(Ty)) { 2267 llvm::Value *V = 2268 EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart()); 2269 if (isPromoted) 2270 V = emitArgumentDemotion(*this, Arg, V); 2271 ArgVals.push_back(ParamValue::forDirect(V)); 2272 } else { 2273 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2274 } 2275 break; 2276 } 2277 2278 case ABIArgInfo::CoerceAndExpand: { 2279 // Reconstruct into a temporary. 2280 Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2281 ArgVals.push_back(ParamValue::forIndirect(alloca)); 2282 2283 auto coercionType = ArgI.getCoerceAndExpandType(); 2284 alloca = Builder.CreateElementBitCast(alloca, coercionType); 2285 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 2286 2287 unsigned argIndex = FirstIRArg; 2288 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 2289 llvm::Type *eltType = coercionType->getElementType(i); 2290 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) 2291 continue; 2292 2293 auto eltAddr = Builder.CreateStructGEP(alloca, i, layout); 2294 auto elt = FnArgs[argIndex++]; 2295 Builder.CreateStore(elt, eltAddr); 2296 } 2297 assert(argIndex == FirstIRArg + NumIRArgs); 2298 break; 2299 } 2300 2301 case ABIArgInfo::Expand: { 2302 // If this structure was expanded into multiple arguments then 2303 // we need to create a temporary and reconstruct it from the 2304 // arguments. 2305 Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg)); 2306 LValue LV = MakeAddrLValue(Alloca, Ty); 2307 ArgVals.push_back(ParamValue::forIndirect(Alloca)); 2308 2309 auto FnArgIter = FnArgs.begin() + FirstIRArg; 2310 ExpandTypeFromArgs(Ty, LV, FnArgIter); 2311 assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs); 2312 for (unsigned i = 0, e = NumIRArgs; i != e; ++i) { 2313 auto AI = FnArgs[FirstIRArg + i]; 2314 AI->setName(Arg->getName() + "." + Twine(i)); 2315 } 2316 break; 2317 } 2318 2319 case ABIArgInfo::Ignore: 2320 assert(NumIRArgs == 0); 2321 // Initialize the local variable appropriately. 2322 if (!hasScalarEvaluationKind(Ty)) { 2323 ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty))); 2324 } else { 2325 llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType())); 2326 ArgVals.push_back(ParamValue::forDirect(U)); 2327 } 2328 break; 2329 } 2330 } 2331 2332 if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 2333 for (int I = Args.size() - 1; I >= 0; --I) 2334 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2335 } else { 2336 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2337 EmitParmDecl(*Args[I], ArgVals[I], I + 1); 2338 } 2339 } 2340 2341 static void eraseUnusedBitCasts(llvm::Instruction *insn) { 2342 while (insn->use_empty()) { 2343 llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn); 2344 if (!bitcast) return; 2345 2346 // This is "safe" because we would have used a ConstantExpr otherwise. 2347 insn = cast<llvm::Instruction>(bitcast->getOperand(0)); 2348 bitcast->eraseFromParent(); 2349 } 2350 } 2351 2352 /// Try to emit a fused autorelease of a return result. 2353 static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF, 2354 llvm::Value *result) { 2355 // We must be immediately followed the cast. 2356 llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock(); 2357 if (BB->empty()) return nullptr; 2358 if (&BB->back() != result) return nullptr; 2359 2360 llvm::Type *resultType = result->getType(); 2361 2362 // result is in a BasicBlock and is therefore an Instruction. 2363 llvm::Instruction *generator = cast<llvm::Instruction>(result); 2364 2365 SmallVector<llvm::Instruction*,4> insnsToKill; 2366 2367 // Look for: 2368 // %generator = bitcast %type1* %generator2 to %type2* 2369 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) { 2370 // We would have emitted this as a constant if the operand weren't 2371 // an Instruction. 2372 generator = cast<llvm::Instruction>(bitcast->getOperand(0)); 2373 2374 // Require the generator to be immediately followed by the cast. 2375 if (generator->getNextNode() != bitcast) 2376 return nullptr; 2377 2378 insnsToKill.push_back(bitcast); 2379 } 2380 2381 // Look for: 2382 // %generator = call i8* @objc_retain(i8* %originalResult) 2383 // or 2384 // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult) 2385 llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator); 2386 if (!call) return nullptr; 2387 2388 bool doRetainAutorelease; 2389 2390 if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints().objc_retain) { 2391 doRetainAutorelease = true; 2392 } else if (call->getCalledValue() == CGF.CGM.getObjCEntrypoints() 2393 .objc_retainAutoreleasedReturnValue) { 2394 doRetainAutorelease = false; 2395 2396 // If we emitted an assembly marker for this call (and the 2397 // ARCEntrypoints field should have been set if so), go looking 2398 // for that call. If we can't find it, we can't do this 2399 // optimization. But it should always be the immediately previous 2400 // instruction, unless we needed bitcasts around the call. 2401 if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) { 2402 llvm::Instruction *prev = call->getPrevNode(); 2403 assert(prev); 2404 if (isa<llvm::BitCastInst>(prev)) { 2405 prev = prev->getPrevNode(); 2406 assert(prev); 2407 } 2408 assert(isa<llvm::CallInst>(prev)); 2409 assert(cast<llvm::CallInst>(prev)->getCalledValue() == 2410 CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker); 2411 insnsToKill.push_back(prev); 2412 } 2413 } else { 2414 return nullptr; 2415 } 2416 2417 result = call->getArgOperand(0); 2418 insnsToKill.push_back(call); 2419 2420 // Keep killing bitcasts, for sanity. Note that we no longer care 2421 // about precise ordering as long as there's exactly one use. 2422 while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) { 2423 if (!bitcast->hasOneUse()) break; 2424 insnsToKill.push_back(bitcast); 2425 result = bitcast->getOperand(0); 2426 } 2427 2428 // Delete all the unnecessary instructions, from latest to earliest. 2429 for (SmallVectorImpl<llvm::Instruction*>::iterator 2430 i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i) 2431 (*i)->eraseFromParent(); 2432 2433 // Do the fused retain/autorelease if we were asked to. 2434 if (doRetainAutorelease) 2435 result = CGF.EmitARCRetainAutoreleaseReturnValue(result); 2436 2437 // Cast back to the result type. 2438 return CGF.Builder.CreateBitCast(result, resultType); 2439 } 2440 2441 /// If this is a +1 of the value of an immutable 'self', remove it. 2442 static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF, 2443 llvm::Value *result) { 2444 // This is only applicable to a method with an immutable 'self'. 2445 const ObjCMethodDecl *method = 2446 dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl); 2447 if (!method) return nullptr; 2448 const VarDecl *self = method->getSelfDecl(); 2449 if (!self->getType().isConstQualified()) return nullptr; 2450 2451 // Look for a retain call. 2452 llvm::CallInst *retainCall = 2453 dyn_cast<llvm::CallInst>(result->stripPointerCasts()); 2454 if (!retainCall || 2455 retainCall->getCalledValue() != CGF.CGM.getObjCEntrypoints().objc_retain) 2456 return nullptr; 2457 2458 // Look for an ordinary load of 'self'. 2459 llvm::Value *retainedValue = retainCall->getArgOperand(0); 2460 llvm::LoadInst *load = 2461 dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts()); 2462 if (!load || load->isAtomic() || load->isVolatile() || 2463 load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer()) 2464 return nullptr; 2465 2466 // Okay! Burn it all down. This relies for correctness on the 2467 // assumption that the retain is emitted as part of the return and 2468 // that thereafter everything is used "linearly". 2469 llvm::Type *resultType = result->getType(); 2470 eraseUnusedBitCasts(cast<llvm::Instruction>(result)); 2471 assert(retainCall->use_empty()); 2472 retainCall->eraseFromParent(); 2473 eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue)); 2474 2475 return CGF.Builder.CreateBitCast(load, resultType); 2476 } 2477 2478 /// Emit an ARC autorelease of the result of a function. 2479 /// 2480 /// \return the value to actually return from the function 2481 static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF, 2482 llvm::Value *result) { 2483 // If we're returning 'self', kill the initial retain. This is a 2484 // heuristic attempt to "encourage correctness" in the really unfortunate 2485 // case where we have a return of self during a dealloc and we desperately 2486 // need to avoid the possible autorelease. 2487 if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result)) 2488 return self; 2489 2490 // At -O0, try to emit a fused retain/autorelease. 2491 if (CGF.shouldUseFusedARCCalls()) 2492 if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result)) 2493 return fused; 2494 2495 return CGF.EmitARCAutoreleaseReturnValue(result); 2496 } 2497 2498 /// Heuristically search for a dominating store to the return-value slot. 2499 static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) { 2500 // Check if a User is a store which pointerOperand is the ReturnValue. 2501 // We are looking for stores to the ReturnValue, not for stores of the 2502 // ReturnValue to some other location. 2503 auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * { 2504 auto *SI = dyn_cast<llvm::StoreInst>(U); 2505 if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer()) 2506 return nullptr; 2507 // These aren't actually possible for non-coerced returns, and we 2508 // only care about non-coerced returns on this code path. 2509 assert(!SI->isAtomic() && !SI->isVolatile()); 2510 return SI; 2511 }; 2512 // If there are multiple uses of the return-value slot, just check 2513 // for something immediately preceding the IP. Sometimes this can 2514 // happen with how we generate implicit-returns; it can also happen 2515 // with noreturn cleanups. 2516 if (!CGF.ReturnValue.getPointer()->hasOneUse()) { 2517 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2518 if (IP->empty()) return nullptr; 2519 llvm::Instruction *I = &IP->back(); 2520 2521 // Skip lifetime markers 2522 for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(), 2523 IE = IP->rend(); 2524 II != IE; ++II) { 2525 if (llvm::IntrinsicInst *Intrinsic = 2526 dyn_cast<llvm::IntrinsicInst>(&*II)) { 2527 if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) { 2528 const llvm::Value *CastAddr = Intrinsic->getArgOperand(1); 2529 ++II; 2530 if (II == IE) 2531 break; 2532 if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II)) 2533 continue; 2534 } 2535 } 2536 I = &*II; 2537 break; 2538 } 2539 2540 return GetStoreIfValid(I); 2541 } 2542 2543 llvm::StoreInst *store = 2544 GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back()); 2545 if (!store) return nullptr; 2546 2547 // Now do a first-and-dirty dominance check: just walk up the 2548 // single-predecessors chain from the current insertion point. 2549 llvm::BasicBlock *StoreBB = store->getParent(); 2550 llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock(); 2551 while (IP != StoreBB) { 2552 if (!(IP = IP->getSinglePredecessor())) 2553 return nullptr; 2554 } 2555 2556 // Okay, the store's basic block dominates the insertion point; we 2557 // can do our thing. 2558 return store; 2559 } 2560 2561 void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI, 2562 bool EmitRetDbgLoc, 2563 SourceLocation EndLoc) { 2564 if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) { 2565 // Naked functions don't have epilogues. 2566 Builder.CreateUnreachable(); 2567 return; 2568 } 2569 2570 // Functions with no result always return void. 2571 if (!ReturnValue.isValid()) { 2572 Builder.CreateRetVoid(); 2573 return; 2574 } 2575 2576 llvm::DebugLoc RetDbgLoc; 2577 llvm::Value *RV = nullptr; 2578 QualType RetTy = FI.getReturnType(); 2579 const ABIArgInfo &RetAI = FI.getReturnInfo(); 2580 2581 switch (RetAI.getKind()) { 2582 case ABIArgInfo::InAlloca: 2583 // Aggregrates get evaluated directly into the destination. Sometimes we 2584 // need to return the sret value in a register, though. 2585 assert(hasAggregateEvaluationKind(RetTy)); 2586 if (RetAI.getInAllocaSRet()) { 2587 llvm::Function::arg_iterator EI = CurFn->arg_end(); 2588 --EI; 2589 llvm::Value *ArgStruct = &*EI; 2590 llvm::Value *SRet = Builder.CreateStructGEP( 2591 nullptr, ArgStruct, RetAI.getInAllocaFieldIndex()); 2592 RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret"); 2593 } 2594 break; 2595 2596 case ABIArgInfo::Indirect: { 2597 auto AI = CurFn->arg_begin(); 2598 if (RetAI.isSRetAfterThis()) 2599 ++AI; 2600 switch (getEvaluationKind(RetTy)) { 2601 case TEK_Complex: { 2602 ComplexPairTy RT = 2603 EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc); 2604 EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy), 2605 /*isInit*/ true); 2606 break; 2607 } 2608 case TEK_Aggregate: 2609 // Do nothing; aggregrates get evaluated directly into the destination. 2610 break; 2611 case TEK_Scalar: 2612 EmitStoreOfScalar(Builder.CreateLoad(ReturnValue), 2613 MakeNaturalAlignAddrLValue(&*AI, RetTy), 2614 /*isInit*/ true); 2615 break; 2616 } 2617 break; 2618 } 2619 2620 case ABIArgInfo::Extend: 2621 case ABIArgInfo::Direct: 2622 if (RetAI.getCoerceToType() == ConvertType(RetTy) && 2623 RetAI.getDirectOffset() == 0) { 2624 // The internal return value temp always will have pointer-to-return-type 2625 // type, just do a load. 2626 2627 // If there is a dominating store to ReturnValue, we can elide 2628 // the load, zap the store, and usually zap the alloca. 2629 if (llvm::StoreInst *SI = 2630 findDominatingStoreToReturnValue(*this)) { 2631 // Reuse the debug location from the store unless there is 2632 // cleanup code to be emitted between the store and return 2633 // instruction. 2634 if (EmitRetDbgLoc && !AutoreleaseResult) 2635 RetDbgLoc = SI->getDebugLoc(); 2636 // Get the stored value and nuke the now-dead store. 2637 RV = SI->getValueOperand(); 2638 SI->eraseFromParent(); 2639 2640 // If that was the only use of the return value, nuke it as well now. 2641 auto returnValueInst = ReturnValue.getPointer(); 2642 if (returnValueInst->use_empty()) { 2643 if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) { 2644 alloca->eraseFromParent(); 2645 ReturnValue = Address::invalid(); 2646 } 2647 } 2648 2649 // Otherwise, we have to do a simple load. 2650 } else { 2651 RV = Builder.CreateLoad(ReturnValue); 2652 } 2653 } else { 2654 // If the value is offset in memory, apply the offset now. 2655 Address V = emitAddressAtOffset(*this, ReturnValue, RetAI); 2656 2657 RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this); 2658 } 2659 2660 // In ARC, end functions that return a retainable type with a call 2661 // to objc_autoreleaseReturnValue. 2662 if (AutoreleaseResult) { 2663 #ifndef NDEBUG 2664 // Type::isObjCRetainabletype has to be called on a QualType that hasn't 2665 // been stripped of the typedefs, so we cannot use RetTy here. Get the 2666 // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from 2667 // CurCodeDecl or BlockInfo. 2668 QualType RT; 2669 2670 if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl)) 2671 RT = FD->getReturnType(); 2672 else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl)) 2673 RT = MD->getReturnType(); 2674 else if (isa<BlockDecl>(CurCodeDecl)) 2675 RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType(); 2676 else 2677 llvm_unreachable("Unexpected function/method type"); 2678 2679 assert(getLangOpts().ObjCAutoRefCount && 2680 !FI.isReturnsRetained() && 2681 RT->isObjCRetainableType()); 2682 #endif 2683 RV = emitAutoreleaseOfResult(*this, RV); 2684 } 2685 2686 break; 2687 2688 case ABIArgInfo::Ignore: 2689 break; 2690 2691 case ABIArgInfo::CoerceAndExpand: { 2692 auto coercionType = RetAI.getCoerceAndExpandType(); 2693 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 2694 2695 // Load all of the coerced elements out into results. 2696 llvm::SmallVector<llvm::Value*, 4> results; 2697 Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType); 2698 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 2699 auto coercedEltType = coercionType->getElementType(i); 2700 if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType)) 2701 continue; 2702 2703 auto eltAddr = Builder.CreateStructGEP(addr, i, layout); 2704 auto elt = Builder.CreateLoad(eltAddr); 2705 results.push_back(elt); 2706 } 2707 2708 // If we have one result, it's the single direct result type. 2709 if (results.size() == 1) { 2710 RV = results[0]; 2711 2712 // Otherwise, we need to make a first-class aggregate. 2713 } else { 2714 // Construct a return type that lacks padding elements. 2715 llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType(); 2716 2717 RV = llvm::UndefValue::get(returnType); 2718 for (unsigned i = 0, e = results.size(); i != e; ++i) { 2719 RV = Builder.CreateInsertValue(RV, results[i], i); 2720 } 2721 } 2722 break; 2723 } 2724 2725 case ABIArgInfo::Expand: 2726 llvm_unreachable("Invalid ABI kind for return argument"); 2727 } 2728 2729 llvm::Instruction *Ret; 2730 if (RV) { 2731 if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) { 2732 if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) { 2733 SanitizerScope SanScope(this); 2734 llvm::Value *Cond = Builder.CreateICmpNE( 2735 RV, llvm::Constant::getNullValue(RV->getType())); 2736 llvm::Constant *StaticData[] = { 2737 EmitCheckSourceLocation(EndLoc), 2738 EmitCheckSourceLocation(RetNNAttr->getLocation()), 2739 }; 2740 EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute), 2741 "nonnull_return", StaticData, None); 2742 } 2743 } 2744 Ret = Builder.CreateRet(RV); 2745 } else { 2746 Ret = Builder.CreateRetVoid(); 2747 } 2748 2749 if (RetDbgLoc) 2750 Ret->setDebugLoc(std::move(RetDbgLoc)); 2751 } 2752 2753 static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) { 2754 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 2755 return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory; 2756 } 2757 2758 static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF, 2759 QualType Ty) { 2760 // FIXME: Generate IR in one pass, rather than going back and fixing up these 2761 // placeholders. 2762 llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty); 2763 llvm::Value *Placeholder = 2764 llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo()); 2765 Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder); 2766 2767 // FIXME: When we generate this IR in one pass, we shouldn't need 2768 // this win32-specific alignment hack. 2769 CharUnits Align = CharUnits::fromQuantity(4); 2770 2771 return AggValueSlot::forAddr(Address(Placeholder, Align), 2772 Ty.getQualifiers(), 2773 AggValueSlot::IsNotDestructed, 2774 AggValueSlot::DoesNotNeedGCBarriers, 2775 AggValueSlot::IsNotAliased); 2776 } 2777 2778 void CodeGenFunction::EmitDelegateCallArg(CallArgList &args, 2779 const VarDecl *param, 2780 SourceLocation loc) { 2781 // StartFunction converted the ABI-lowered parameter(s) into a 2782 // local alloca. We need to turn that into an r-value suitable 2783 // for EmitCall. 2784 Address local = GetAddrOfLocalVar(param); 2785 2786 QualType type = param->getType(); 2787 2788 // For the most part, we just need to load the alloca, except: 2789 // 1) aggregate r-values are actually pointers to temporaries, and 2790 // 2) references to non-scalars are pointers directly to the aggregate. 2791 // I don't know why references to scalars are different here. 2792 if (const ReferenceType *ref = type->getAs<ReferenceType>()) { 2793 if (!hasScalarEvaluationKind(ref->getPointeeType())) 2794 return args.add(RValue::getAggregate(local), type); 2795 2796 // Locals which are references to scalars are represented 2797 // with allocas holding the pointer. 2798 return args.add(RValue::get(Builder.CreateLoad(local)), type); 2799 } 2800 2801 assert(!isInAllocaArgument(CGM.getCXXABI(), type) && 2802 "cannot emit delegate call arguments for inalloca arguments!"); 2803 2804 args.add(convertTempToRValue(local, type, loc), type); 2805 } 2806 2807 static bool isProvablyNull(llvm::Value *addr) { 2808 return isa<llvm::ConstantPointerNull>(addr); 2809 } 2810 2811 static bool isProvablyNonNull(llvm::Value *addr) { 2812 return isa<llvm::AllocaInst>(addr); 2813 } 2814 2815 /// Emit the actual writing-back of a writeback. 2816 static void emitWriteback(CodeGenFunction &CGF, 2817 const CallArgList::Writeback &writeback) { 2818 const LValue &srcLV = writeback.Source; 2819 Address srcAddr = srcLV.getAddress(); 2820 assert(!isProvablyNull(srcAddr.getPointer()) && 2821 "shouldn't have writeback for provably null argument"); 2822 2823 llvm::BasicBlock *contBB = nullptr; 2824 2825 // If the argument wasn't provably non-null, we need to null check 2826 // before doing the store. 2827 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer()); 2828 if (!provablyNonNull) { 2829 llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback"); 2830 contBB = CGF.createBasicBlock("icr.done"); 2831 2832 llvm::Value *isNull = 2833 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 2834 CGF.Builder.CreateCondBr(isNull, contBB, writebackBB); 2835 CGF.EmitBlock(writebackBB); 2836 } 2837 2838 // Load the value to writeback. 2839 llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary); 2840 2841 // Cast it back, in case we're writing an id to a Foo* or something. 2842 value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(), 2843 "icr.writeback-cast"); 2844 2845 // Perform the writeback. 2846 2847 // If we have a "to use" value, it's something we need to emit a use 2848 // of. This has to be carefully threaded in: if it's done after the 2849 // release it's potentially undefined behavior (and the optimizer 2850 // will ignore it), and if it happens before the retain then the 2851 // optimizer could move the release there. 2852 if (writeback.ToUse) { 2853 assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong); 2854 2855 // Retain the new value. No need to block-copy here: the block's 2856 // being passed up the stack. 2857 value = CGF.EmitARCRetainNonBlock(value); 2858 2859 // Emit the intrinsic use here. 2860 CGF.EmitARCIntrinsicUse(writeback.ToUse); 2861 2862 // Load the old value (primitively). 2863 llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation()); 2864 2865 // Put the new value in place (primitively). 2866 CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false); 2867 2868 // Release the old value. 2869 CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime()); 2870 2871 // Otherwise, we can just do a normal lvalue store. 2872 } else { 2873 CGF.EmitStoreThroughLValue(RValue::get(value), srcLV); 2874 } 2875 2876 // Jump to the continuation block. 2877 if (!provablyNonNull) 2878 CGF.EmitBlock(contBB); 2879 } 2880 2881 static void emitWritebacks(CodeGenFunction &CGF, 2882 const CallArgList &args) { 2883 for (const auto &I : args.writebacks()) 2884 emitWriteback(CGF, I); 2885 } 2886 2887 static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF, 2888 const CallArgList &CallArgs) { 2889 assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()); 2890 ArrayRef<CallArgList::CallArgCleanup> Cleanups = 2891 CallArgs.getCleanupsToDeactivate(); 2892 // Iterate in reverse to increase the likelihood of popping the cleanup. 2893 for (const auto &I : llvm::reverse(Cleanups)) { 2894 CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP); 2895 I.IsActiveIP->eraseFromParent(); 2896 } 2897 } 2898 2899 static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) { 2900 if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens())) 2901 if (uop->getOpcode() == UO_AddrOf) 2902 return uop->getSubExpr(); 2903 return nullptr; 2904 } 2905 2906 /// Emit an argument that's being passed call-by-writeback. That is, 2907 /// we are passing the address of an __autoreleased temporary; it 2908 /// might be copy-initialized with the current value of the given 2909 /// address, but it will definitely be copied out of after the call. 2910 static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args, 2911 const ObjCIndirectCopyRestoreExpr *CRE) { 2912 LValue srcLV; 2913 2914 // Make an optimistic effort to emit the address as an l-value. 2915 // This can fail if the argument expression is more complicated. 2916 if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) { 2917 srcLV = CGF.EmitLValue(lvExpr); 2918 2919 // Otherwise, just emit it as a scalar. 2920 } else { 2921 Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr()); 2922 2923 QualType srcAddrType = 2924 CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType(); 2925 srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType); 2926 } 2927 Address srcAddr = srcLV.getAddress(); 2928 2929 // The dest and src types don't necessarily match in LLVM terms 2930 // because of the crazy ObjC compatibility rules. 2931 2932 llvm::PointerType *destType = 2933 cast<llvm::PointerType>(CGF.ConvertType(CRE->getType())); 2934 2935 // If the address is a constant null, just pass the appropriate null. 2936 if (isProvablyNull(srcAddr.getPointer())) { 2937 args.add(RValue::get(llvm::ConstantPointerNull::get(destType)), 2938 CRE->getType()); 2939 return; 2940 } 2941 2942 // Create the temporary. 2943 Address temp = CGF.CreateTempAlloca(destType->getElementType(), 2944 CGF.getPointerAlign(), 2945 "icr.temp"); 2946 // Loading an l-value can introduce a cleanup if the l-value is __weak, 2947 // and that cleanup will be conditional if we can't prove that the l-value 2948 // isn't null, so we need to register a dominating point so that the cleanups 2949 // system will make valid IR. 2950 CodeGenFunction::ConditionalEvaluation condEval(CGF); 2951 2952 // Zero-initialize it if we're not doing a copy-initialization. 2953 bool shouldCopy = CRE->shouldCopy(); 2954 if (!shouldCopy) { 2955 llvm::Value *null = 2956 llvm::ConstantPointerNull::get( 2957 cast<llvm::PointerType>(destType->getElementType())); 2958 CGF.Builder.CreateStore(null, temp); 2959 } 2960 2961 llvm::BasicBlock *contBB = nullptr; 2962 llvm::BasicBlock *originBB = nullptr; 2963 2964 // If the address is *not* known to be non-null, we need to switch. 2965 llvm::Value *finalArgument; 2966 2967 bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer()); 2968 if (provablyNonNull) { 2969 finalArgument = temp.getPointer(); 2970 } else { 2971 llvm::Value *isNull = 2972 CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull"); 2973 2974 finalArgument = CGF.Builder.CreateSelect(isNull, 2975 llvm::ConstantPointerNull::get(destType), 2976 temp.getPointer(), "icr.argument"); 2977 2978 // If we need to copy, then the load has to be conditional, which 2979 // means we need control flow. 2980 if (shouldCopy) { 2981 originBB = CGF.Builder.GetInsertBlock(); 2982 contBB = CGF.createBasicBlock("icr.cont"); 2983 llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy"); 2984 CGF.Builder.CreateCondBr(isNull, contBB, copyBB); 2985 CGF.EmitBlock(copyBB); 2986 condEval.begin(CGF); 2987 } 2988 } 2989 2990 llvm::Value *valueToUse = nullptr; 2991 2992 // Perform a copy if necessary. 2993 if (shouldCopy) { 2994 RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation()); 2995 assert(srcRV.isScalar()); 2996 2997 llvm::Value *src = srcRV.getScalarVal(); 2998 src = CGF.Builder.CreateBitCast(src, destType->getElementType(), 2999 "icr.cast"); 3000 3001 // Use an ordinary store, not a store-to-lvalue. 3002 CGF.Builder.CreateStore(src, temp); 3003 3004 // If optimization is enabled, and the value was held in a 3005 // __strong variable, we need to tell the optimizer that this 3006 // value has to stay alive until we're doing the store back. 3007 // This is because the temporary is effectively unretained, 3008 // and so otherwise we can violate the high-level semantics. 3009 if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 && 3010 srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) { 3011 valueToUse = src; 3012 } 3013 } 3014 3015 // Finish the control flow if we needed it. 3016 if (shouldCopy && !provablyNonNull) { 3017 llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock(); 3018 CGF.EmitBlock(contBB); 3019 3020 // Make a phi for the value to intrinsically use. 3021 if (valueToUse) { 3022 llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2, 3023 "icr.to-use"); 3024 phiToUse->addIncoming(valueToUse, copyBB); 3025 phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()), 3026 originBB); 3027 valueToUse = phiToUse; 3028 } 3029 3030 condEval.end(CGF); 3031 } 3032 3033 args.addWriteback(srcLV, temp, valueToUse); 3034 args.add(RValue::get(finalArgument), CRE->getType()); 3035 } 3036 3037 void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) { 3038 assert(!StackBase && !StackCleanup.isValid()); 3039 3040 // Save the stack. 3041 llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave); 3042 StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save"); 3043 } 3044 3045 void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const { 3046 if (StackBase) { 3047 // Restore the stack after the call. 3048 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 3049 CGF.Builder.CreateCall(F, StackBase); 3050 } 3051 } 3052 3053 void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType, 3054 SourceLocation ArgLoc, 3055 const FunctionDecl *FD, 3056 unsigned ParmNum) { 3057 if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD) 3058 return; 3059 auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr; 3060 unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum; 3061 auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo); 3062 if (!NNAttr) 3063 return; 3064 SanitizerScope SanScope(this); 3065 assert(RV.isScalar()); 3066 llvm::Value *V = RV.getScalarVal(); 3067 llvm::Value *Cond = 3068 Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType())); 3069 llvm::Constant *StaticData[] = { 3070 EmitCheckSourceLocation(ArgLoc), 3071 EmitCheckSourceLocation(NNAttr->getLocation()), 3072 llvm::ConstantInt::get(Int32Ty, ArgNo + 1), 3073 }; 3074 EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute), 3075 "nonnull_arg", StaticData, None); 3076 } 3077 3078 void CodeGenFunction::EmitCallArgs( 3079 CallArgList &Args, ArrayRef<QualType> ArgTypes, 3080 llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange, 3081 const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) { 3082 assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin())); 3083 3084 auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg) { 3085 if (CalleeDecl == nullptr || I >= CalleeDecl->getNumParams()) 3086 return; 3087 auto *PS = CalleeDecl->getParamDecl(I)->getAttr<PassObjectSizeAttr>(); 3088 if (PS == nullptr) 3089 return; 3090 3091 const auto &Context = getContext(); 3092 auto SizeTy = Context.getSizeType(); 3093 auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy)); 3094 llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T); 3095 Args.add(RValue::get(V), SizeTy); 3096 }; 3097 3098 // We *have* to evaluate arguments from right to left in the MS C++ ABI, 3099 // because arguments are destroyed left to right in the callee. 3100 if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 3101 // Insert a stack save if we're going to need any inalloca args. 3102 bool HasInAllocaArgs = false; 3103 for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end(); 3104 I != E && !HasInAllocaArgs; ++I) 3105 HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I); 3106 if (HasInAllocaArgs) { 3107 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 3108 Args.allocateArgumentMemory(*this); 3109 } 3110 3111 // Evaluate each argument. 3112 size_t CallArgsStart = Args.size(); 3113 for (int I = ArgTypes.size() - 1; I >= 0; --I) { 3114 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I; 3115 EmitCallArg(Args, *Arg, ArgTypes[I]); 3116 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(), 3117 CalleeDecl, ParamsToSkip + I); 3118 MaybeEmitImplicitObjectSize(I, *Arg); 3119 } 3120 3121 // Un-reverse the arguments we just evaluated so they match up with the LLVM 3122 // IR function. 3123 std::reverse(Args.begin() + CallArgsStart, Args.end()); 3124 return; 3125 } 3126 3127 for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) { 3128 CallExpr::const_arg_iterator Arg = ArgRange.begin() + I; 3129 assert(Arg != ArgRange.end()); 3130 EmitCallArg(Args, *Arg, ArgTypes[I]); 3131 EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(), 3132 CalleeDecl, ParamsToSkip + I); 3133 MaybeEmitImplicitObjectSize(I, *Arg); 3134 } 3135 } 3136 3137 namespace { 3138 3139 struct DestroyUnpassedArg final : EHScopeStack::Cleanup { 3140 DestroyUnpassedArg(Address Addr, QualType Ty) 3141 : Addr(Addr), Ty(Ty) {} 3142 3143 Address Addr; 3144 QualType Ty; 3145 3146 void Emit(CodeGenFunction &CGF, Flags flags) override { 3147 const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor(); 3148 assert(!Dtor->isTrivial()); 3149 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false, 3150 /*Delegating=*/false, Addr); 3151 } 3152 }; 3153 3154 struct DisableDebugLocationUpdates { 3155 CodeGenFunction &CGF; 3156 bool disabledDebugInfo; 3157 DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) { 3158 if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo())) 3159 CGF.disableDebugInfo(); 3160 } 3161 ~DisableDebugLocationUpdates() { 3162 if (disabledDebugInfo) 3163 CGF.enableDebugInfo(); 3164 } 3165 }; 3166 3167 } // end anonymous namespace 3168 3169 void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E, 3170 QualType type) { 3171 DisableDebugLocationUpdates Dis(*this, E); 3172 if (const ObjCIndirectCopyRestoreExpr *CRE 3173 = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) { 3174 assert(getLangOpts().ObjCAutoRefCount); 3175 assert(getContext().hasSameType(E->getType(), type)); 3176 return emitWritebackArg(*this, args, CRE); 3177 } 3178 3179 assert(type->isReferenceType() == E->isGLValue() && 3180 "reference binding to unmaterialized r-value!"); 3181 3182 if (E->isGLValue()) { 3183 assert(E->getObjectKind() == OK_Ordinary); 3184 return args.add(EmitReferenceBindingToExpr(E), type); 3185 } 3186 3187 bool HasAggregateEvalKind = hasAggregateEvaluationKind(type); 3188 3189 // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee. 3190 // However, we still have to push an EH-only cleanup in case we unwind before 3191 // we make it to the call. 3192 if (HasAggregateEvalKind && 3193 CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 3194 // If we're using inalloca, use the argument memory. Otherwise, use a 3195 // temporary. 3196 AggValueSlot Slot; 3197 if (args.isUsingInAlloca()) 3198 Slot = createPlaceholderSlot(*this, type); 3199 else 3200 Slot = CreateAggTemp(type, "agg.tmp"); 3201 3202 const CXXRecordDecl *RD = type->getAsCXXRecordDecl(); 3203 bool DestroyedInCallee = 3204 RD && RD->hasNonTrivialDestructor() && 3205 CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default; 3206 if (DestroyedInCallee) 3207 Slot.setExternallyDestructed(); 3208 3209 EmitAggExpr(E, Slot); 3210 RValue RV = Slot.asRValue(); 3211 args.add(RV, type); 3212 3213 if (DestroyedInCallee) { 3214 // Create a no-op GEP between the placeholder and the cleanup so we can 3215 // RAUW it successfully. It also serves as a marker of the first 3216 // instruction where the cleanup is active. 3217 pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(), 3218 type); 3219 // This unreachable is a temporary marker which will be removed later. 3220 llvm::Instruction *IsActive = Builder.CreateUnreachable(); 3221 args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive); 3222 } 3223 return; 3224 } 3225 3226 if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) && 3227 cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) { 3228 LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr()); 3229 assert(L.isSimple()); 3230 if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) { 3231 args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true); 3232 } else { 3233 // We can't represent a misaligned lvalue in the CallArgList, so copy 3234 // to an aligned temporary now. 3235 Address tmp = CreateMemTemp(type); 3236 EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile()); 3237 args.add(RValue::getAggregate(tmp), type); 3238 } 3239 return; 3240 } 3241 3242 args.add(EmitAnyExprToTemp(E), type); 3243 } 3244 3245 QualType CodeGenFunction::getVarArgType(const Expr *Arg) { 3246 // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC 3247 // implicitly widens null pointer constants that are arguments to varargs 3248 // functions to pointer-sized ints. 3249 if (!getTarget().getTriple().isOSWindows()) 3250 return Arg->getType(); 3251 3252 if (Arg->getType()->isIntegerType() && 3253 getContext().getTypeSize(Arg->getType()) < 3254 getContext().getTargetInfo().getPointerWidth(0) && 3255 Arg->isNullPointerConstant(getContext(), 3256 Expr::NPC_ValueDependentIsNotNull)) { 3257 return getContext().getIntPtrType(); 3258 } 3259 3260 return Arg->getType(); 3261 } 3262 3263 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3264 // optimizer it can aggressively ignore unwind edges. 3265 void 3266 CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) { 3267 if (CGM.getCodeGenOpts().OptimizationLevel != 0 && 3268 !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions) 3269 Inst->setMetadata("clang.arc.no_objc_arc_exceptions", 3270 CGM.getNoObjCARCExceptionsMetadata()); 3271 } 3272 3273 /// Emits a call to the given no-arguments nounwind runtime function. 3274 llvm::CallInst * 3275 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee, 3276 const llvm::Twine &name) { 3277 return EmitNounwindRuntimeCall(callee, None, name); 3278 } 3279 3280 /// Emits a call to the given nounwind runtime function. 3281 llvm::CallInst * 3282 CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee, 3283 ArrayRef<llvm::Value*> args, 3284 const llvm::Twine &name) { 3285 llvm::CallInst *call = EmitRuntimeCall(callee, args, name); 3286 call->setDoesNotThrow(); 3287 return call; 3288 } 3289 3290 /// Emits a simple call (never an invoke) to the given no-arguments 3291 /// runtime function. 3292 llvm::CallInst * 3293 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee, 3294 const llvm::Twine &name) { 3295 return EmitRuntimeCall(callee, None, name); 3296 } 3297 3298 // Calls which may throw must have operand bundles indicating which funclet 3299 // they are nested within. 3300 static void 3301 getBundlesForFunclet(llvm::Value *Callee, llvm::Instruction *CurrentFuncletPad, 3302 SmallVectorImpl<llvm::OperandBundleDef> &BundleList) { 3303 // There is no need for a funclet operand bundle if we aren't inside a 3304 // funclet. 3305 if (!CurrentFuncletPad) 3306 return; 3307 3308 // Skip intrinsics which cannot throw. 3309 auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts()); 3310 if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow()) 3311 return; 3312 3313 BundleList.emplace_back("funclet", CurrentFuncletPad); 3314 } 3315 3316 /// Emits a simple call (never an invoke) to the given runtime function. 3317 llvm::CallInst * 3318 CodeGenFunction::EmitRuntimeCall(llvm::Value *callee, 3319 ArrayRef<llvm::Value*> args, 3320 const llvm::Twine &name) { 3321 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3322 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList); 3323 3324 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList, name); 3325 call->setCallingConv(getRuntimeCC()); 3326 return call; 3327 } 3328 3329 /// Emits a call or invoke to the given noreturn runtime function. 3330 void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee, 3331 ArrayRef<llvm::Value*> args) { 3332 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3333 getBundlesForFunclet(callee, CurrentFuncletPad, BundleList); 3334 3335 if (getInvokeDest()) { 3336 llvm::InvokeInst *invoke = 3337 Builder.CreateInvoke(callee, 3338 getUnreachableBlock(), 3339 getInvokeDest(), 3340 args, 3341 BundleList); 3342 invoke->setDoesNotReturn(); 3343 invoke->setCallingConv(getRuntimeCC()); 3344 } else { 3345 llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList); 3346 call->setDoesNotReturn(); 3347 call->setCallingConv(getRuntimeCC()); 3348 Builder.CreateUnreachable(); 3349 } 3350 } 3351 3352 /// Emits a call or invoke instruction to the given nullary runtime function. 3353 llvm::CallSite 3354 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee, 3355 const Twine &name) { 3356 return EmitRuntimeCallOrInvoke(callee, None, name); 3357 } 3358 3359 /// Emits a call or invoke instruction to the given runtime function. 3360 llvm::CallSite 3361 CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee, 3362 ArrayRef<llvm::Value*> args, 3363 const Twine &name) { 3364 llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name); 3365 callSite.setCallingConv(getRuntimeCC()); 3366 return callSite; 3367 } 3368 3369 /// Emits a call or invoke instruction to the given function, depending 3370 /// on the current state of the EH stack. 3371 llvm::CallSite 3372 CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee, 3373 ArrayRef<llvm::Value *> Args, 3374 const Twine &Name) { 3375 llvm::BasicBlock *InvokeDest = getInvokeDest(); 3376 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3377 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList); 3378 3379 llvm::Instruction *Inst; 3380 if (!InvokeDest) 3381 Inst = Builder.CreateCall(Callee, Args, BundleList, Name); 3382 else { 3383 llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont"); 3384 Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList, 3385 Name); 3386 EmitBlock(ContBB); 3387 } 3388 3389 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3390 // optimizer it can aggressively ignore unwind edges. 3391 if (CGM.getLangOpts().ObjCAutoRefCount) 3392 AddObjCARCExceptionMetadata(Inst); 3393 3394 return llvm::CallSite(Inst); 3395 } 3396 3397 /// \brief Store a non-aggregate value to an address to initialize it. For 3398 /// initialization, a non-atomic store will be used. 3399 static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src, 3400 LValue Dst) { 3401 if (Src.isScalar()) 3402 CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true); 3403 else 3404 CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true); 3405 } 3406 3407 void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old, 3408 llvm::Value *New) { 3409 DeferredReplacements.push_back(std::make_pair(Old, New)); 3410 } 3411 3412 RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo, 3413 llvm::Value *Callee, 3414 ReturnValueSlot ReturnValue, 3415 const CallArgList &CallArgs, 3416 CGCalleeInfo CalleeInfo, 3417 llvm::Instruction **callOrInvoke) { 3418 // FIXME: We no longer need the types from CallArgs; lift up and simplify. 3419 3420 // Handle struct-return functions by passing a pointer to the 3421 // location that we would like to return into. 3422 QualType RetTy = CallInfo.getReturnType(); 3423 const ABIArgInfo &RetAI = CallInfo.getReturnInfo(); 3424 3425 llvm::FunctionType *IRFuncTy = 3426 cast<llvm::FunctionType>( 3427 cast<llvm::PointerType>(Callee->getType())->getElementType()); 3428 3429 // If we're using inalloca, insert the allocation after the stack save. 3430 // FIXME: Do this earlier rather than hacking it in here! 3431 Address ArgMemory = Address::invalid(); 3432 const llvm::StructLayout *ArgMemoryLayout = nullptr; 3433 if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) { 3434 ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct); 3435 llvm::Instruction *IP = CallArgs.getStackBase(); 3436 llvm::AllocaInst *AI; 3437 if (IP) { 3438 IP = IP->getNextNode(); 3439 AI = new llvm::AllocaInst(ArgStruct, "argmem", IP); 3440 } else { 3441 AI = CreateTempAlloca(ArgStruct, "argmem"); 3442 } 3443 auto Align = CallInfo.getArgStructAlignment(); 3444 AI->setAlignment(Align.getQuantity()); 3445 AI->setUsedWithInAlloca(true); 3446 assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca()); 3447 ArgMemory = Address(AI, Align); 3448 } 3449 3450 // Helper function to drill into the inalloca allocation. 3451 auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address { 3452 auto FieldOffset = 3453 CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex)); 3454 return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset); 3455 }; 3456 3457 ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo); 3458 SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs()); 3459 3460 // If the call returns a temporary with struct return, create a temporary 3461 // alloca to hold the result, unless one is given to us. 3462 Address SRetPtr = Address::invalid(); 3463 size_t UnusedReturnSize = 0; 3464 if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) { 3465 if (!ReturnValue.isNull()) { 3466 SRetPtr = ReturnValue.getValue(); 3467 } else { 3468 SRetPtr = CreateMemTemp(RetTy); 3469 if (HaveInsertPoint() && ReturnValue.isUnused()) { 3470 uint64_t size = 3471 CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy)); 3472 if (EmitLifetimeStart(size, SRetPtr.getPointer())) 3473 UnusedReturnSize = size; 3474 } 3475 } 3476 if (IRFunctionArgs.hasSRetArg()) { 3477 IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer(); 3478 } else if (RetAI.isInAlloca()) { 3479 Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex()); 3480 Builder.CreateStore(SRetPtr.getPointer(), Addr); 3481 } 3482 } 3483 3484 assert(CallInfo.arg_size() == CallArgs.size() && 3485 "Mismatch between function signature & arguments."); 3486 unsigned ArgNo = 0; 3487 CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin(); 3488 for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end(); 3489 I != E; ++I, ++info_it, ++ArgNo) { 3490 const ABIArgInfo &ArgInfo = info_it->info; 3491 RValue RV = I->RV; 3492 3493 // Insert a padding argument to ensure proper alignment. 3494 if (IRFunctionArgs.hasPaddingArg(ArgNo)) 3495 IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] = 3496 llvm::UndefValue::get(ArgInfo.getPaddingType()); 3497 3498 unsigned FirstIRArg, NumIRArgs; 3499 std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo); 3500 3501 switch (ArgInfo.getKind()) { 3502 case ABIArgInfo::InAlloca: { 3503 assert(NumIRArgs == 0); 3504 assert(getTarget().getTriple().getArch() == llvm::Triple::x86); 3505 if (RV.isAggregate()) { 3506 // Replace the placeholder with the appropriate argument slot GEP. 3507 llvm::Instruction *Placeholder = 3508 cast<llvm::Instruction>(RV.getAggregatePointer()); 3509 CGBuilderTy::InsertPoint IP = Builder.saveIP(); 3510 Builder.SetInsertPoint(Placeholder); 3511 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex()); 3512 Builder.restoreIP(IP); 3513 deferPlaceholderReplacement(Placeholder, Addr.getPointer()); 3514 } else { 3515 // Store the RValue into the argument struct. 3516 Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex()); 3517 unsigned AS = Addr.getType()->getPointerAddressSpace(); 3518 llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS); 3519 // There are some cases where a trivial bitcast is not avoidable. The 3520 // definition of a type later in a translation unit may change it's type 3521 // from {}* to (%struct.foo*)*. 3522 if (Addr.getType() != MemType) 3523 Addr = Builder.CreateBitCast(Addr, MemType); 3524 LValue argLV = MakeAddrLValue(Addr, I->Ty); 3525 EmitInitStoreOfNonAggregate(*this, RV, argLV); 3526 } 3527 break; 3528 } 3529 3530 case ABIArgInfo::Indirect: { 3531 assert(NumIRArgs == 1); 3532 if (RV.isScalar() || RV.isComplex()) { 3533 // Make a temporary alloca to pass the argument. 3534 Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign()); 3535 IRCallArgs[FirstIRArg] = Addr.getPointer(); 3536 3537 LValue argLV = MakeAddrLValue(Addr, I->Ty); 3538 EmitInitStoreOfNonAggregate(*this, RV, argLV); 3539 } else { 3540 // We want to avoid creating an unnecessary temporary+copy here; 3541 // however, we need one in three cases: 3542 // 1. If the argument is not byval, and we are required to copy the 3543 // source. (This case doesn't occur on any common architecture.) 3544 // 2. If the argument is byval, RV is not sufficiently aligned, and 3545 // we cannot force it to be sufficiently aligned. 3546 // 3. If the argument is byval, but RV is located in an address space 3547 // different than that of the argument (0). 3548 Address Addr = RV.getAggregateAddress(); 3549 CharUnits Align = ArgInfo.getIndirectAlign(); 3550 const llvm::DataLayout *TD = &CGM.getDataLayout(); 3551 const unsigned RVAddrSpace = Addr.getType()->getAddressSpace(); 3552 const unsigned ArgAddrSpace = 3553 (FirstIRArg < IRFuncTy->getNumParams() 3554 ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() 3555 : 0); 3556 if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) || 3557 (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align && 3558 llvm::getOrEnforceKnownAlignment(Addr.getPointer(), 3559 Align.getQuantity(), *TD) 3560 < Align.getQuantity()) || 3561 (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) { 3562 // Create an aligned temporary, and copy to it. 3563 Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign()); 3564 IRCallArgs[FirstIRArg] = AI.getPointer(); 3565 EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified()); 3566 } else { 3567 // Skip the extra memcpy call. 3568 IRCallArgs[FirstIRArg] = Addr.getPointer(); 3569 } 3570 } 3571 break; 3572 } 3573 3574 case ABIArgInfo::Ignore: 3575 assert(NumIRArgs == 0); 3576 break; 3577 3578 case ABIArgInfo::Extend: 3579 case ABIArgInfo::Direct: { 3580 if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) && 3581 ArgInfo.getCoerceToType() == ConvertType(info_it->type) && 3582 ArgInfo.getDirectOffset() == 0) { 3583 assert(NumIRArgs == 1); 3584 llvm::Value *V; 3585 if (RV.isScalar()) 3586 V = RV.getScalarVal(); 3587 else 3588 V = Builder.CreateLoad(RV.getAggregateAddress()); 3589 3590 // We might have to widen integers, but we should never truncate. 3591 if (ArgInfo.getCoerceToType() != V->getType() && 3592 V->getType()->isIntegerTy()) 3593 V = Builder.CreateZExt(V, ArgInfo.getCoerceToType()); 3594 3595 // If the argument doesn't match, perform a bitcast to coerce it. This 3596 // can happen due to trivial type mismatches. 3597 if (FirstIRArg < IRFuncTy->getNumParams() && 3598 V->getType() != IRFuncTy->getParamType(FirstIRArg)) 3599 V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg)); 3600 IRCallArgs[FirstIRArg] = V; 3601 break; 3602 } 3603 3604 // FIXME: Avoid the conversion through memory if possible. 3605 Address Src = Address::invalid(); 3606 if (RV.isScalar() || RV.isComplex()) { 3607 Src = CreateMemTemp(I->Ty, "coerce"); 3608 LValue SrcLV = MakeAddrLValue(Src, I->Ty); 3609 EmitInitStoreOfNonAggregate(*this, RV, SrcLV); 3610 } else { 3611 Src = RV.getAggregateAddress(); 3612 } 3613 3614 // If the value is offset in memory, apply the offset now. 3615 Src = emitAddressAtOffset(*this, Src, ArgInfo); 3616 3617 // Fast-isel and the optimizer generally like scalar values better than 3618 // FCAs, so we flatten them if this is safe to do for this argument. 3619 llvm::StructType *STy = 3620 dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType()); 3621 if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) { 3622 llvm::Type *SrcTy = Src.getType()->getElementType(); 3623 uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy); 3624 uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy); 3625 3626 // If the source type is smaller than the destination type of the 3627 // coerce-to logic, copy the source value into a temp alloca the size 3628 // of the destination type to allow loading all of it. The bits past 3629 // the source value are left undef. 3630 if (SrcSize < DstSize) { 3631 Address TempAlloca 3632 = CreateTempAlloca(STy, Src.getAlignment(), 3633 Src.getName() + ".coerce"); 3634 Builder.CreateMemCpy(TempAlloca, Src, SrcSize); 3635 Src = TempAlloca; 3636 } else { 3637 Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy)); 3638 } 3639 3640 auto SrcLayout = CGM.getDataLayout().getStructLayout(STy); 3641 assert(NumIRArgs == STy->getNumElements()); 3642 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 3643 auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i)); 3644 Address EltPtr = Builder.CreateStructGEP(Src, i, Offset); 3645 llvm::Value *LI = Builder.CreateLoad(EltPtr); 3646 IRCallArgs[FirstIRArg + i] = LI; 3647 } 3648 } else { 3649 // In the simple case, just pass the coerced loaded value. 3650 assert(NumIRArgs == 1); 3651 IRCallArgs[FirstIRArg] = 3652 CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this); 3653 } 3654 3655 break; 3656 } 3657 3658 case ABIArgInfo::CoerceAndExpand: { 3659 assert(RV.isAggregate() && 3660 "CoerceAndExpand does not support non-aggregate types yet"); 3661 3662 auto coercionType = ArgInfo.getCoerceAndExpandType(); 3663 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 3664 3665 Address addr = RV.getAggregateAddress(); 3666 addr = Builder.CreateElementBitCast(addr, coercionType); 3667 3668 unsigned IRArgPos = FirstIRArg; 3669 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 3670 llvm::Type *eltType = coercionType->getElementType(i); 3671 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 3672 Address eltAddr = Builder.CreateStructGEP(addr, i, layout); 3673 llvm::Value *elt = Builder.CreateLoad(eltAddr); 3674 IRCallArgs[IRArgPos++] = elt; 3675 } 3676 assert(IRArgPos == FirstIRArg + NumIRArgs); 3677 3678 break; 3679 } 3680 3681 case ABIArgInfo::Expand: 3682 unsigned IRArgPos = FirstIRArg; 3683 ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos); 3684 assert(IRArgPos == FirstIRArg + NumIRArgs); 3685 break; 3686 } 3687 } 3688 3689 if (ArgMemory.isValid()) { 3690 llvm::Value *Arg = ArgMemory.getPointer(); 3691 if (CallInfo.isVariadic()) { 3692 // When passing non-POD arguments by value to variadic functions, we will 3693 // end up with a variadic prototype and an inalloca call site. In such 3694 // cases, we can't do any parameter mismatch checks. Give up and bitcast 3695 // the callee. 3696 unsigned CalleeAS = 3697 cast<llvm::PointerType>(Callee->getType())->getAddressSpace(); 3698 Callee = Builder.CreateBitCast( 3699 Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS)); 3700 } else { 3701 llvm::Type *LastParamTy = 3702 IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1); 3703 if (Arg->getType() != LastParamTy) { 3704 #ifndef NDEBUG 3705 // Assert that these structs have equivalent element types. 3706 llvm::StructType *FullTy = CallInfo.getArgStruct(); 3707 llvm::StructType *DeclaredTy = cast<llvm::StructType>( 3708 cast<llvm::PointerType>(LastParamTy)->getElementType()); 3709 assert(DeclaredTy->getNumElements() == FullTy->getNumElements()); 3710 for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(), 3711 DE = DeclaredTy->element_end(), 3712 FI = FullTy->element_begin(); 3713 DI != DE; ++DI, ++FI) 3714 assert(*DI == *FI); 3715 #endif 3716 Arg = Builder.CreateBitCast(Arg, LastParamTy); 3717 } 3718 } 3719 assert(IRFunctionArgs.hasInallocaArg()); 3720 IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg; 3721 } 3722 3723 if (!CallArgs.getCleanupsToDeactivate().empty()) 3724 deactivateArgCleanupsBeforeCall(*this, CallArgs); 3725 3726 // If the callee is a bitcast of a function to a varargs pointer to function 3727 // type, check to see if we can remove the bitcast. This handles some cases 3728 // with unprototyped functions. 3729 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee)) 3730 if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) { 3731 llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType()); 3732 llvm::FunctionType *CurFT = 3733 cast<llvm::FunctionType>(CurPT->getElementType()); 3734 llvm::FunctionType *ActualFT = CalleeF->getFunctionType(); 3735 3736 if (CE->getOpcode() == llvm::Instruction::BitCast && 3737 ActualFT->getReturnType() == CurFT->getReturnType() && 3738 ActualFT->getNumParams() == CurFT->getNumParams() && 3739 ActualFT->getNumParams() == IRCallArgs.size() && 3740 (CurFT->isVarArg() || !ActualFT->isVarArg())) { 3741 bool ArgsMatch = true; 3742 for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i) 3743 if (ActualFT->getParamType(i) != CurFT->getParamType(i)) { 3744 ArgsMatch = false; 3745 break; 3746 } 3747 3748 // Strip the cast if we can get away with it. This is a nice cleanup, 3749 // but also allows us to inline the function at -O0 if it is marked 3750 // always_inline. 3751 if (ArgsMatch) 3752 Callee = CalleeF; 3753 } 3754 } 3755 3756 assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg()); 3757 for (unsigned i = 0; i < IRCallArgs.size(); ++i) { 3758 // Inalloca argument can have different type. 3759 if (IRFunctionArgs.hasInallocaArg() && 3760 i == IRFunctionArgs.getInallocaArgNo()) 3761 continue; 3762 if (i < IRFuncTy->getNumParams()) 3763 assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i)); 3764 } 3765 3766 unsigned CallingConv; 3767 CodeGen::AttributeListType AttributeList; 3768 CGM.ConstructAttributeList(Callee->getName(), CallInfo, CalleeInfo, 3769 AttributeList, CallingConv, 3770 /*AttrOnCallSite=*/true); 3771 llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(), 3772 AttributeList); 3773 3774 bool CannotThrow; 3775 if (currentFunctionUsesSEHTry()) { 3776 // SEH cares about asynchronous exceptions, everything can "throw." 3777 CannotThrow = false; 3778 } else if (isCleanupPadScope() && 3779 EHPersonality::get(*this).isMSVCXXPersonality()) { 3780 // The MSVC++ personality will implicitly terminate the program if an 3781 // exception is thrown. An unwind edge cannot be reached. 3782 CannotThrow = true; 3783 } else { 3784 // Otherwise, nowunind callsites will never throw. 3785 CannotThrow = Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex, 3786 llvm::Attribute::NoUnwind); 3787 } 3788 llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest(); 3789 3790 SmallVector<llvm::OperandBundleDef, 1> BundleList; 3791 getBundlesForFunclet(Callee, CurrentFuncletPad, BundleList); 3792 3793 llvm::CallSite CS; 3794 if (!InvokeDest) { 3795 CS = Builder.CreateCall(Callee, IRCallArgs, BundleList); 3796 } else { 3797 llvm::BasicBlock *Cont = createBasicBlock("invoke.cont"); 3798 CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs, 3799 BundleList); 3800 EmitBlock(Cont); 3801 } 3802 if (callOrInvoke) 3803 *callOrInvoke = CS.getInstruction(); 3804 3805 if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() && 3806 !CS.hasFnAttr(llvm::Attribute::NoInline)) 3807 Attrs = 3808 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex, 3809 llvm::Attribute::AlwaysInline); 3810 3811 // Disable inlining inside SEH __try blocks. 3812 if (isSEHTryScope()) 3813 Attrs = 3814 Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex, 3815 llvm::Attribute::NoInline); 3816 3817 CS.setAttributes(Attrs); 3818 CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 3819 3820 // Insert instrumentation or attach profile metadata at indirect call sites 3821 if (!CS.getCalledFunction()) 3822 PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget, 3823 CS.getInstruction(), Callee); 3824 3825 // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC 3826 // optimizer it can aggressively ignore unwind edges. 3827 if (CGM.getLangOpts().ObjCAutoRefCount) 3828 AddObjCARCExceptionMetadata(CS.getInstruction()); 3829 3830 // If the call doesn't return, finish the basic block and clear the 3831 // insertion point; this allows the rest of IRgen to discard 3832 // unreachable code. 3833 if (CS.doesNotReturn()) { 3834 if (UnusedReturnSize) 3835 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize), 3836 SRetPtr.getPointer()); 3837 3838 Builder.CreateUnreachable(); 3839 Builder.ClearInsertionPoint(); 3840 3841 // FIXME: For now, emit a dummy basic block because expr emitters in 3842 // generally are not ready to handle emitting expressions at unreachable 3843 // points. 3844 EnsureInsertPoint(); 3845 3846 // Return a reasonable RValue. 3847 return GetUndefRValue(RetTy); 3848 } 3849 3850 llvm::Instruction *CI = CS.getInstruction(); 3851 if (!CI->getType()->isVoidTy()) 3852 CI->setName("call"); 3853 3854 // Emit any writebacks immediately. Arguably this should happen 3855 // after any return-value munging. 3856 if (CallArgs.hasWritebacks()) 3857 emitWritebacks(*this, CallArgs); 3858 3859 // The stack cleanup for inalloca arguments has to run out of the normal 3860 // lexical order, so deactivate it and run it manually here. 3861 CallArgs.freeArgumentMemory(*this); 3862 3863 if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) { 3864 const Decl *TargetDecl = CalleeInfo.getCalleeDecl(); 3865 if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>()) 3866 Call->setTailCallKind(llvm::CallInst::TCK_NoTail); 3867 } 3868 3869 RValue Ret = [&] { 3870 switch (RetAI.getKind()) { 3871 case ABIArgInfo::InAlloca: 3872 case ABIArgInfo::Indirect: { 3873 RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation()); 3874 if (UnusedReturnSize) 3875 EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize), 3876 SRetPtr.getPointer()); 3877 return ret; 3878 } 3879 3880 case ABIArgInfo::CoerceAndExpand: { 3881 auto coercionType = RetAI.getCoerceAndExpandType(); 3882 auto layout = CGM.getDataLayout().getStructLayout(coercionType); 3883 3884 Address addr = SRetPtr; 3885 addr = Builder.CreateElementBitCast(addr, coercionType); 3886 3887 unsigned unpaddedIndex = 0; 3888 for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) { 3889 llvm::Type *eltType = coercionType->getElementType(i); 3890 if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue; 3891 Address eltAddr = Builder.CreateStructGEP(addr, i, layout); 3892 llvm::Value *elt = Builder.CreateExtractValue(CI, unpaddedIndex++); 3893 Builder.CreateStore(elt, eltAddr); 3894 } 3895 break; 3896 } 3897 3898 case ABIArgInfo::Ignore: 3899 // If we are ignoring an argument that had a result, make sure to 3900 // construct the appropriate return value for our caller. 3901 return GetUndefRValue(RetTy); 3902 3903 case ABIArgInfo::Extend: 3904 case ABIArgInfo::Direct: { 3905 llvm::Type *RetIRTy = ConvertType(RetTy); 3906 if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) { 3907 switch (getEvaluationKind(RetTy)) { 3908 case TEK_Complex: { 3909 llvm::Value *Real = Builder.CreateExtractValue(CI, 0); 3910 llvm::Value *Imag = Builder.CreateExtractValue(CI, 1); 3911 return RValue::getComplex(std::make_pair(Real, Imag)); 3912 } 3913 case TEK_Aggregate: { 3914 Address DestPtr = ReturnValue.getValue(); 3915 bool DestIsVolatile = ReturnValue.isVolatile(); 3916 3917 if (!DestPtr.isValid()) { 3918 DestPtr = CreateMemTemp(RetTy, "agg.tmp"); 3919 DestIsVolatile = false; 3920 } 3921 BuildAggStore(*this, CI, DestPtr, DestIsVolatile); 3922 return RValue::getAggregate(DestPtr); 3923 } 3924 case TEK_Scalar: { 3925 // If the argument doesn't match, perform a bitcast to coerce it. This 3926 // can happen due to trivial type mismatches. 3927 llvm::Value *V = CI; 3928 if (V->getType() != RetIRTy) 3929 V = Builder.CreateBitCast(V, RetIRTy); 3930 return RValue::get(V); 3931 } 3932 } 3933 llvm_unreachable("bad evaluation kind"); 3934 } 3935 3936 Address DestPtr = ReturnValue.getValue(); 3937 bool DestIsVolatile = ReturnValue.isVolatile(); 3938 3939 if (!DestPtr.isValid()) { 3940 DestPtr = CreateMemTemp(RetTy, "coerce"); 3941 DestIsVolatile = false; 3942 } 3943 3944 // If the value is offset in memory, apply the offset now. 3945 Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI); 3946 CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this); 3947 3948 return convertTempToRValue(DestPtr, RetTy, SourceLocation()); 3949 } 3950 3951 case ABIArgInfo::Expand: 3952 llvm_unreachable("Invalid ABI kind for return argument"); 3953 } 3954 3955 llvm_unreachable("Unhandled ABIArgInfo::Kind"); 3956 } (); 3957 3958 const Decl *TargetDecl = CalleeInfo.getCalleeDecl(); 3959 3960 if (Ret.isScalar() && TargetDecl) { 3961 if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) { 3962 llvm::Value *OffsetValue = nullptr; 3963 if (const auto *Offset = AA->getOffset()) 3964 OffsetValue = EmitScalarExpr(Offset); 3965 3966 llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment()); 3967 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment); 3968 EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(), 3969 OffsetValue); 3970 } 3971 } 3972 3973 return Ret; 3974 } 3975 3976 /* VarArg handling */ 3977 3978 Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) { 3979 VAListAddr = VE->isMicrosoftABI() 3980 ? EmitMSVAListRef(VE->getSubExpr()) 3981 : EmitVAListRef(VE->getSubExpr()); 3982 QualType Ty = VE->getType(); 3983 if (VE->isMicrosoftABI()) 3984 return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty); 3985 return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty); 3986 } 3987