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