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