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