1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===// 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 // This contains code dealing with code generation of C++ expressions 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CodeGenFunction.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGDebugInfo.h" 18 #include "CGObjCRuntime.h" 19 #include "clang/CodeGen/CGFunctionInfo.h" 20 #include "clang/Frontend/CodeGenOptions.h" 21 #include "llvm/IR/CallSite.h" 22 #include "llvm/IR/Intrinsics.h" 23 24 using namespace clang; 25 using namespace CodeGen; 26 27 static RequiredArgs 28 commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD, 29 llvm::Value *This, llvm::Value *ImplicitParam, 30 QualType ImplicitParamTy, const CallExpr *CE, 31 CallArgList &Args) { 32 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) || 33 isa<CXXOperatorCallExpr>(CE)); 34 assert(MD->isInstance() && 35 "Trying to emit a member or operator call expr on a static method!"); 36 37 // C++11 [class.mfct.non-static]p2: 38 // If a non-static member function of a class X is called for an object that 39 // is not of type X, or of a type derived from X, the behavior is undefined. 40 SourceLocation CallLoc; 41 if (CE) 42 CallLoc = CE->getExprLoc(); 43 CGF.EmitTypeCheck( 44 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall 45 : CodeGenFunction::TCK_MemberCall, 46 CallLoc, This, CGF.getContext().getRecordType(MD->getParent())); 47 48 // Push the this ptr. 49 Args.add(RValue::get(This), MD->getThisType(CGF.getContext())); 50 51 // If there is an implicit parameter (e.g. VTT), emit it. 52 if (ImplicitParam) { 53 Args.add(RValue::get(ImplicitParam), ImplicitParamTy); 54 } 55 56 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 57 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size()); 58 59 // And the rest of the call args. 60 if (CE) { 61 // Special case: skip first argument of CXXOperatorCall (it is "this"). 62 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0; 63 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip), 64 CE->getDirectCallee()); 65 } else { 66 assert( 67 FPT->getNumParams() == 0 && 68 "No CallExpr specified for function with non-zero number of arguments"); 69 } 70 return required; 71 } 72 73 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall( 74 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue, 75 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy, 76 const CallExpr *CE) { 77 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 78 CallArgList Args; 79 RequiredArgs required = commonEmitCXXMemberOrOperatorCall( 80 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args); 81 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), 82 Callee, ReturnValue, Args, MD); 83 } 84 85 RValue CodeGenFunction::EmitCXXDestructorCall( 86 const CXXDestructorDecl *DD, llvm::Value *Callee, llvm::Value *This, 87 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE, 88 StructorType Type) { 89 CallArgList Args; 90 commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam, 91 ImplicitParamTy, CE, Args); 92 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type), 93 Callee, ReturnValueSlot(), Args, DD); 94 } 95 96 static CXXRecordDecl *getCXXRecord(const Expr *E) { 97 QualType T = E->getType(); 98 if (const PointerType *PTy = T->getAs<PointerType>()) 99 T = PTy->getPointeeType(); 100 const RecordType *Ty = T->castAs<RecordType>(); 101 return cast<CXXRecordDecl>(Ty->getDecl()); 102 } 103 104 // Note: This function also emit constructor calls to support a MSVC 105 // extensions allowing explicit constructor function call. 106 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 107 ReturnValueSlot ReturnValue) { 108 const Expr *callee = CE->getCallee()->IgnoreParens(); 109 110 if (isa<BinaryOperator>(callee)) 111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 112 113 const MemberExpr *ME = cast<MemberExpr>(callee); 114 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 115 116 if (MD->isStatic()) { 117 // The method is static, emit it as we would a regular call. 118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD); 119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE, 120 ReturnValue); 121 } 122 123 bool HasQualifier = ME->hasQualifier(); 124 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr; 125 bool IsArrow = ME->isArrow(); 126 const Expr *Base = ME->getBase(); 127 128 return EmitCXXMemberOrOperatorMemberCallExpr( 129 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base); 130 } 131 132 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr( 133 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue, 134 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow, 135 const Expr *Base) { 136 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE)); 137 138 // Compute the object pointer. 139 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier; 140 141 const CXXMethodDecl *DevirtualizedMethod = nullptr; 142 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) { 143 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 144 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl); 145 assert(DevirtualizedMethod); 146 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent(); 147 const Expr *Inner = Base->ignoreParenBaseCasts(); 148 if (DevirtualizedMethod->getReturnType().getCanonicalType() != 149 MD->getReturnType().getCanonicalType()) 150 // If the return types are not the same, this might be a case where more 151 // code needs to run to compensate for it. For example, the derived 152 // method might return a type that inherits form from the return 153 // type of MD and has a prefix. 154 // For now we just avoid devirtualizing these covariant cases. 155 DevirtualizedMethod = nullptr; 156 else if (getCXXRecord(Inner) == DevirtualizedClass) 157 // If the class of the Inner expression is where the dynamic method 158 // is defined, build the this pointer from it. 159 Base = Inner; 160 else if (getCXXRecord(Base) != DevirtualizedClass) { 161 // If the method is defined in a class that is not the best dynamic 162 // one or the one of the full expression, we would have to build 163 // a derived-to-base cast to compute the correct this pointer, but 164 // we don't have support for that yet, so do a virtual call. 165 DevirtualizedMethod = nullptr; 166 } 167 } 168 169 Address This = Address::invalid(); 170 if (IsArrow) 171 This = EmitPointerWithAlignment(Base); 172 else 173 This = EmitLValue(Base).getAddress(); 174 175 176 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) { 177 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr); 178 if (isa<CXXConstructorDecl>(MD) && 179 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) 180 return RValue::get(nullptr); 181 182 if (!MD->getParent()->mayInsertExtraPadding()) { 183 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) { 184 // We don't like to generate the trivial copy/move assignment operator 185 // when it isn't necessary; just produce the proper effect here. 186 // Special case: skip first argument of CXXOperatorCall (it is "this"). 187 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0; 188 Address RHS = EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress(); 189 EmitAggregateAssign(This, RHS, CE->getType()); 190 return RValue::get(This.getPointer()); 191 } 192 193 if (isa<CXXConstructorDecl>(MD) && 194 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) { 195 // Trivial move and copy ctor are the same. 196 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 197 Address RHS = EmitLValue(*CE->arg_begin()).getAddress(); 198 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType()); 199 return RValue::get(This.getPointer()); 200 } 201 llvm_unreachable("unknown trivial member function"); 202 } 203 } 204 205 // Compute the function type we're calling. 206 const CXXMethodDecl *CalleeDecl = 207 DevirtualizedMethod ? DevirtualizedMethod : MD; 208 const CGFunctionInfo *FInfo = nullptr; 209 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl)) 210 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 211 Dtor, StructorType::Complete); 212 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl)) 213 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration( 214 Ctor, StructorType::Complete); 215 else 216 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl); 217 218 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo); 219 220 // C++ [class.virtual]p12: 221 // Explicit qualification with the scope operator (5.1) suppresses the 222 // virtual call mechanism. 223 // 224 // We also don't emit a virtual call if the base expression has a record type 225 // because then we know what the type is. 226 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod; 227 llvm::Value *Callee; 228 229 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) { 230 assert(CE->arg_begin() == CE->arg_end() && 231 "Destructor shouldn't have explicit parameters"); 232 assert(ReturnValue.isNull() && "Destructor shouldn't have return value"); 233 if (UseVirtualCall) { 234 CGM.getCXXABI().EmitVirtualDestructorCall( 235 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE)); 236 } else { 237 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 238 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 239 else if (!DevirtualizedMethod) 240 Callee = 241 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty); 242 else { 243 const CXXDestructorDecl *DDtor = 244 cast<CXXDestructorDecl>(DevirtualizedMethod); 245 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty); 246 } 247 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(), 248 /*ImplicitParam=*/nullptr, QualType(), CE); 249 } 250 return RValue::get(nullptr); 251 } 252 253 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) { 254 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty); 255 } else if (UseVirtualCall) { 256 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty, 257 CE->getLocStart()); 258 } else { 259 if (SanOpts.has(SanitizerKind::CFINVCall) && 260 MD->getParent()->isDynamicClass()) { 261 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent()); 262 EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall, 263 CE->getLocStart()); 264 } 265 266 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier) 267 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty); 268 else if (!DevirtualizedMethod) 269 Callee = CGM.GetAddrOfFunction(MD, Ty); 270 else { 271 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty); 272 } 273 } 274 275 if (MD->isVirtual()) { 276 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall( 277 *this, CalleeDecl, This, UseVirtualCall); 278 } 279 280 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(), 281 /*ImplicitParam=*/nullptr, QualType(), CE); 282 } 283 284 RValue 285 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 286 ReturnValueSlot ReturnValue) { 287 const BinaryOperator *BO = 288 cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 289 const Expr *BaseExpr = BO->getLHS(); 290 const Expr *MemFnExpr = BO->getRHS(); 291 292 const MemberPointerType *MPT = 293 MemFnExpr->getType()->castAs<MemberPointerType>(); 294 295 const FunctionProtoType *FPT = 296 MPT->getPointeeType()->castAs<FunctionProtoType>(); 297 const CXXRecordDecl *RD = 298 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 299 300 // Get the member function pointer. 301 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 302 303 // Emit the 'this' pointer. 304 Address This = Address::invalid(); 305 if (BO->getOpcode() == BO_PtrMemI) 306 This = EmitPointerWithAlignment(BaseExpr); 307 else 308 This = EmitLValue(BaseExpr).getAddress(); 309 310 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(), 311 QualType(MPT->getClass(), 0)); 312 313 // Ask the ABI to load the callee. Note that This is modified. 314 llvm::Value *ThisPtrForCall = nullptr; 315 llvm::Value *Callee = 316 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This, 317 ThisPtrForCall, MemFnPtr, MPT); 318 319 CallArgList Args; 320 321 QualType ThisType = 322 getContext().getPointerType(getContext().getTagDeclType(RD)); 323 324 // Push the this ptr. 325 Args.add(RValue::get(ThisPtrForCall), ThisType); 326 327 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1); 328 329 // And the rest of the call args 330 EmitCallArgs(Args, FPT, E->arguments(), E->getDirectCallee()); 331 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required), 332 Callee, ReturnValue, Args); 333 } 334 335 RValue 336 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 337 const CXXMethodDecl *MD, 338 ReturnValueSlot ReturnValue) { 339 assert(MD->isInstance() && 340 "Trying to emit a member call expr on a static method!"); 341 return EmitCXXMemberOrOperatorMemberCallExpr( 342 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr, 343 /*IsArrow=*/false, E->getArg(0)); 344 } 345 346 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 347 ReturnValueSlot ReturnValue) { 348 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 349 } 350 351 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 352 Address DestPtr, 353 const CXXRecordDecl *Base) { 354 if (Base->isEmpty()) 355 return; 356 357 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty); 358 359 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 360 CharUnits NVSize = Layout.getNonVirtualSize(); 361 362 // We cannot simply zero-initialize the entire base sub-object if vbptrs are 363 // present, they are initialized by the most derived class before calling the 364 // constructor. 365 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores; 366 Stores.emplace_back(CharUnits::Zero(), NVSize); 367 368 // Each store is split by the existence of a vbptr. 369 CharUnits VBPtrWidth = CGF.getPointerSize(); 370 std::vector<CharUnits> VBPtrOffsets = 371 CGF.CGM.getCXXABI().getVBPtrOffsets(Base); 372 for (CharUnits VBPtrOffset : VBPtrOffsets) { 373 // Stop before we hit any virtual base pointers located in virtual bases. 374 if (VBPtrOffset >= NVSize) 375 break; 376 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val(); 377 CharUnits LastStoreOffset = LastStore.first; 378 CharUnits LastStoreSize = LastStore.second; 379 380 CharUnits SplitBeforeOffset = LastStoreOffset; 381 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset; 382 assert(!SplitBeforeSize.isNegative() && "negative store size!"); 383 if (!SplitBeforeSize.isZero()) 384 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize); 385 386 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth; 387 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset; 388 assert(!SplitAfterSize.isNegative() && "negative store size!"); 389 if (!SplitAfterSize.isZero()) 390 Stores.emplace_back(SplitAfterOffset, SplitAfterSize); 391 } 392 393 // If the type contains a pointer to data member we can't memset it to zero. 394 // Instead, create a null constant and copy it to the destination. 395 // TODO: there are other patterns besides zero that we can usefully memset, 396 // like -1, which happens to be the pattern used by member-pointers. 397 // TODO: isZeroInitializable can be over-conservative in the case where a 398 // virtual base contains a member pointer. 399 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base); 400 if (!NullConstantForBase->isNullValue()) { 401 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable( 402 CGF.CGM.getModule(), NullConstantForBase->getType(), 403 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage, 404 NullConstantForBase, Twine()); 405 406 CharUnits Align = std::max(Layout.getNonVirtualAlignment(), 407 DestPtr.getAlignment()); 408 NullVariable->setAlignment(Align.getQuantity()); 409 410 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align); 411 412 // Get and call the appropriate llvm.memcpy overload. 413 for (std::pair<CharUnits, CharUnits> Store : Stores) { 414 CharUnits StoreOffset = Store.first; 415 CharUnits StoreSize = Store.second; 416 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 417 CGF.Builder.CreateMemCpy( 418 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 419 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset), 420 StoreSizeVal); 421 } 422 423 // Otherwise, just memset the whole thing to zero. This is legal 424 // because in LLVM, all default initializers (other than the ones we just 425 // handled above) are guaranteed to have a bit pattern of all zeros. 426 } else { 427 for (std::pair<CharUnits, CharUnits> Store : Stores) { 428 CharUnits StoreOffset = Store.first; 429 CharUnits StoreSize = Store.second; 430 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize); 431 CGF.Builder.CreateMemSet( 432 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset), 433 CGF.Builder.getInt8(0), StoreSizeVal); 434 } 435 } 436 } 437 438 void 439 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 440 AggValueSlot Dest) { 441 assert(!Dest.isIgnored() && "Must have a destination!"); 442 const CXXConstructorDecl *CD = E->getConstructor(); 443 444 // If we require zero initialization before (or instead of) calling the 445 // constructor, as can be the case with a non-user-provided default 446 // constructor, emit the zero initialization now, unless destination is 447 // already zeroed. 448 if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 449 switch (E->getConstructionKind()) { 450 case CXXConstructExpr::CK_Delegating: 451 case CXXConstructExpr::CK_Complete: 452 EmitNullInitialization(Dest.getAddress(), E->getType()); 453 break; 454 case CXXConstructExpr::CK_VirtualBase: 455 case CXXConstructExpr::CK_NonVirtualBase: 456 EmitNullBaseClassInitialization(*this, Dest.getAddress(), 457 CD->getParent()); 458 break; 459 } 460 } 461 462 // If this is a call to a trivial default constructor, do nothing. 463 if (CD->isTrivial() && CD->isDefaultConstructor()) 464 return; 465 466 // Elide the constructor if we're constructing from a temporary. 467 // The temporary check is required because Sema sets this on NRVO 468 // returns. 469 if (getLangOpts().ElideConstructors && E->isElidable()) { 470 assert(getContext().hasSameUnqualifiedType(E->getType(), 471 E->getArg(0)->getType())); 472 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) { 473 EmitAggExpr(E->getArg(0), Dest); 474 return; 475 } 476 } 477 478 if (const ArrayType *arrayType 479 = getContext().getAsArrayType(E->getType())) { 480 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E); 481 } else { 482 CXXCtorType Type = Ctor_Complete; 483 bool ForVirtualBase = false; 484 bool Delegating = false; 485 486 switch (E->getConstructionKind()) { 487 case CXXConstructExpr::CK_Delegating: 488 // We should be emitting a constructor; GlobalDecl will assert this 489 Type = CurGD.getCtorType(); 490 Delegating = true; 491 break; 492 493 case CXXConstructExpr::CK_Complete: 494 Type = Ctor_Complete; 495 break; 496 497 case CXXConstructExpr::CK_VirtualBase: 498 ForVirtualBase = true; 499 // fall-through 500 501 case CXXConstructExpr::CK_NonVirtualBase: 502 Type = Ctor_Base; 503 } 504 505 // Call the constructor. 506 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating, 507 Dest.getAddress(), E); 508 } 509 } 510 511 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src, 512 const Expr *Exp) { 513 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 514 Exp = E->getSubExpr(); 515 assert(isa<CXXConstructExpr>(Exp) && 516 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 517 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 518 const CXXConstructorDecl *CD = E->getConstructor(); 519 RunCleanupsScope Scope(*this); 520 521 // If we require zero initialization before (or instead of) calling the 522 // constructor, as can be the case with a non-user-provided default 523 // constructor, emit the zero initialization now. 524 // FIXME. Do I still need this for a copy ctor synthesis? 525 if (E->requiresZeroInitialization()) 526 EmitNullInitialization(Dest, E->getType()); 527 528 assert(!getContext().getAsConstantArrayType(E->getType()) 529 && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 530 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E); 531 } 532 533 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 534 const CXXNewExpr *E) { 535 if (!E->isArray()) 536 return CharUnits::Zero(); 537 538 // No cookie is required if the operator new[] being used is the 539 // reserved placement operator new[]. 540 if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 541 return CharUnits::Zero(); 542 543 return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 544 } 545 546 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 547 const CXXNewExpr *e, 548 unsigned minElements, 549 llvm::Value *&numElements, 550 llvm::Value *&sizeWithoutCookie) { 551 QualType type = e->getAllocatedType(); 552 553 if (!e->isArray()) { 554 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 555 sizeWithoutCookie 556 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 557 return sizeWithoutCookie; 558 } 559 560 // The width of size_t. 561 unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 562 563 // Figure out the cookie size. 564 llvm::APInt cookieSize(sizeWidth, 565 CalculateCookiePadding(CGF, e).getQuantity()); 566 567 // Emit the array size expression. 568 // We multiply the size of all dimensions for NumElements. 569 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 570 numElements = CGF.EmitScalarExpr(e->getArraySize()); 571 assert(isa<llvm::IntegerType>(numElements->getType())); 572 573 // The number of elements can be have an arbitrary integer type; 574 // essentially, we need to multiply it by a constant factor, add a 575 // cookie size, and verify that the result is representable as a 576 // size_t. That's just a gloss, though, and it's wrong in one 577 // important way: if the count is negative, it's an error even if 578 // the cookie size would bring the total size >= 0. 579 bool isSigned 580 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType(); 581 llvm::IntegerType *numElementsType 582 = cast<llvm::IntegerType>(numElements->getType()); 583 unsigned numElementsWidth = numElementsType->getBitWidth(); 584 585 // Compute the constant factor. 586 llvm::APInt arraySizeMultiplier(sizeWidth, 1); 587 while (const ConstantArrayType *CAT 588 = CGF.getContext().getAsConstantArrayType(type)) { 589 type = CAT->getElementType(); 590 arraySizeMultiplier *= CAT->getSize(); 591 } 592 593 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 594 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 595 typeSizeMultiplier *= arraySizeMultiplier; 596 597 // This will be a size_t. 598 llvm::Value *size; 599 600 // If someone is doing 'new int[42]' there is no need to do a dynamic check. 601 // Don't bloat the -O0 code. 602 if (llvm::ConstantInt *numElementsC = 603 dyn_cast<llvm::ConstantInt>(numElements)) { 604 const llvm::APInt &count = numElementsC->getValue(); 605 606 bool hasAnyOverflow = false; 607 608 // If 'count' was a negative number, it's an overflow. 609 if (isSigned && count.isNegative()) 610 hasAnyOverflow = true; 611 612 // We want to do all this arithmetic in size_t. If numElements is 613 // wider than that, check whether it's already too big, and if so, 614 // overflow. 615 else if (numElementsWidth > sizeWidth && 616 numElementsWidth - sizeWidth > count.countLeadingZeros()) 617 hasAnyOverflow = true; 618 619 // Okay, compute a count at the right width. 620 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 621 622 // If there is a brace-initializer, we cannot allocate fewer elements than 623 // there are initializers. If we do, that's treated like an overflow. 624 if (adjustedCount.ult(minElements)) 625 hasAnyOverflow = true; 626 627 // Scale numElements by that. This might overflow, but we don't 628 // care because it only overflows if allocationSize does, too, and 629 // if that overflows then we shouldn't use this. 630 numElements = llvm::ConstantInt::get(CGF.SizeTy, 631 adjustedCount * arraySizeMultiplier); 632 633 // Compute the size before cookie, and track whether it overflowed. 634 bool overflow; 635 llvm::APInt allocationSize 636 = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 637 hasAnyOverflow |= overflow; 638 639 // Add in the cookie, and check whether it's overflowed. 640 if (cookieSize != 0) { 641 // Save the current size without a cookie. This shouldn't be 642 // used if there was overflow. 643 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 644 645 allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 646 hasAnyOverflow |= overflow; 647 } 648 649 // On overflow, produce a -1 so operator new will fail. 650 if (hasAnyOverflow) { 651 size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 652 } else { 653 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 654 } 655 656 // Otherwise, we might need to use the overflow intrinsics. 657 } else { 658 // There are up to five conditions we need to test for: 659 // 1) if isSigned, we need to check whether numElements is negative; 660 // 2) if numElementsWidth > sizeWidth, we need to check whether 661 // numElements is larger than something representable in size_t; 662 // 3) if minElements > 0, we need to check whether numElements is smaller 663 // than that. 664 // 4) we need to compute 665 // sizeWithoutCookie := numElements * typeSizeMultiplier 666 // and check whether it overflows; and 667 // 5) if we need a cookie, we need to compute 668 // size := sizeWithoutCookie + cookieSize 669 // and check whether it overflows. 670 671 llvm::Value *hasOverflow = nullptr; 672 673 // If numElementsWidth > sizeWidth, then one way or another, we're 674 // going to have to do a comparison for (2), and this happens to 675 // take care of (1), too. 676 if (numElementsWidth > sizeWidth) { 677 llvm::APInt threshold(numElementsWidth, 1); 678 threshold <<= sizeWidth; 679 680 llvm::Value *thresholdV 681 = llvm::ConstantInt::get(numElementsType, threshold); 682 683 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 684 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 685 686 // Otherwise, if we're signed, we want to sext up to size_t. 687 } else if (isSigned) { 688 if (numElementsWidth < sizeWidth) 689 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 690 691 // If there's a non-1 type size multiplier, then we can do the 692 // signedness check at the same time as we do the multiply 693 // because a negative number times anything will cause an 694 // unsigned overflow. Otherwise, we have to do it here. But at least 695 // in this case, we can subsume the >= minElements check. 696 if (typeSizeMultiplier == 1) 697 hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 698 llvm::ConstantInt::get(CGF.SizeTy, minElements)); 699 700 // Otherwise, zext up to size_t if necessary. 701 } else if (numElementsWidth < sizeWidth) { 702 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 703 } 704 705 assert(numElements->getType() == CGF.SizeTy); 706 707 if (minElements) { 708 // Don't allow allocation of fewer elements than we have initializers. 709 if (!hasOverflow) { 710 hasOverflow = CGF.Builder.CreateICmpULT(numElements, 711 llvm::ConstantInt::get(CGF.SizeTy, minElements)); 712 } else if (numElementsWidth > sizeWidth) { 713 // The other existing overflow subsumes this check. 714 // We do an unsigned comparison, since any signed value < -1 is 715 // taken care of either above or below. 716 hasOverflow = CGF.Builder.CreateOr(hasOverflow, 717 CGF.Builder.CreateICmpULT(numElements, 718 llvm::ConstantInt::get(CGF.SizeTy, minElements))); 719 } 720 } 721 722 size = numElements; 723 724 // Multiply by the type size if necessary. This multiplier 725 // includes all the factors for nested arrays. 726 // 727 // This step also causes numElements to be scaled up by the 728 // nested-array factor if necessary. Overflow on this computation 729 // can be ignored because the result shouldn't be used if 730 // allocation fails. 731 if (typeSizeMultiplier != 1) { 732 llvm::Value *umul_with_overflow 733 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 734 735 llvm::Value *tsmV = 736 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 737 llvm::Value *result = 738 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV}); 739 740 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 741 if (hasOverflow) 742 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 743 else 744 hasOverflow = overflowed; 745 746 size = CGF.Builder.CreateExtractValue(result, 0); 747 748 // Also scale up numElements by the array size multiplier. 749 if (arraySizeMultiplier != 1) { 750 // If the base element type size is 1, then we can re-use the 751 // multiply we just did. 752 if (typeSize.isOne()) { 753 assert(arraySizeMultiplier == typeSizeMultiplier); 754 numElements = size; 755 756 // Otherwise we need a separate multiply. 757 } else { 758 llvm::Value *asmV = 759 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 760 numElements = CGF.Builder.CreateMul(numElements, asmV); 761 } 762 } 763 } else { 764 // numElements doesn't need to be scaled. 765 assert(arraySizeMultiplier == 1); 766 } 767 768 // Add in the cookie size if necessary. 769 if (cookieSize != 0) { 770 sizeWithoutCookie = size; 771 772 llvm::Value *uadd_with_overflow 773 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 774 775 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 776 llvm::Value *result = 777 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV}); 778 779 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 780 if (hasOverflow) 781 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 782 else 783 hasOverflow = overflowed; 784 785 size = CGF.Builder.CreateExtractValue(result, 0); 786 } 787 788 // If we had any possibility of dynamic overflow, make a select to 789 // overwrite 'size' with an all-ones value, which should cause 790 // operator new to throw. 791 if (hasOverflow) 792 size = CGF.Builder.CreateSelect(hasOverflow, 793 llvm::Constant::getAllOnesValue(CGF.SizeTy), 794 size); 795 } 796 797 if (cookieSize == 0) 798 sizeWithoutCookie = size; 799 else 800 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 801 802 return size; 803 } 804 805 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 806 QualType AllocType, Address NewPtr) { 807 // FIXME: Refactor with EmitExprAsInit. 808 switch (CGF.getEvaluationKind(AllocType)) { 809 case TEK_Scalar: 810 CGF.EmitScalarInit(Init, nullptr, 811 CGF.MakeAddrLValue(NewPtr, AllocType), false); 812 return; 813 case TEK_Complex: 814 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType), 815 /*isInit*/ true); 816 return; 817 case TEK_Aggregate: { 818 AggValueSlot Slot 819 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(), 820 AggValueSlot::IsDestructed, 821 AggValueSlot::DoesNotNeedGCBarriers, 822 AggValueSlot::IsNotAliased); 823 CGF.EmitAggExpr(Init, Slot); 824 return; 825 } 826 } 827 llvm_unreachable("bad evaluation kind"); 828 } 829 830 void CodeGenFunction::EmitNewArrayInitializer( 831 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy, 832 Address BeginPtr, llvm::Value *NumElements, 833 llvm::Value *AllocSizeWithoutCookie) { 834 // If we have a type with trivial initialization and no initializer, 835 // there's nothing to do. 836 if (!E->hasInitializer()) 837 return; 838 839 Address CurPtr = BeginPtr; 840 841 unsigned InitListElements = 0; 842 843 const Expr *Init = E->getInitializer(); 844 Address EndOfInit = Address::invalid(); 845 QualType::DestructionKind DtorKind = ElementType.isDestructedType(); 846 EHScopeStack::stable_iterator Cleanup; 847 llvm::Instruction *CleanupDominator = nullptr; 848 849 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType); 850 CharUnits ElementAlign = 851 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize); 852 853 // If the initializer is an initializer list, first do the explicit elements. 854 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 855 InitListElements = ILE->getNumInits(); 856 857 // If this is a multi-dimensional array new, we will initialize multiple 858 // elements with each init list element. 859 QualType AllocType = E->getAllocatedType(); 860 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>( 861 AllocType->getAsArrayTypeUnsafe())) { 862 ElementTy = ConvertTypeForMem(AllocType); 863 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy); 864 InitListElements *= getContext().getConstantArrayElementCount(CAT); 865 } 866 867 // Enter a partial-destruction Cleanup if necessary. 868 if (needsEHCleanup(DtorKind)) { 869 // In principle we could tell the Cleanup where we are more 870 // directly, but the control flow can get so varied here that it 871 // would actually be quite complex. Therefore we go through an 872 // alloca. 873 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(), 874 "array.init.end"); 875 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit); 876 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit, 877 ElementType, ElementAlign, 878 getDestroyer(DtorKind)); 879 Cleanup = EHStack.stable_begin(); 880 } 881 882 CharUnits StartAlign = CurPtr.getAlignment(); 883 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 884 // Tell the cleanup that it needs to destroy up to this 885 // element. TODO: some of these stores can be trivially 886 // observed to be unnecessary. 887 if (EndOfInit.isValid()) { 888 auto FinishedPtr = 889 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType()); 890 Builder.CreateStore(FinishedPtr, EndOfInit); 891 } 892 // FIXME: If the last initializer is an incomplete initializer list for 893 // an array, and we have an array filler, we can fold together the two 894 // initialization loops. 895 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), 896 ILE->getInit(i)->getType(), CurPtr); 897 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(), 898 Builder.getSize(1), 899 "array.exp.next"), 900 StartAlign.alignmentAtOffset((i + 1) * ElementSize)); 901 } 902 903 // The remaining elements are filled with the array filler expression. 904 Init = ILE->getArrayFiller(); 905 906 // Extract the initializer for the individual array elements by pulling 907 // out the array filler from all the nested initializer lists. This avoids 908 // generating a nested loop for the initialization. 909 while (Init && Init->getType()->isConstantArrayType()) { 910 auto *SubILE = dyn_cast<InitListExpr>(Init); 911 if (!SubILE) 912 break; 913 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?"); 914 Init = SubILE->getArrayFiller(); 915 } 916 917 // Switch back to initializing one base element at a time. 918 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType()); 919 } 920 921 // Attempt to perform zero-initialization using memset. 922 auto TryMemsetInitialization = [&]() -> bool { 923 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI, 924 // we can initialize with a memset to -1. 925 if (!CGM.getTypes().isZeroInitializable(ElementType)) 926 return false; 927 928 // Optimization: since zero initialization will just set the memory 929 // to all zeroes, generate a single memset to do it in one shot. 930 931 // Subtract out the size of any elements we've already initialized. 932 auto *RemainingSize = AllocSizeWithoutCookie; 933 if (InitListElements) { 934 // We know this can't overflow; we check this when doing the allocation. 935 auto *InitializedSize = llvm::ConstantInt::get( 936 RemainingSize->getType(), 937 getContext().getTypeSizeInChars(ElementType).getQuantity() * 938 InitListElements); 939 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize); 940 } 941 942 // Create the memset. 943 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false); 944 return true; 945 }; 946 947 // If all elements have already been initialized, skip any further 948 // initialization. 949 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements); 950 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) { 951 // If there was a Cleanup, deactivate it. 952 if (CleanupDominator) 953 DeactivateCleanupBlock(Cleanup, CleanupDominator); 954 return; 955 } 956 957 assert(Init && "have trailing elements to initialize but no initializer"); 958 959 // If this is a constructor call, try to optimize it out, and failing that 960 // emit a single loop to initialize all remaining elements. 961 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 962 CXXConstructorDecl *Ctor = CCE->getConstructor(); 963 if (Ctor->isTrivial()) { 964 // If new expression did not specify value-initialization, then there 965 // is no initialization. 966 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 967 return; 968 969 if (TryMemsetInitialization()) 970 return; 971 } 972 973 // Store the new Cleanup position for irregular Cleanups. 974 // 975 // FIXME: Share this cleanup with the constructor call emission rather than 976 // having it create a cleanup of its own. 977 if (EndOfInit.isValid()) 978 Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 979 980 // Emit a constructor call loop to initialize the remaining elements. 981 if (InitListElements) 982 NumElements = Builder.CreateSub( 983 NumElements, 984 llvm::ConstantInt::get(NumElements->getType(), InitListElements)); 985 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE, 986 CCE->requiresZeroInitialization()); 987 return; 988 } 989 990 // If this is value-initialization, we can usually use memset. 991 ImplicitValueInitExpr IVIE(ElementType); 992 if (isa<ImplicitValueInitExpr>(Init)) { 993 if (TryMemsetInitialization()) 994 return; 995 996 // Switch to an ImplicitValueInitExpr for the element type. This handles 997 // only one case: multidimensional array new of pointers to members. In 998 // all other cases, we already have an initializer for the array element. 999 Init = &IVIE; 1000 } 1001 1002 // At this point we should have found an initializer for the individual 1003 // elements of the array. 1004 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) && 1005 "got wrong type of element to initialize"); 1006 1007 // If we have an empty initializer list, we can usually use memset. 1008 if (auto *ILE = dyn_cast<InitListExpr>(Init)) 1009 if (ILE->getNumInits() == 0 && TryMemsetInitialization()) 1010 return; 1011 1012 // If we have a struct whose every field is value-initialized, we can 1013 // usually use memset. 1014 if (auto *ILE = dyn_cast<InitListExpr>(Init)) { 1015 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) { 1016 if (RType->getDecl()->isStruct()) { 1017 unsigned NumElements = 0; 1018 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl())) 1019 NumElements = CXXRD->getNumBases(); 1020 for (auto *Field : RType->getDecl()->fields()) 1021 if (!Field->isUnnamedBitfield()) 1022 ++NumElements; 1023 // FIXME: Recurse into nested InitListExprs. 1024 if (ILE->getNumInits() == NumElements) 1025 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) 1026 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i))) 1027 --NumElements; 1028 if (ILE->getNumInits() == NumElements && TryMemsetInitialization()) 1029 return; 1030 } 1031 } 1032 } 1033 1034 // Create the loop blocks. 1035 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock(); 1036 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop"); 1037 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end"); 1038 1039 // Find the end of the array, hoisted out of the loop. 1040 llvm::Value *EndPtr = 1041 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end"); 1042 1043 // If the number of elements isn't constant, we have to now check if there is 1044 // anything left to initialize. 1045 if (!ConstNum) { 1046 llvm::Value *IsEmpty = 1047 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty"); 1048 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB); 1049 } 1050 1051 // Enter the loop. 1052 EmitBlock(LoopBB); 1053 1054 // Set up the current-element phi. 1055 llvm::PHINode *CurPtrPhi = 1056 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur"); 1057 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB); 1058 1059 CurPtr = Address(CurPtrPhi, ElementAlign); 1060 1061 // Store the new Cleanup position for irregular Cleanups. 1062 if (EndOfInit.isValid()) 1063 Builder.CreateStore(CurPtr.getPointer(), EndOfInit); 1064 1065 // Enter a partial-destruction Cleanup if necessary. 1066 if (!CleanupDominator && needsEHCleanup(DtorKind)) { 1067 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(), 1068 ElementType, ElementAlign, 1069 getDestroyer(DtorKind)); 1070 Cleanup = EHStack.stable_begin(); 1071 CleanupDominator = Builder.CreateUnreachable(); 1072 } 1073 1074 // Emit the initializer into this element. 1075 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr); 1076 1077 // Leave the Cleanup if we entered one. 1078 if (CleanupDominator) { 1079 DeactivateCleanupBlock(Cleanup, CleanupDominator); 1080 CleanupDominator->eraseFromParent(); 1081 } 1082 1083 // Advance to the next element by adjusting the pointer type as necessary. 1084 llvm::Value *NextPtr = 1085 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1, 1086 "array.next"); 1087 1088 // Check whether we've gotten to the end of the array and, if so, 1089 // exit the loop. 1090 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend"); 1091 Builder.CreateCondBr(IsEnd, ContBB, LoopBB); 1092 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock()); 1093 1094 EmitBlock(ContBB); 1095 } 1096 1097 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 1098 QualType ElementType, llvm::Type *ElementTy, 1099 Address NewPtr, llvm::Value *NumElements, 1100 llvm::Value *AllocSizeWithoutCookie) { 1101 ApplyDebugLocation DL(CGF, E); 1102 if (E->isArray()) 1103 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements, 1104 AllocSizeWithoutCookie); 1105 else if (const Expr *Init = E->getInitializer()) 1106 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr); 1107 } 1108 1109 /// Emit a call to an operator new or operator delete function, as implicitly 1110 /// created by new-expressions and delete-expressions. 1111 static RValue EmitNewDeleteCall(CodeGenFunction &CGF, 1112 const FunctionDecl *Callee, 1113 const FunctionProtoType *CalleeType, 1114 const CallArgList &Args) { 1115 llvm::Instruction *CallOrInvoke; 1116 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee); 1117 RValue RV = 1118 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall( 1119 Args, CalleeType, /*chainCall=*/false), 1120 CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke); 1121 1122 /// C++1y [expr.new]p10: 1123 /// [In a new-expression,] an implementation is allowed to omit a call 1124 /// to a replaceable global allocation function. 1125 /// 1126 /// We model such elidable calls with the 'builtin' attribute. 1127 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr); 1128 if (Callee->isReplaceableGlobalAllocationFunction() && 1129 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) { 1130 // FIXME: Add addAttribute to CallSite. 1131 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke)) 1132 CI->addAttribute(llvm::AttributeSet::FunctionIndex, 1133 llvm::Attribute::Builtin); 1134 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke)) 1135 II->addAttribute(llvm::AttributeSet::FunctionIndex, 1136 llvm::Attribute::Builtin); 1137 else 1138 llvm_unreachable("unexpected kind of call instruction"); 1139 } 1140 1141 return RV; 1142 } 1143 1144 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type, 1145 const Expr *Arg, 1146 bool IsDelete) { 1147 CallArgList Args; 1148 const Stmt *ArgS = Arg; 1149 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS)); 1150 // Find the allocation or deallocation function that we're calling. 1151 ASTContext &Ctx = getContext(); 1152 DeclarationName Name = Ctx.DeclarationNames 1153 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New); 1154 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name)) 1155 if (auto *FD = dyn_cast<FunctionDecl>(Decl)) 1156 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0))) 1157 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args); 1158 llvm_unreachable("predeclared global operator new/delete is missing"); 1159 } 1160 1161 namespace { 1162 /// A cleanup to call the given 'operator delete' function upon 1163 /// abnormal exit from a new expression. 1164 class CallDeleteDuringNew final : public EHScopeStack::Cleanup { 1165 size_t NumPlacementArgs; 1166 const FunctionDecl *OperatorDelete; 1167 llvm::Value *Ptr; 1168 llvm::Value *AllocSize; 1169 1170 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); } 1171 1172 public: 1173 static size_t getExtraSize(size_t NumPlacementArgs) { 1174 return NumPlacementArgs * sizeof(RValue); 1175 } 1176 1177 CallDeleteDuringNew(size_t NumPlacementArgs, 1178 const FunctionDecl *OperatorDelete, 1179 llvm::Value *Ptr, 1180 llvm::Value *AllocSize) 1181 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete), 1182 Ptr(Ptr), AllocSize(AllocSize) {} 1183 1184 void setPlacementArg(unsigned I, RValue Arg) { 1185 assert(I < NumPlacementArgs && "index out of range"); 1186 getPlacementArgs()[I] = Arg; 1187 } 1188 1189 void Emit(CodeGenFunction &CGF, Flags flags) override { 1190 const FunctionProtoType *FPT 1191 = OperatorDelete->getType()->getAs<FunctionProtoType>(); 1192 assert(FPT->getNumParams() == NumPlacementArgs + 1 || 1193 (FPT->getNumParams() == 2 && NumPlacementArgs == 0)); 1194 1195 CallArgList DeleteArgs; 1196 1197 // The first argument is always a void*. 1198 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin(); 1199 DeleteArgs.add(RValue::get(Ptr), *AI++); 1200 1201 // A member 'operator delete' can take an extra 'size_t' argument. 1202 if (FPT->getNumParams() == NumPlacementArgs + 2) 1203 DeleteArgs.add(RValue::get(AllocSize), *AI++); 1204 1205 // Pass the rest of the arguments, which must match exactly. 1206 for (unsigned I = 0; I != NumPlacementArgs; ++I) 1207 DeleteArgs.add(getPlacementArgs()[I], *AI++); 1208 1209 // Call 'operator delete'. 1210 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 1211 } 1212 }; 1213 1214 /// A cleanup to call the given 'operator delete' function upon 1215 /// abnormal exit from a new expression when the new expression is 1216 /// conditional. 1217 class CallDeleteDuringConditionalNew final : public EHScopeStack::Cleanup { 1218 size_t NumPlacementArgs; 1219 const FunctionDecl *OperatorDelete; 1220 DominatingValue<RValue>::saved_type Ptr; 1221 DominatingValue<RValue>::saved_type AllocSize; 1222 1223 DominatingValue<RValue>::saved_type *getPlacementArgs() { 1224 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1); 1225 } 1226 1227 public: 1228 static size_t getExtraSize(size_t NumPlacementArgs) { 1229 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type); 1230 } 1231 1232 CallDeleteDuringConditionalNew(size_t NumPlacementArgs, 1233 const FunctionDecl *OperatorDelete, 1234 DominatingValue<RValue>::saved_type Ptr, 1235 DominatingValue<RValue>::saved_type AllocSize) 1236 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete), 1237 Ptr(Ptr), AllocSize(AllocSize) {} 1238 1239 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) { 1240 assert(I < NumPlacementArgs && "index out of range"); 1241 getPlacementArgs()[I] = Arg; 1242 } 1243 1244 void Emit(CodeGenFunction &CGF, Flags flags) override { 1245 const FunctionProtoType *FPT 1246 = OperatorDelete->getType()->getAs<FunctionProtoType>(); 1247 assert(FPT->getNumParams() == NumPlacementArgs + 1 || 1248 (FPT->getNumParams() == 2 && NumPlacementArgs == 0)); 1249 1250 CallArgList DeleteArgs; 1251 1252 // The first argument is always a void*. 1253 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin(); 1254 DeleteArgs.add(Ptr.restore(CGF), *AI++); 1255 1256 // A member 'operator delete' can take an extra 'size_t' argument. 1257 if (FPT->getNumParams() == NumPlacementArgs + 2) { 1258 RValue RV = AllocSize.restore(CGF); 1259 DeleteArgs.add(RV, *AI++); 1260 } 1261 1262 // Pass the rest of the arguments, which must match exactly. 1263 for (unsigned I = 0; I != NumPlacementArgs; ++I) { 1264 RValue RV = getPlacementArgs()[I].restore(CGF); 1265 DeleteArgs.add(RV, *AI++); 1266 } 1267 1268 // Call 'operator delete'. 1269 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs); 1270 } 1271 }; 1272 } 1273 1274 /// Enter a cleanup to call 'operator delete' if the initializer in a 1275 /// new-expression throws. 1276 static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 1277 const CXXNewExpr *E, 1278 Address NewPtr, 1279 llvm::Value *AllocSize, 1280 const CallArgList &NewArgs) { 1281 // If we're not inside a conditional branch, then the cleanup will 1282 // dominate and we can do the easier (and more efficient) thing. 1283 if (!CGF.isInConditionalBranch()) { 1284 CallDeleteDuringNew *Cleanup = CGF.EHStack 1285 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup, 1286 E->getNumPlacementArgs(), 1287 E->getOperatorDelete(), 1288 NewPtr.getPointer(), 1289 AllocSize); 1290 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) 1291 Cleanup->setPlacementArg(I, NewArgs[I+1].RV); 1292 1293 return; 1294 } 1295 1296 // Otherwise, we need to save all this stuff. 1297 DominatingValue<RValue>::saved_type SavedNewPtr = 1298 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer())); 1299 DominatingValue<RValue>::saved_type SavedAllocSize = 1300 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 1301 1302 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack 1303 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup, 1304 E->getNumPlacementArgs(), 1305 E->getOperatorDelete(), 1306 SavedNewPtr, 1307 SavedAllocSize); 1308 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) 1309 Cleanup->setPlacementArg(I, 1310 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV)); 1311 1312 CGF.initFullExprCleanup(); 1313 } 1314 1315 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 1316 // The element type being allocated. 1317 QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 1318 1319 // 1. Build a call to the allocation function. 1320 FunctionDecl *allocator = E->getOperatorNew(); 1321 1322 // If there is a brace-initializer, cannot allocate fewer elements than inits. 1323 unsigned minElements = 0; 1324 if (E->isArray() && E->hasInitializer()) { 1325 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer())) 1326 minElements = ILE->getNumInits(); 1327 } 1328 1329 llvm::Value *numElements = nullptr; 1330 llvm::Value *allocSizeWithoutCookie = nullptr; 1331 llvm::Value *allocSize = 1332 EmitCXXNewAllocSize(*this, E, minElements, numElements, 1333 allocSizeWithoutCookie); 1334 1335 // Emit the allocation call. If the allocator is a global placement 1336 // operator, just "inline" it directly. 1337 Address allocation = Address::invalid(); 1338 CallArgList allocatorArgs; 1339 if (allocator->isReservedGlobalPlacementOperator()) { 1340 assert(E->getNumPlacementArgs() == 1); 1341 const Expr *arg = *E->placement_arguments().begin(); 1342 1343 AlignmentSource alignSource; 1344 allocation = EmitPointerWithAlignment(arg, &alignSource); 1345 1346 // The pointer expression will, in many cases, be an opaque void*. 1347 // In these cases, discard the computed alignment and use the 1348 // formal alignment of the allocated type. 1349 if (alignSource != AlignmentSource::Decl) { 1350 allocation = Address(allocation.getPointer(), 1351 getContext().getTypeAlignInChars(allocType)); 1352 } 1353 1354 // Set up allocatorArgs for the call to operator delete if it's not 1355 // the reserved global operator. 1356 if (E->getOperatorDelete() && 1357 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1358 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType()); 1359 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType()); 1360 } 1361 1362 } else { 1363 const FunctionProtoType *allocatorType = 1364 allocator->getType()->castAs<FunctionProtoType>(); 1365 1366 // The allocation size is the first argument. 1367 QualType sizeType = getContext().getSizeType(); 1368 allocatorArgs.add(RValue::get(allocSize), sizeType); 1369 1370 // We start at 1 here because the first argument (the allocation size) 1371 // has already been emitted. 1372 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(), 1373 /* CalleeDecl */ nullptr, 1374 /*ParamsToSkip*/ 1); 1375 1376 RValue RV = 1377 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs); 1378 1379 // For now, only assume that the allocation function returns 1380 // something satisfactorily aligned for the element type, plus 1381 // the cookie if we have one. 1382 CharUnits allocationAlign = 1383 getContext().getTypeAlignInChars(allocType); 1384 if (allocSize != allocSizeWithoutCookie) { 1385 CharUnits cookieAlign = getSizeAlign(); // FIXME? 1386 allocationAlign = std::max(allocationAlign, cookieAlign); 1387 } 1388 1389 allocation = Address(RV.getScalarVal(), allocationAlign); 1390 } 1391 1392 // Emit a null check on the allocation result if the allocation 1393 // function is allowed to return null (because it has a non-throwing 1394 // exception spec or is the reserved placement new) and we have an 1395 // interesting initializer. 1396 bool nullCheck = E->shouldNullCheckAllocation(getContext()) && 1397 (!allocType.isPODType(getContext()) || E->hasInitializer()); 1398 1399 llvm::BasicBlock *nullCheckBB = nullptr; 1400 llvm::BasicBlock *contBB = nullptr; 1401 1402 // The null-check means that the initializer is conditionally 1403 // evaluated. 1404 ConditionalEvaluation conditional(*this); 1405 1406 if (nullCheck) { 1407 conditional.begin(*this); 1408 1409 nullCheckBB = Builder.GetInsertBlock(); 1410 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 1411 contBB = createBasicBlock("new.cont"); 1412 1413 llvm::Value *isNull = 1414 Builder.CreateIsNull(allocation.getPointer(), "new.isnull"); 1415 Builder.CreateCondBr(isNull, contBB, notNullBB); 1416 EmitBlock(notNullBB); 1417 } 1418 1419 // If there's an operator delete, enter a cleanup to call it if an 1420 // exception is thrown. 1421 EHScopeStack::stable_iterator operatorDeleteCleanup; 1422 llvm::Instruction *cleanupDominator = nullptr; 1423 if (E->getOperatorDelete() && 1424 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 1425 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs); 1426 operatorDeleteCleanup = EHStack.stable_begin(); 1427 cleanupDominator = Builder.CreateUnreachable(); 1428 } 1429 1430 assert((allocSize == allocSizeWithoutCookie) == 1431 CalculateCookiePadding(*this, E).isZero()); 1432 if (allocSize != allocSizeWithoutCookie) { 1433 assert(E->isArray()); 1434 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 1435 numElements, 1436 E, allocType); 1437 } 1438 1439 llvm::Type *elementTy = ConvertTypeForMem(allocType); 1440 Address result = Builder.CreateElementBitCast(allocation, elementTy); 1441 1442 // Passing pointer through invariant.group.barrier to avoid propagation of 1443 // vptrs information which may be included in previous type. 1444 if (CGM.getCodeGenOpts().StrictVTablePointers && 1445 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1446 allocator->isReservedGlobalPlacementOperator()) 1447 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()), 1448 result.getAlignment()); 1449 1450 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements, 1451 allocSizeWithoutCookie); 1452 if (E->isArray()) { 1453 // NewPtr is a pointer to the base element type. If we're 1454 // allocating an array of arrays, we'll need to cast back to the 1455 // array pointer type. 1456 llvm::Type *resultType = ConvertTypeForMem(E->getType()); 1457 if (result.getType() != resultType) 1458 result = Builder.CreateBitCast(result, resultType); 1459 } 1460 1461 // Deactivate the 'operator delete' cleanup if we finished 1462 // initialization. 1463 if (operatorDeleteCleanup.isValid()) { 1464 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 1465 cleanupDominator->eraseFromParent(); 1466 } 1467 1468 llvm::Value *resultPtr = result.getPointer(); 1469 if (nullCheck) { 1470 conditional.end(*this); 1471 1472 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 1473 EmitBlock(contBB); 1474 1475 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2); 1476 PHI->addIncoming(resultPtr, notNullBB); 1477 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()), 1478 nullCheckBB); 1479 1480 resultPtr = PHI; 1481 } 1482 1483 return resultPtr; 1484 } 1485 1486 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 1487 llvm::Value *Ptr, 1488 QualType DeleteTy) { 1489 assert(DeleteFD->getOverloadedOperator() == OO_Delete); 1490 1491 const FunctionProtoType *DeleteFTy = 1492 DeleteFD->getType()->getAs<FunctionProtoType>(); 1493 1494 CallArgList DeleteArgs; 1495 1496 // Check if we need to pass the size to the delete operator. 1497 llvm::Value *Size = nullptr; 1498 QualType SizeTy; 1499 if (DeleteFTy->getNumParams() == 2) { 1500 SizeTy = DeleteFTy->getParamType(1); 1501 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 1502 Size = llvm::ConstantInt::get(ConvertType(SizeTy), 1503 DeleteTypeSize.getQuantity()); 1504 } 1505 1506 QualType ArgTy = DeleteFTy->getParamType(0); 1507 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 1508 DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 1509 1510 if (Size) 1511 DeleteArgs.add(RValue::get(Size), SizeTy); 1512 1513 // Emit the call to delete. 1514 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs); 1515 } 1516 1517 namespace { 1518 /// Calls the given 'operator delete' on a single object. 1519 struct CallObjectDelete final : EHScopeStack::Cleanup { 1520 llvm::Value *Ptr; 1521 const FunctionDecl *OperatorDelete; 1522 QualType ElementType; 1523 1524 CallObjectDelete(llvm::Value *Ptr, 1525 const FunctionDecl *OperatorDelete, 1526 QualType ElementType) 1527 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 1528 1529 void Emit(CodeGenFunction &CGF, Flags flags) override { 1530 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 1531 } 1532 }; 1533 } 1534 1535 void 1536 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete, 1537 llvm::Value *CompletePtr, 1538 QualType ElementType) { 1539 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr, 1540 OperatorDelete, ElementType); 1541 } 1542 1543 /// Emit the code for deleting a single object. 1544 static void EmitObjectDelete(CodeGenFunction &CGF, 1545 const CXXDeleteExpr *DE, 1546 Address Ptr, 1547 QualType ElementType) { 1548 // Find the destructor for the type, if applicable. If the 1549 // destructor is virtual, we'll just emit the vcall and return. 1550 const CXXDestructorDecl *Dtor = nullptr; 1551 if (const RecordType *RT = ElementType->getAs<RecordType>()) { 1552 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 1553 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 1554 Dtor = RD->getDestructor(); 1555 1556 if (Dtor->isVirtual()) { 1557 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType, 1558 Dtor); 1559 return; 1560 } 1561 } 1562 } 1563 1564 // Make sure that we call delete even if the dtor throws. 1565 // This doesn't have to a conditional cleanup because we're going 1566 // to pop it off in a second. 1567 const FunctionDecl *OperatorDelete = DE->getOperatorDelete(); 1568 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 1569 Ptr.getPointer(), 1570 OperatorDelete, ElementType); 1571 1572 if (Dtor) 1573 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 1574 /*ForVirtualBase=*/false, 1575 /*Delegating=*/false, 1576 Ptr); 1577 else if (auto Lifetime = ElementType.getObjCLifetime()) { 1578 switch (Lifetime) { 1579 case Qualifiers::OCL_None: 1580 case Qualifiers::OCL_ExplicitNone: 1581 case Qualifiers::OCL_Autoreleasing: 1582 break; 1583 1584 case Qualifiers::OCL_Strong: 1585 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime); 1586 break; 1587 1588 case Qualifiers::OCL_Weak: 1589 CGF.EmitARCDestroyWeak(Ptr); 1590 break; 1591 } 1592 } 1593 1594 CGF.PopCleanupBlock(); 1595 } 1596 1597 namespace { 1598 /// Calls the given 'operator delete' on an array of objects. 1599 struct CallArrayDelete final : EHScopeStack::Cleanup { 1600 llvm::Value *Ptr; 1601 const FunctionDecl *OperatorDelete; 1602 llvm::Value *NumElements; 1603 QualType ElementType; 1604 CharUnits CookieSize; 1605 1606 CallArrayDelete(llvm::Value *Ptr, 1607 const FunctionDecl *OperatorDelete, 1608 llvm::Value *NumElements, 1609 QualType ElementType, 1610 CharUnits CookieSize) 1611 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 1612 ElementType(ElementType), CookieSize(CookieSize) {} 1613 1614 void Emit(CodeGenFunction &CGF, Flags flags) override { 1615 const FunctionProtoType *DeleteFTy = 1616 OperatorDelete->getType()->getAs<FunctionProtoType>(); 1617 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2); 1618 1619 CallArgList Args; 1620 1621 // Pass the pointer as the first argument. 1622 QualType VoidPtrTy = DeleteFTy->getParamType(0); 1623 llvm::Value *DeletePtr 1624 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy)); 1625 Args.add(RValue::get(DeletePtr), VoidPtrTy); 1626 1627 // Pass the original requested size as the second argument. 1628 if (DeleteFTy->getNumParams() == 2) { 1629 QualType size_t = DeleteFTy->getParamType(1); 1630 llvm::IntegerType *SizeTy 1631 = cast<llvm::IntegerType>(CGF.ConvertType(size_t)); 1632 1633 CharUnits ElementTypeSize = 1634 CGF.CGM.getContext().getTypeSizeInChars(ElementType); 1635 1636 // The size of an element, multiplied by the number of elements. 1637 llvm::Value *Size 1638 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity()); 1639 if (NumElements) 1640 Size = CGF.Builder.CreateMul(Size, NumElements); 1641 1642 // Plus the size of the cookie if applicable. 1643 if (!CookieSize.isZero()) { 1644 llvm::Value *CookieSizeV 1645 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()); 1646 Size = CGF.Builder.CreateAdd(Size, CookieSizeV); 1647 } 1648 1649 Args.add(RValue::get(Size), size_t); 1650 } 1651 1652 // Emit the call to delete. 1653 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args); 1654 } 1655 }; 1656 } 1657 1658 /// Emit the code for deleting an array of objects. 1659 static void EmitArrayDelete(CodeGenFunction &CGF, 1660 const CXXDeleteExpr *E, 1661 Address deletedPtr, 1662 QualType elementType) { 1663 llvm::Value *numElements = nullptr; 1664 llvm::Value *allocatedPtr = nullptr; 1665 CharUnits cookieSize; 1666 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 1667 numElements, allocatedPtr, cookieSize); 1668 1669 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 1670 1671 // Make sure that we call delete even if one of the dtors throws. 1672 const FunctionDecl *operatorDelete = E->getOperatorDelete(); 1673 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 1674 allocatedPtr, operatorDelete, 1675 numElements, elementType, 1676 cookieSize); 1677 1678 // Destroy the elements. 1679 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 1680 assert(numElements && "no element count for a type with a destructor!"); 1681 1682 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType); 1683 CharUnits elementAlign = 1684 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize); 1685 1686 llvm::Value *arrayBegin = deletedPtr.getPointer(); 1687 llvm::Value *arrayEnd = 1688 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end"); 1689 1690 // Note that it is legal to allocate a zero-length array, and we 1691 // can never fold the check away because the length should always 1692 // come from a cookie. 1693 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign, 1694 CGF.getDestroyer(dtorKind), 1695 /*checkZeroLength*/ true, 1696 CGF.needsEHCleanup(dtorKind)); 1697 } 1698 1699 // Pop the cleanup block. 1700 CGF.PopCleanupBlock(); 1701 } 1702 1703 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 1704 const Expr *Arg = E->getArgument(); 1705 Address Ptr = EmitPointerWithAlignment(Arg); 1706 1707 // Null check the pointer. 1708 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 1709 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 1710 1711 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull"); 1712 1713 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 1714 EmitBlock(DeleteNotNull); 1715 1716 // We might be deleting a pointer to array. If so, GEP down to the 1717 // first non-array element. 1718 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 1719 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType(); 1720 if (DeleteTy->isConstantArrayType()) { 1721 llvm::Value *Zero = Builder.getInt32(0); 1722 SmallVector<llvm::Value*,8> GEP; 1723 1724 GEP.push_back(Zero); // point at the outermost array 1725 1726 // For each layer of array type we're pointing at: 1727 while (const ConstantArrayType *Arr 1728 = getContext().getAsConstantArrayType(DeleteTy)) { 1729 // 1. Unpeel the array type. 1730 DeleteTy = Arr->getElementType(); 1731 1732 // 2. GEP to the first element of the array. 1733 GEP.push_back(Zero); 1734 } 1735 1736 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"), 1737 Ptr.getAlignment()); 1738 } 1739 1740 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType()); 1741 1742 if (E->isArrayForm()) { 1743 EmitArrayDelete(*this, E, Ptr, DeleteTy); 1744 } else { 1745 EmitObjectDelete(*this, E, Ptr, DeleteTy); 1746 } 1747 1748 EmitBlock(DeleteEnd); 1749 } 1750 1751 static bool isGLValueFromPointerDeref(const Expr *E) { 1752 E = E->IgnoreParens(); 1753 1754 if (const auto *CE = dyn_cast<CastExpr>(E)) { 1755 if (!CE->getSubExpr()->isGLValue()) 1756 return false; 1757 return isGLValueFromPointerDeref(CE->getSubExpr()); 1758 } 1759 1760 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) 1761 return isGLValueFromPointerDeref(OVE->getSourceExpr()); 1762 1763 if (const auto *BO = dyn_cast<BinaryOperator>(E)) 1764 if (BO->getOpcode() == BO_Comma) 1765 return isGLValueFromPointerDeref(BO->getRHS()); 1766 1767 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E)) 1768 return isGLValueFromPointerDeref(ACO->getTrueExpr()) || 1769 isGLValueFromPointerDeref(ACO->getFalseExpr()); 1770 1771 // C++11 [expr.sub]p1: 1772 // The expression E1[E2] is identical (by definition) to *((E1)+(E2)) 1773 if (isa<ArraySubscriptExpr>(E)) 1774 return true; 1775 1776 if (const auto *UO = dyn_cast<UnaryOperator>(E)) 1777 if (UO->getOpcode() == UO_Deref) 1778 return true; 1779 1780 return false; 1781 } 1782 1783 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E, 1784 llvm::Type *StdTypeInfoPtrTy) { 1785 // Get the vtable pointer. 1786 Address ThisPtr = CGF.EmitLValue(E).getAddress(); 1787 1788 // C++ [expr.typeid]p2: 1789 // If the glvalue expression is obtained by applying the unary * operator to 1790 // a pointer and the pointer is a null pointer value, the typeid expression 1791 // throws the std::bad_typeid exception. 1792 // 1793 // However, this paragraph's intent is not clear. We choose a very generous 1794 // interpretation which implores us to consider comma operators, conditional 1795 // operators, parentheses and other such constructs. 1796 QualType SrcRecordTy = E->getType(); 1797 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked( 1798 isGLValueFromPointerDeref(E), SrcRecordTy)) { 1799 llvm::BasicBlock *BadTypeidBlock = 1800 CGF.createBasicBlock("typeid.bad_typeid"); 1801 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end"); 1802 1803 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer()); 1804 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 1805 1806 CGF.EmitBlock(BadTypeidBlock); 1807 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF); 1808 CGF.EmitBlock(EndBlock); 1809 } 1810 1811 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr, 1812 StdTypeInfoPtrTy); 1813 } 1814 1815 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 1816 llvm::Type *StdTypeInfoPtrTy = 1817 ConvertType(E->getType())->getPointerTo(); 1818 1819 if (E->isTypeOperand()) { 1820 llvm::Constant *TypeInfo = 1821 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext())); 1822 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 1823 } 1824 1825 // C++ [expr.typeid]p2: 1826 // When typeid is applied to a glvalue expression whose type is a 1827 // polymorphic class type, the result refers to a std::type_info object 1828 // representing the type of the most derived object (that is, the dynamic 1829 // type) to which the glvalue refers. 1830 if (E->isPotentiallyEvaluated()) 1831 return EmitTypeidFromVTable(*this, E->getExprOperand(), 1832 StdTypeInfoPtrTy); 1833 1834 QualType OperandTy = E->getExprOperand()->getType(); 1835 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 1836 StdTypeInfoPtrTy); 1837 } 1838 1839 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 1840 QualType DestTy) { 1841 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 1842 if (DestTy->isPointerType()) 1843 return llvm::Constant::getNullValue(DestLTy); 1844 1845 /// C++ [expr.dynamic.cast]p9: 1846 /// A failed cast to reference type throws std::bad_cast 1847 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF)) 1848 return nullptr; 1849 1850 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 1851 return llvm::UndefValue::get(DestLTy); 1852 } 1853 1854 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr, 1855 const CXXDynamicCastExpr *DCE) { 1856 CGM.EmitExplicitCastExprType(DCE, this); 1857 QualType DestTy = DCE->getTypeAsWritten(); 1858 1859 if (DCE->isAlwaysNull()) 1860 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy)) 1861 return T; 1862 1863 QualType SrcTy = DCE->getSubExpr()->getType(); 1864 1865 // C++ [expr.dynamic.cast]p7: 1866 // If T is "pointer to cv void," then the result is a pointer to the most 1867 // derived object pointed to by v. 1868 const PointerType *DestPTy = DestTy->getAs<PointerType>(); 1869 1870 bool isDynamicCastToVoid; 1871 QualType SrcRecordTy; 1872 QualType DestRecordTy; 1873 if (DestPTy) { 1874 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType(); 1875 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 1876 DestRecordTy = DestPTy->getPointeeType(); 1877 } else { 1878 isDynamicCastToVoid = false; 1879 SrcRecordTy = SrcTy; 1880 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 1881 } 1882 1883 assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 1884 1885 // C++ [expr.dynamic.cast]p4: 1886 // If the value of v is a null pointer value in the pointer case, the result 1887 // is the null pointer value of type T. 1888 bool ShouldNullCheckSrcValue = 1889 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(), 1890 SrcRecordTy); 1891 1892 llvm::BasicBlock *CastNull = nullptr; 1893 llvm::BasicBlock *CastNotNull = nullptr; 1894 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 1895 1896 if (ShouldNullCheckSrcValue) { 1897 CastNull = createBasicBlock("dynamic_cast.null"); 1898 CastNotNull = createBasicBlock("dynamic_cast.notnull"); 1899 1900 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer()); 1901 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 1902 EmitBlock(CastNotNull); 1903 } 1904 1905 llvm::Value *Value; 1906 if (isDynamicCastToVoid) { 1907 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy, 1908 DestTy); 1909 } else { 1910 assert(DestRecordTy->isRecordType() && 1911 "destination type must be a record type!"); 1912 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy, 1913 DestTy, DestRecordTy, CastEnd); 1914 CastNotNull = Builder.GetInsertBlock(); 1915 } 1916 1917 if (ShouldNullCheckSrcValue) { 1918 EmitBranch(CastEnd); 1919 1920 EmitBlock(CastNull); 1921 EmitBranch(CastEnd); 1922 } 1923 1924 EmitBlock(CastEnd); 1925 1926 if (ShouldNullCheckSrcValue) { 1927 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 1928 PHI->addIncoming(Value, CastNotNull); 1929 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 1930 1931 Value = PHI; 1932 } 1933 1934 return Value; 1935 } 1936 1937 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) { 1938 RunCleanupsScope Scope(*this); 1939 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType()); 1940 1941 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin(); 1942 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(), 1943 e = E->capture_init_end(); 1944 i != e; ++i, ++CurField) { 1945 // Emit initialization 1946 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField); 1947 if (CurField->hasCapturedVLAType()) { 1948 auto VAT = CurField->getCapturedVLAType(); 1949 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV); 1950 } else { 1951 ArrayRef<VarDecl *> ArrayIndexes; 1952 if (CurField->getType()->isArrayType()) 1953 ArrayIndexes = E->getCaptureInitIndexVars(i); 1954 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes); 1955 } 1956 } 1957 } 1958