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