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