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