clang API Documentation
00001 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This contains code dealing with code generation of C++ expressions 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/Frontend/CodeGenOptions.h" 00015 #include "CodeGenFunction.h" 00016 #include "CGCUDARuntime.h" 00017 #include "CGCXXABI.h" 00018 #include "CGObjCRuntime.h" 00019 #include "CGDebugInfo.h" 00020 #include "llvm/Intrinsics.h" 00021 #include "llvm/Support/CallSite.h" 00022 00023 using namespace clang; 00024 using namespace CodeGen; 00025 00026 RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD, 00027 llvm::Value *Callee, 00028 ReturnValueSlot ReturnValue, 00029 llvm::Value *This, 00030 llvm::Value *VTT, 00031 CallExpr::const_arg_iterator ArgBeg, 00032 CallExpr::const_arg_iterator ArgEnd) { 00033 assert(MD->isInstance() && 00034 "Trying to emit a member call expr on a static method!"); 00035 00036 CallArgList Args; 00037 00038 // Push the this ptr. 00039 Args.add(RValue::get(This), MD->getThisType(getContext())); 00040 00041 // If there is a VTT parameter, emit it. 00042 if (VTT) { 00043 QualType T = getContext().getPointerType(getContext().VoidPtrTy); 00044 Args.add(RValue::get(VTT), T); 00045 } 00046 00047 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 00048 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size()); 00049 00050 // And the rest of the call args. 00051 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd); 00052 00053 return EmitCall(CGM.getTypes().arrangeFunctionCall(FPT->getResultType(), Args, 00054 FPT->getExtInfo(), 00055 required), 00056 Callee, ReturnValue, Args, MD); 00057 } 00058 00059 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) { 00060 const Expr *E = Base; 00061 00062 while (true) { 00063 E = E->IgnoreParens(); 00064 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 00065 if (CE->getCastKind() == CK_DerivedToBase || 00066 CE->getCastKind() == CK_UncheckedDerivedToBase || 00067 CE->getCastKind() == CK_NoOp) { 00068 E = CE->getSubExpr(); 00069 continue; 00070 } 00071 } 00072 00073 break; 00074 } 00075 00076 QualType DerivedType = E->getType(); 00077 if (const PointerType *PTy = DerivedType->getAs<PointerType>()) 00078 DerivedType = PTy->getPointeeType(); 00079 00080 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl()); 00081 } 00082 00083 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do 00084 // quite what we want. 00085 static const Expr *skipNoOpCastsAndParens(const Expr *E) { 00086 while (true) { 00087 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 00088 E = PE->getSubExpr(); 00089 continue; 00090 } 00091 00092 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 00093 if (CE->getCastKind() == CK_NoOp) { 00094 E = CE->getSubExpr(); 00095 continue; 00096 } 00097 } 00098 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 00099 if (UO->getOpcode() == UO_Extension) { 00100 E = UO->getSubExpr(); 00101 continue; 00102 } 00103 } 00104 return E; 00105 } 00106 } 00107 00108 /// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 00109 /// expr can be devirtualized. 00110 static bool canDevirtualizeMemberFunctionCalls(ASTContext &Context, 00111 const Expr *Base, 00112 const CXXMethodDecl *MD) { 00113 00114 // When building with -fapple-kext, all calls must go through the vtable since 00115 // the kernel linker can do runtime patching of vtables. 00116 if (Context.getLangOpts().AppleKext) 00117 return false; 00118 00119 // If the most derived class is marked final, we know that no subclass can 00120 // override this member function and so we can devirtualize it. For example: 00121 // 00122 // struct A { virtual void f(); } 00123 // struct B final : A { }; 00124 // 00125 // void f(B *b) { 00126 // b->f(); 00127 // } 00128 // 00129 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base); 00130 if (MostDerivedClassDecl->hasAttr<FinalAttr>()) 00131 return true; 00132 00133 // If the member function is marked 'final', we know that it can't be 00134 // overridden and can therefore devirtualize it. 00135 if (MD->hasAttr<FinalAttr>()) 00136 return true; 00137 00138 // Similarly, if the class itself is marked 'final' it can't be overridden 00139 // and we can therefore devirtualize the member function call. 00140 if (MD->getParent()->hasAttr<FinalAttr>()) 00141 return true; 00142 00143 Base = skipNoOpCastsAndParens(Base); 00144 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 00145 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 00146 // This is a record decl. We know the type and can devirtualize it. 00147 return VD->getType()->isRecordType(); 00148 } 00149 00150 return false; 00151 } 00152 00153 // We can always devirtualize calls on temporary object expressions. 00154 if (isa<CXXConstructExpr>(Base)) 00155 return true; 00156 00157 // And calls on bound temporaries. 00158 if (isa<CXXBindTemporaryExpr>(Base)) 00159 return true; 00160 00161 // Check if this is a call expr that returns a record type. 00162 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 00163 return CE->getCallReturnType()->isRecordType(); 00164 00165 // We can't devirtualize the call. 00166 return false; 00167 } 00168 00169 // Note: This function also emit constructor calls to support a MSVC 00170 // extensions allowing explicit constructor function call. 00171 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE, 00172 ReturnValueSlot ReturnValue) { 00173 const Expr *callee = CE->getCallee()->IgnoreParens(); 00174 00175 if (isa<BinaryOperator>(callee)) 00176 return EmitCXXMemberPointerCallExpr(CE, ReturnValue); 00177 00178 const MemberExpr *ME = cast<MemberExpr>(callee); 00179 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 00180 00181 CGDebugInfo *DI = getDebugInfo(); 00182 if (DI && CGM.getCodeGenOpts().DebugInfo == CodeGenOptions::LimitedDebugInfo 00183 && !isa<CallExpr>(ME->getBase())) { 00184 QualType PQTy = ME->getBase()->IgnoreParenImpCasts()->getType(); 00185 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy)) { 00186 DI->getOrCreateRecordType(PTy->getPointeeType(), 00187 MD->getParent()->getLocation()); 00188 } 00189 } 00190 00191 if (MD->isStatic()) { 00192 // The method is static, emit it as we would a regular call. 00193 llvm::Value *Callee = CGM.GetAddrOfFunction(MD); 00194 return EmitCall(getContext().getPointerType(MD->getType()), Callee, 00195 ReturnValue, CE->arg_begin(), CE->arg_end()); 00196 } 00197 00198 // Compute the object pointer. 00199 llvm::Value *This; 00200 if (ME->isArrow()) 00201 This = EmitScalarExpr(ME->getBase()); 00202 else 00203 This = EmitLValue(ME->getBase()).getAddress(); 00204 00205 if (MD->isTrivial()) { 00206 if (isa<CXXDestructorDecl>(MD)) return RValue::get(0); 00207 if (isa<CXXConstructorDecl>(MD) && 00208 cast<CXXConstructorDecl>(MD)->isDefaultConstructor()) 00209 return RValue::get(0); 00210 00211 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) { 00212 // We don't like to generate the trivial copy/move assignment operator 00213 // when it isn't necessary; just produce the proper effect here. 00214 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress(); 00215 EmitAggregateCopy(This, RHS, CE->getType()); 00216 return RValue::get(This); 00217 } 00218 00219 if (isa<CXXConstructorDecl>(MD) && 00220 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) { 00221 // Trivial move and copy ctor are the same. 00222 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress(); 00223 EmitSynthesizedCXXCopyCtorCall(cast<CXXConstructorDecl>(MD), This, RHS, 00224 CE->arg_begin(), CE->arg_end()); 00225 return RValue::get(This); 00226 } 00227 llvm_unreachable("unknown trivial member function"); 00228 } 00229 00230 // Compute the function type we're calling. 00231 const CGFunctionInfo *FInfo = 0; 00232 if (isa<CXXDestructorDecl>(MD)) 00233 FInfo = &CGM.getTypes().arrangeCXXDestructor(cast<CXXDestructorDecl>(MD), 00234 Dtor_Complete); 00235 else if (isa<CXXConstructorDecl>(MD)) 00236 FInfo = &CGM.getTypes().arrangeCXXConstructorDeclaration( 00237 cast<CXXConstructorDecl>(MD), 00238 Ctor_Complete); 00239 else 00240 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(MD); 00241 00242 llvm::Type *Ty = CGM.getTypes().GetFunctionType(*FInfo); 00243 00244 // C++ [class.virtual]p12: 00245 // Explicit qualification with the scope operator (5.1) suppresses the 00246 // virtual call mechanism. 00247 // 00248 // We also don't emit a virtual call if the base expression has a record type 00249 // because then we know what the type is. 00250 bool UseVirtualCall; 00251 UseVirtualCall = MD->isVirtual() && !ME->hasQualifier() 00252 && !canDevirtualizeMemberFunctionCalls(getContext(), 00253 ME->getBase(), MD); 00254 llvm::Value *Callee; 00255 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) { 00256 if (UseVirtualCall) { 00257 Callee = BuildVirtualCall(Dtor, Dtor_Complete, This, Ty); 00258 } else { 00259 if (getContext().getLangOpts().AppleKext && 00260 MD->isVirtual() && 00261 ME->hasQualifier()) 00262 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty); 00263 else 00264 Callee = CGM.GetAddrOfFunction(GlobalDecl(Dtor, Dtor_Complete), Ty); 00265 } 00266 } else if (const CXXConstructorDecl *Ctor = 00267 dyn_cast<CXXConstructorDecl>(MD)) { 00268 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty); 00269 } else if (UseVirtualCall) { 00270 Callee = BuildVirtualCall(MD, This, Ty); 00271 } else { 00272 if (getContext().getLangOpts().AppleKext && 00273 MD->isVirtual() && 00274 ME->hasQualifier()) 00275 Callee = BuildAppleKextVirtualCall(MD, ME->getQualifier(), Ty); 00276 else 00277 Callee = CGM.GetAddrOfFunction(MD, Ty); 00278 } 00279 00280 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0, 00281 CE->arg_begin(), CE->arg_end()); 00282 } 00283 00284 RValue 00285 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E, 00286 ReturnValueSlot ReturnValue) { 00287 const BinaryOperator *BO = 00288 cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 00289 const Expr *BaseExpr = BO->getLHS(); 00290 const Expr *MemFnExpr = BO->getRHS(); 00291 00292 const MemberPointerType *MPT = 00293 MemFnExpr->getType()->castAs<MemberPointerType>(); 00294 00295 const FunctionProtoType *FPT = 00296 MPT->getPointeeType()->castAs<FunctionProtoType>(); 00297 const CXXRecordDecl *RD = 00298 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 00299 00300 // Get the member function pointer. 00301 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr); 00302 00303 // Emit the 'this' pointer. 00304 llvm::Value *This; 00305 00306 if (BO->getOpcode() == BO_PtrMemI) 00307 This = EmitScalarExpr(BaseExpr); 00308 else 00309 This = EmitLValue(BaseExpr).getAddress(); 00310 00311 // Ask the ABI to load the callee. Note that This is modified. 00312 llvm::Value *Callee = 00313 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, This, MemFnPtr, MPT); 00314 00315 CallArgList Args; 00316 00317 QualType ThisType = 00318 getContext().getPointerType(getContext().getTagDeclType(RD)); 00319 00320 // Push the this ptr. 00321 Args.add(RValue::get(This), ThisType); 00322 00323 // And the rest of the call args 00324 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end()); 00325 return EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee, 00326 ReturnValue, Args); 00327 } 00328 00329 RValue 00330 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 00331 const CXXMethodDecl *MD, 00332 ReturnValueSlot ReturnValue) { 00333 assert(MD->isInstance() && 00334 "Trying to emit a member call expr on a static method!"); 00335 LValue LV = EmitLValue(E->getArg(0)); 00336 llvm::Value *This = LV.getAddress(); 00337 00338 if ((MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) && 00339 MD->isTrivial()) { 00340 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress(); 00341 QualType Ty = E->getType(); 00342 EmitAggregateCopy(This, Src, Ty); 00343 return RValue::get(This); 00344 } 00345 00346 llvm::Value *Callee = EmitCXXOperatorMemberCallee(E, MD, This); 00347 return EmitCXXMemberCall(MD, Callee, ReturnValue, This, /*VTT=*/0, 00348 E->arg_begin() + 1, E->arg_end()); 00349 } 00350 00351 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E, 00352 ReturnValueSlot ReturnValue) { 00353 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue); 00354 } 00355 00356 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF, 00357 llvm::Value *DestPtr, 00358 const CXXRecordDecl *Base) { 00359 if (Base->isEmpty()) 00360 return; 00361 00362 DestPtr = CGF.EmitCastToVoidPtr(DestPtr); 00363 00364 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base); 00365 CharUnits Size = Layout.getNonVirtualSize(); 00366 CharUnits Align = Layout.getNonVirtualAlign(); 00367 00368 llvm::Value *SizeVal = CGF.CGM.getSize(Size); 00369 00370 // If the type contains a pointer to data member we can't memset it to zero. 00371 // Instead, create a null constant and copy it to the destination. 00372 // TODO: there are other patterns besides zero that we can usefully memset, 00373 // like -1, which happens to be the pattern used by member-pointers. 00374 // TODO: isZeroInitializable can be over-conservative in the case where a 00375 // virtual base contains a member pointer. 00376 if (!CGF.CGM.getTypes().isZeroInitializable(Base)) { 00377 llvm::Constant *NullConstant = CGF.CGM.EmitNullConstantForBase(Base); 00378 00379 llvm::GlobalVariable *NullVariable = 00380 new llvm::GlobalVariable(CGF.CGM.getModule(), NullConstant->getType(), 00381 /*isConstant=*/true, 00382 llvm::GlobalVariable::PrivateLinkage, 00383 NullConstant, Twine()); 00384 NullVariable->setAlignment(Align.getQuantity()); 00385 llvm::Value *SrcPtr = CGF.EmitCastToVoidPtr(NullVariable); 00386 00387 // Get and call the appropriate llvm.memcpy overload. 00388 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, SizeVal, Align.getQuantity()); 00389 return; 00390 } 00391 00392 // Otherwise, just memset the whole thing to zero. This is legal 00393 // because in LLVM, all default initializers (other than the ones we just 00394 // handled above) are guaranteed to have a bit pattern of all zeros. 00395 CGF.Builder.CreateMemSet(DestPtr, CGF.Builder.getInt8(0), SizeVal, 00396 Align.getQuantity()); 00397 } 00398 00399 void 00400 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E, 00401 AggValueSlot Dest) { 00402 assert(!Dest.isIgnored() && "Must have a destination!"); 00403 const CXXConstructorDecl *CD = E->getConstructor(); 00404 00405 // If we require zero initialization before (or instead of) calling the 00406 // constructor, as can be the case with a non-user-provided default 00407 // constructor, emit the zero initialization now, unless destination is 00408 // already zeroed. 00409 if (E->requiresZeroInitialization() && !Dest.isZeroed()) { 00410 switch (E->getConstructionKind()) { 00411 case CXXConstructExpr::CK_Delegating: 00412 assert(0 && "Delegating constructor should not need zeroing"); 00413 case CXXConstructExpr::CK_Complete: 00414 EmitNullInitialization(Dest.getAddr(), E->getType()); 00415 break; 00416 case CXXConstructExpr::CK_VirtualBase: 00417 case CXXConstructExpr::CK_NonVirtualBase: 00418 EmitNullBaseClassInitialization(*this, Dest.getAddr(), CD->getParent()); 00419 break; 00420 } 00421 } 00422 00423 // If this is a call to a trivial default constructor, do nothing. 00424 if (CD->isTrivial() && CD->isDefaultConstructor()) 00425 return; 00426 00427 // Elide the constructor if we're constructing from a temporary. 00428 // The temporary check is required because Sema sets this on NRVO 00429 // returns. 00430 if (getContext().getLangOpts().ElideConstructors && E->isElidable()) { 00431 assert(getContext().hasSameUnqualifiedType(E->getType(), 00432 E->getArg(0)->getType())); 00433 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) { 00434 EmitAggExpr(E->getArg(0), Dest); 00435 return; 00436 } 00437 } 00438 00439 if (const ConstantArrayType *arrayType 00440 = getContext().getAsConstantArrayType(E->getType())) { 00441 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddr(), 00442 E->arg_begin(), E->arg_end()); 00443 } else { 00444 CXXCtorType Type = Ctor_Complete; 00445 bool ForVirtualBase = false; 00446 00447 switch (E->getConstructionKind()) { 00448 case CXXConstructExpr::CK_Delegating: 00449 // We should be emitting a constructor; GlobalDecl will assert this 00450 Type = CurGD.getCtorType(); 00451 break; 00452 00453 case CXXConstructExpr::CK_Complete: 00454 Type = Ctor_Complete; 00455 break; 00456 00457 case CXXConstructExpr::CK_VirtualBase: 00458 ForVirtualBase = true; 00459 // fall-through 00460 00461 case CXXConstructExpr::CK_NonVirtualBase: 00462 Type = Ctor_Base; 00463 } 00464 00465 // Call the constructor. 00466 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Dest.getAddr(), 00467 E->arg_begin(), E->arg_end()); 00468 } 00469 } 00470 00471 void 00472 CodeGenFunction::EmitSynthesizedCXXCopyCtor(llvm::Value *Dest, 00473 llvm::Value *Src, 00474 const Expr *Exp) { 00475 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp)) 00476 Exp = E->getSubExpr(); 00477 assert(isa<CXXConstructExpr>(Exp) && 00478 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr"); 00479 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp); 00480 const CXXConstructorDecl *CD = E->getConstructor(); 00481 RunCleanupsScope Scope(*this); 00482 00483 // If we require zero initialization before (or instead of) calling the 00484 // constructor, as can be the case with a non-user-provided default 00485 // constructor, emit the zero initialization now. 00486 // FIXME. Do I still need this for a copy ctor synthesis? 00487 if (E->requiresZeroInitialization()) 00488 EmitNullInitialization(Dest, E->getType()); 00489 00490 assert(!getContext().getAsConstantArrayType(E->getType()) 00491 && "EmitSynthesizedCXXCopyCtor - Copied-in Array"); 00492 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, 00493 E->arg_begin(), E->arg_end()); 00494 } 00495 00496 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF, 00497 const CXXNewExpr *E) { 00498 if (!E->isArray()) 00499 return CharUnits::Zero(); 00500 00501 // No cookie is required if the operator new[] being used is the 00502 // reserved placement operator new[]. 00503 if (E->getOperatorNew()->isReservedGlobalPlacementOperator()) 00504 return CharUnits::Zero(); 00505 00506 return CGF.CGM.getCXXABI().GetArrayCookieSize(E); 00507 } 00508 00509 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF, 00510 const CXXNewExpr *e, 00511 unsigned minElements, 00512 llvm::Value *&numElements, 00513 llvm::Value *&sizeWithoutCookie) { 00514 QualType type = e->getAllocatedType(); 00515 00516 if (!e->isArray()) { 00517 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 00518 sizeWithoutCookie 00519 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity()); 00520 return sizeWithoutCookie; 00521 } 00522 00523 // The width of size_t. 00524 unsigned sizeWidth = CGF.SizeTy->getBitWidth(); 00525 00526 // Figure out the cookie size. 00527 llvm::APInt cookieSize(sizeWidth, 00528 CalculateCookiePadding(CGF, e).getQuantity()); 00529 00530 // Emit the array size expression. 00531 // We multiply the size of all dimensions for NumElements. 00532 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6. 00533 numElements = CGF.EmitScalarExpr(e->getArraySize()); 00534 assert(isa<llvm::IntegerType>(numElements->getType())); 00535 00536 // The number of elements can be have an arbitrary integer type; 00537 // essentially, we need to multiply it by a constant factor, add a 00538 // cookie size, and verify that the result is representable as a 00539 // size_t. That's just a gloss, though, and it's wrong in one 00540 // important way: if the count is negative, it's an error even if 00541 // the cookie size would bring the total size >= 0. 00542 bool isSigned 00543 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType(); 00544 llvm::IntegerType *numElementsType 00545 = cast<llvm::IntegerType>(numElements->getType()); 00546 unsigned numElementsWidth = numElementsType->getBitWidth(); 00547 00548 // Compute the constant factor. 00549 llvm::APInt arraySizeMultiplier(sizeWidth, 1); 00550 while (const ConstantArrayType *CAT 00551 = CGF.getContext().getAsConstantArrayType(type)) { 00552 type = CAT->getElementType(); 00553 arraySizeMultiplier *= CAT->getSize(); 00554 } 00555 00556 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type); 00557 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity()); 00558 typeSizeMultiplier *= arraySizeMultiplier; 00559 00560 // This will be a size_t. 00561 llvm::Value *size; 00562 00563 // If someone is doing 'new int[42]' there is no need to do a dynamic check. 00564 // Don't bloat the -O0 code. 00565 if (llvm::ConstantInt *numElementsC = 00566 dyn_cast<llvm::ConstantInt>(numElements)) { 00567 const llvm::APInt &count = numElementsC->getValue(); 00568 00569 bool hasAnyOverflow = false; 00570 00571 // If 'count' was a negative number, it's an overflow. 00572 if (isSigned && count.isNegative()) 00573 hasAnyOverflow = true; 00574 00575 // We want to do all this arithmetic in size_t. If numElements is 00576 // wider than that, check whether it's already too big, and if so, 00577 // overflow. 00578 else if (numElementsWidth > sizeWidth && 00579 numElementsWidth - sizeWidth > count.countLeadingZeros()) 00580 hasAnyOverflow = true; 00581 00582 // Okay, compute a count at the right width. 00583 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth); 00584 00585 // If there is a brace-initializer, we cannot allocate fewer elements than 00586 // there are initializers. If we do, that's treated like an overflow. 00587 if (adjustedCount.ult(minElements)) 00588 hasAnyOverflow = true; 00589 00590 // Scale numElements by that. This might overflow, but we don't 00591 // care because it only overflows if allocationSize does, too, and 00592 // if that overflows then we shouldn't use this. 00593 numElements = llvm::ConstantInt::get(CGF.SizeTy, 00594 adjustedCount * arraySizeMultiplier); 00595 00596 // Compute the size before cookie, and track whether it overflowed. 00597 bool overflow; 00598 llvm::APInt allocationSize 00599 = adjustedCount.umul_ov(typeSizeMultiplier, overflow); 00600 hasAnyOverflow |= overflow; 00601 00602 // Add in the cookie, and check whether it's overflowed. 00603 if (cookieSize != 0) { 00604 // Save the current size without a cookie. This shouldn't be 00605 // used if there was overflow. 00606 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 00607 00608 allocationSize = allocationSize.uadd_ov(cookieSize, overflow); 00609 hasAnyOverflow |= overflow; 00610 } 00611 00612 // On overflow, produce a -1 so operator new will fail. 00613 if (hasAnyOverflow) { 00614 size = llvm::Constant::getAllOnesValue(CGF.SizeTy); 00615 } else { 00616 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize); 00617 } 00618 00619 // Otherwise, we might need to use the overflow intrinsics. 00620 } else { 00621 // There are up to five conditions we need to test for: 00622 // 1) if isSigned, we need to check whether numElements is negative; 00623 // 2) if numElementsWidth > sizeWidth, we need to check whether 00624 // numElements is larger than something representable in size_t; 00625 // 3) if minElements > 0, we need to check whether numElements is smaller 00626 // than that. 00627 // 4) we need to compute 00628 // sizeWithoutCookie := numElements * typeSizeMultiplier 00629 // and check whether it overflows; and 00630 // 5) if we need a cookie, we need to compute 00631 // size := sizeWithoutCookie + cookieSize 00632 // and check whether it overflows. 00633 00634 llvm::Value *hasOverflow = 0; 00635 00636 // If numElementsWidth > sizeWidth, then one way or another, we're 00637 // going to have to do a comparison for (2), and this happens to 00638 // take care of (1), too. 00639 if (numElementsWidth > sizeWidth) { 00640 llvm::APInt threshold(numElementsWidth, 1); 00641 threshold <<= sizeWidth; 00642 00643 llvm::Value *thresholdV 00644 = llvm::ConstantInt::get(numElementsType, threshold); 00645 00646 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV); 00647 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy); 00648 00649 // Otherwise, if we're signed, we want to sext up to size_t. 00650 } else if (isSigned) { 00651 if (numElementsWidth < sizeWidth) 00652 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy); 00653 00654 // If there's a non-1 type size multiplier, then we can do the 00655 // signedness check at the same time as we do the multiply 00656 // because a negative number times anything will cause an 00657 // unsigned overflow. Otherwise, we have to do it here. But at least 00658 // in this case, we can subsume the >= minElements check. 00659 if (typeSizeMultiplier == 1) 00660 hasOverflow = CGF.Builder.CreateICmpSLT(numElements, 00661 llvm::ConstantInt::get(CGF.SizeTy, minElements)); 00662 00663 // Otherwise, zext up to size_t if necessary. 00664 } else if (numElementsWidth < sizeWidth) { 00665 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy); 00666 } 00667 00668 assert(numElements->getType() == CGF.SizeTy); 00669 00670 if (minElements) { 00671 // Don't allow allocation of fewer elements than we have initializers. 00672 if (!hasOverflow) { 00673 hasOverflow = CGF.Builder.CreateICmpULT(numElements, 00674 llvm::ConstantInt::get(CGF.SizeTy, minElements)); 00675 } else if (numElementsWidth > sizeWidth) { 00676 // The other existing overflow subsumes this check. 00677 // We do an unsigned comparison, since any signed value < -1 is 00678 // taken care of either above or below. 00679 hasOverflow = CGF.Builder.CreateOr(hasOverflow, 00680 CGF.Builder.CreateICmpULT(numElements, 00681 llvm::ConstantInt::get(CGF.SizeTy, minElements))); 00682 } 00683 } 00684 00685 size = numElements; 00686 00687 // Multiply by the type size if necessary. This multiplier 00688 // includes all the factors for nested arrays. 00689 // 00690 // This step also causes numElements to be scaled up by the 00691 // nested-array factor if necessary. Overflow on this computation 00692 // can be ignored because the result shouldn't be used if 00693 // allocation fails. 00694 if (typeSizeMultiplier != 1) { 00695 llvm::Value *umul_with_overflow 00696 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy); 00697 00698 llvm::Value *tsmV = 00699 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier); 00700 llvm::Value *result = 00701 CGF.Builder.CreateCall2(umul_with_overflow, size, tsmV); 00702 00703 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 00704 if (hasOverflow) 00705 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 00706 else 00707 hasOverflow = overflowed; 00708 00709 size = CGF.Builder.CreateExtractValue(result, 0); 00710 00711 // Also scale up numElements by the array size multiplier. 00712 if (arraySizeMultiplier != 1) { 00713 // If the base element type size is 1, then we can re-use the 00714 // multiply we just did. 00715 if (typeSize.isOne()) { 00716 assert(arraySizeMultiplier == typeSizeMultiplier); 00717 numElements = size; 00718 00719 // Otherwise we need a separate multiply. 00720 } else { 00721 llvm::Value *asmV = 00722 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier); 00723 numElements = CGF.Builder.CreateMul(numElements, asmV); 00724 } 00725 } 00726 } else { 00727 // numElements doesn't need to be scaled. 00728 assert(arraySizeMultiplier == 1); 00729 } 00730 00731 // Add in the cookie size if necessary. 00732 if (cookieSize != 0) { 00733 sizeWithoutCookie = size; 00734 00735 llvm::Value *uadd_with_overflow 00736 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy); 00737 00738 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize); 00739 llvm::Value *result = 00740 CGF.Builder.CreateCall2(uadd_with_overflow, size, cookieSizeV); 00741 00742 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1); 00743 if (hasOverflow) 00744 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed); 00745 else 00746 hasOverflow = overflowed; 00747 00748 size = CGF.Builder.CreateExtractValue(result, 0); 00749 } 00750 00751 // If we had any possibility of dynamic overflow, make a select to 00752 // overwrite 'size' with an all-ones value, which should cause 00753 // operator new to throw. 00754 if (hasOverflow) 00755 size = CGF.Builder.CreateSelect(hasOverflow, 00756 llvm::Constant::getAllOnesValue(CGF.SizeTy), 00757 size); 00758 } 00759 00760 if (cookieSize == 0) 00761 sizeWithoutCookie = size; 00762 else 00763 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?"); 00764 00765 return size; 00766 } 00767 00768 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init, 00769 QualType AllocType, llvm::Value *NewPtr) { 00770 00771 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(AllocType); 00772 if (!CGF.hasAggregateLLVMType(AllocType)) 00773 CGF.EmitScalarInit(Init, 0, CGF.MakeAddrLValue(NewPtr, AllocType, 00774 Alignment), 00775 false); 00776 else if (AllocType->isAnyComplexType()) 00777 CGF.EmitComplexExprIntoAddr(Init, NewPtr, 00778 AllocType.isVolatileQualified()); 00779 else { 00780 AggValueSlot Slot 00781 = AggValueSlot::forAddr(NewPtr, Alignment, AllocType.getQualifiers(), 00782 AggValueSlot::IsDestructed, 00783 AggValueSlot::DoesNotNeedGCBarriers, 00784 AggValueSlot::IsNotAliased); 00785 CGF.EmitAggExpr(Init, Slot); 00786 00787 CGF.MaybeEmitStdInitializerListCleanup(NewPtr, Init); 00788 } 00789 } 00790 00791 void 00792 CodeGenFunction::EmitNewArrayInitializer(const CXXNewExpr *E, 00793 QualType elementType, 00794 llvm::Value *beginPtr, 00795 llvm::Value *numElements) { 00796 if (!E->hasInitializer()) 00797 return; // We have a POD type. 00798 00799 llvm::Value *explicitPtr = beginPtr; 00800 // Find the end of the array, hoisted out of the loop. 00801 llvm::Value *endPtr = 00802 Builder.CreateInBoundsGEP(beginPtr, numElements, "array.end"); 00803 00804 unsigned initializerElements = 0; 00805 00806 const Expr *Init = E->getInitializer(); 00807 llvm::AllocaInst *endOfInit = 0; 00808 QualType::DestructionKind dtorKind = elementType.isDestructedType(); 00809 EHScopeStack::stable_iterator cleanup; 00810 llvm::Instruction *cleanupDominator = 0; 00811 // If the initializer is an initializer list, first do the explicit elements. 00812 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) { 00813 initializerElements = ILE->getNumInits(); 00814 00815 // Enter a partial-destruction cleanup if necessary. 00816 if (needsEHCleanup(dtorKind)) { 00817 // In principle we could tell the cleanup where we are more 00818 // directly, but the control flow can get so varied here that it 00819 // would actually be quite complex. Therefore we go through an 00820 // alloca. 00821 endOfInit = CreateTempAlloca(beginPtr->getType(), "array.endOfInit"); 00822 cleanupDominator = Builder.CreateStore(beginPtr, endOfInit); 00823 pushIrregularPartialArrayCleanup(beginPtr, endOfInit, elementType, 00824 getDestroyer(dtorKind)); 00825 cleanup = EHStack.stable_begin(); 00826 } 00827 00828 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) { 00829 // Tell the cleanup that it needs to destroy up to this 00830 // element. TODO: some of these stores can be trivially 00831 // observed to be unnecessary. 00832 if (endOfInit) Builder.CreateStore(explicitPtr, endOfInit); 00833 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i), elementType, explicitPtr); 00834 explicitPtr =Builder.CreateConstGEP1_32(explicitPtr, 1, "array.exp.next"); 00835 } 00836 00837 // The remaining elements are filled with the array filler expression. 00838 Init = ILE->getArrayFiller(); 00839 } 00840 00841 // Create the continuation block. 00842 llvm::BasicBlock *contBB = createBasicBlock("new.loop.end"); 00843 00844 // If the number of elements isn't constant, we have to now check if there is 00845 // anything left to initialize. 00846 if (llvm::ConstantInt *constNum = dyn_cast<llvm::ConstantInt>(numElements)) { 00847 // If all elements have already been initialized, skip the whole loop. 00848 if (constNum->getZExtValue() <= initializerElements) { 00849 // If there was a cleanup, deactivate it. 00850 if (cleanupDominator) 00851 DeactivateCleanupBlock(cleanup, cleanupDominator);; 00852 return; 00853 } 00854 } else { 00855 llvm::BasicBlock *nonEmptyBB = createBasicBlock("new.loop.nonempty"); 00856 llvm::Value *isEmpty = Builder.CreateICmpEQ(explicitPtr, endPtr, 00857 "array.isempty"); 00858 Builder.CreateCondBr(isEmpty, contBB, nonEmptyBB); 00859 EmitBlock(nonEmptyBB); 00860 } 00861 00862 // Enter the loop. 00863 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 00864 llvm::BasicBlock *loopBB = createBasicBlock("new.loop"); 00865 00866 EmitBlock(loopBB); 00867 00868 // Set up the current-element phi. 00869 llvm::PHINode *curPtr = 00870 Builder.CreatePHI(explicitPtr->getType(), 2, "array.cur"); 00871 curPtr->addIncoming(explicitPtr, entryBB); 00872 00873 // Store the new cleanup position for irregular cleanups. 00874 if (endOfInit) Builder.CreateStore(curPtr, endOfInit); 00875 00876 // Enter a partial-destruction cleanup if necessary. 00877 if (!cleanupDominator && needsEHCleanup(dtorKind)) { 00878 pushRegularPartialArrayCleanup(beginPtr, curPtr, elementType, 00879 getDestroyer(dtorKind)); 00880 cleanup = EHStack.stable_begin(); 00881 cleanupDominator = Builder.CreateUnreachable(); 00882 } 00883 00884 // Emit the initializer into this element. 00885 StoreAnyExprIntoOneUnit(*this, Init, E->getAllocatedType(), curPtr); 00886 00887 // Leave the cleanup if we entered one. 00888 if (cleanupDominator) { 00889 DeactivateCleanupBlock(cleanup, cleanupDominator); 00890 cleanupDominator->eraseFromParent(); 00891 } 00892 00893 // Advance to the next element. 00894 llvm::Value *nextPtr = Builder.CreateConstGEP1_32(curPtr, 1, "array.next"); 00895 00896 // Check whether we've gotten to the end of the array and, if so, 00897 // exit the loop. 00898 llvm::Value *isEnd = Builder.CreateICmpEQ(nextPtr, endPtr, "array.atend"); 00899 Builder.CreateCondBr(isEnd, contBB, loopBB); 00900 curPtr->addIncoming(nextPtr, Builder.GetInsertBlock()); 00901 00902 EmitBlock(contBB); 00903 } 00904 00905 static void EmitZeroMemSet(CodeGenFunction &CGF, QualType T, 00906 llvm::Value *NewPtr, llvm::Value *Size) { 00907 CGF.EmitCastToVoidPtr(NewPtr); 00908 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(T); 00909 CGF.Builder.CreateMemSet(NewPtr, CGF.Builder.getInt8(0), Size, 00910 Alignment.getQuantity(), false); 00911 } 00912 00913 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E, 00914 QualType ElementType, 00915 llvm::Value *NewPtr, 00916 llvm::Value *NumElements, 00917 llvm::Value *AllocSizeWithoutCookie) { 00918 const Expr *Init = E->getInitializer(); 00919 if (E->isArray()) { 00920 if (const CXXConstructExpr *CCE = dyn_cast_or_null<CXXConstructExpr>(Init)){ 00921 CXXConstructorDecl *Ctor = CCE->getConstructor(); 00922 bool RequiresZeroInitialization = false; 00923 if (Ctor->isTrivial()) { 00924 // If new expression did not specify value-initialization, then there 00925 // is no initialization. 00926 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty()) 00927 return; 00928 00929 if (CGF.CGM.getTypes().isZeroInitializable(ElementType)) { 00930 // Optimization: since zero initialization will just set the memory 00931 // to all zeroes, generate a single memset to do it in one shot. 00932 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie); 00933 return; 00934 } 00935 00936 RequiresZeroInitialization = true; 00937 } 00938 00939 CGF.EmitCXXAggrConstructorCall(Ctor, NumElements, NewPtr, 00940 CCE->arg_begin(), CCE->arg_end(), 00941 RequiresZeroInitialization); 00942 return; 00943 } else if (Init && isa<ImplicitValueInitExpr>(Init) && 00944 CGF.CGM.getTypes().isZeroInitializable(ElementType)) { 00945 // Optimization: since zero initialization will just set the memory 00946 // to all zeroes, generate a single memset to do it in one shot. 00947 EmitZeroMemSet(CGF, ElementType, NewPtr, AllocSizeWithoutCookie); 00948 return; 00949 } 00950 CGF.EmitNewArrayInitializer(E, ElementType, NewPtr, NumElements); 00951 return; 00952 } 00953 00954 if (!Init) 00955 return; 00956 00957 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr); 00958 } 00959 00960 namespace { 00961 /// A cleanup to call the given 'operator delete' function upon 00962 /// abnormal exit from a new expression. 00963 class CallDeleteDuringNew : public EHScopeStack::Cleanup { 00964 size_t NumPlacementArgs; 00965 const FunctionDecl *OperatorDelete; 00966 llvm::Value *Ptr; 00967 llvm::Value *AllocSize; 00968 00969 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); } 00970 00971 public: 00972 static size_t getExtraSize(size_t NumPlacementArgs) { 00973 return NumPlacementArgs * sizeof(RValue); 00974 } 00975 00976 CallDeleteDuringNew(size_t NumPlacementArgs, 00977 const FunctionDecl *OperatorDelete, 00978 llvm::Value *Ptr, 00979 llvm::Value *AllocSize) 00980 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete), 00981 Ptr(Ptr), AllocSize(AllocSize) {} 00982 00983 void setPlacementArg(unsigned I, RValue Arg) { 00984 assert(I < NumPlacementArgs && "index out of range"); 00985 getPlacementArgs()[I] = Arg; 00986 } 00987 00988 void Emit(CodeGenFunction &CGF, Flags flags) { 00989 const FunctionProtoType *FPT 00990 = OperatorDelete->getType()->getAs<FunctionProtoType>(); 00991 assert(FPT->getNumArgs() == NumPlacementArgs + 1 || 00992 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0)); 00993 00994 CallArgList DeleteArgs; 00995 00996 // The first argument is always a void*. 00997 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin(); 00998 DeleteArgs.add(RValue::get(Ptr), *AI++); 00999 01000 // A member 'operator delete' can take an extra 'size_t' argument. 01001 if (FPT->getNumArgs() == NumPlacementArgs + 2) 01002 DeleteArgs.add(RValue::get(AllocSize), *AI++); 01003 01004 // Pass the rest of the arguments, which must match exactly. 01005 for (unsigned I = 0; I != NumPlacementArgs; ++I) 01006 DeleteArgs.add(getPlacementArgs()[I], *AI++); 01007 01008 // Call 'operator delete'. 01009 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT), 01010 CGF.CGM.GetAddrOfFunction(OperatorDelete), 01011 ReturnValueSlot(), DeleteArgs, OperatorDelete); 01012 } 01013 }; 01014 01015 /// A cleanup to call the given 'operator delete' function upon 01016 /// abnormal exit from a new expression when the new expression is 01017 /// conditional. 01018 class CallDeleteDuringConditionalNew : public EHScopeStack::Cleanup { 01019 size_t NumPlacementArgs; 01020 const FunctionDecl *OperatorDelete; 01021 DominatingValue<RValue>::saved_type Ptr; 01022 DominatingValue<RValue>::saved_type AllocSize; 01023 01024 DominatingValue<RValue>::saved_type *getPlacementArgs() { 01025 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1); 01026 } 01027 01028 public: 01029 static size_t getExtraSize(size_t NumPlacementArgs) { 01030 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type); 01031 } 01032 01033 CallDeleteDuringConditionalNew(size_t NumPlacementArgs, 01034 const FunctionDecl *OperatorDelete, 01035 DominatingValue<RValue>::saved_type Ptr, 01036 DominatingValue<RValue>::saved_type AllocSize) 01037 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete), 01038 Ptr(Ptr), AllocSize(AllocSize) {} 01039 01040 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) { 01041 assert(I < NumPlacementArgs && "index out of range"); 01042 getPlacementArgs()[I] = Arg; 01043 } 01044 01045 void Emit(CodeGenFunction &CGF, Flags flags) { 01046 const FunctionProtoType *FPT 01047 = OperatorDelete->getType()->getAs<FunctionProtoType>(); 01048 assert(FPT->getNumArgs() == NumPlacementArgs + 1 || 01049 (FPT->getNumArgs() == 2 && NumPlacementArgs == 0)); 01050 01051 CallArgList DeleteArgs; 01052 01053 // The first argument is always a void*. 01054 FunctionProtoType::arg_type_iterator AI = FPT->arg_type_begin(); 01055 DeleteArgs.add(Ptr.restore(CGF), *AI++); 01056 01057 // A member 'operator delete' can take an extra 'size_t' argument. 01058 if (FPT->getNumArgs() == NumPlacementArgs + 2) { 01059 RValue RV = AllocSize.restore(CGF); 01060 DeleteArgs.add(RV, *AI++); 01061 } 01062 01063 // Pass the rest of the arguments, which must match exactly. 01064 for (unsigned I = 0; I != NumPlacementArgs; ++I) { 01065 RValue RV = getPlacementArgs()[I].restore(CGF); 01066 DeleteArgs.add(RV, *AI++); 01067 } 01068 01069 // Call 'operator delete'. 01070 CGF.EmitCall(CGF.CGM.getTypes().arrangeFunctionCall(DeleteArgs, FPT), 01071 CGF.CGM.GetAddrOfFunction(OperatorDelete), 01072 ReturnValueSlot(), DeleteArgs, OperatorDelete); 01073 } 01074 }; 01075 } 01076 01077 /// Enter a cleanup to call 'operator delete' if the initializer in a 01078 /// new-expression throws. 01079 static void EnterNewDeleteCleanup(CodeGenFunction &CGF, 01080 const CXXNewExpr *E, 01081 llvm::Value *NewPtr, 01082 llvm::Value *AllocSize, 01083 const CallArgList &NewArgs) { 01084 // If we're not inside a conditional branch, then the cleanup will 01085 // dominate and we can do the easier (and more efficient) thing. 01086 if (!CGF.isInConditionalBranch()) { 01087 CallDeleteDuringNew *Cleanup = CGF.EHStack 01088 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup, 01089 E->getNumPlacementArgs(), 01090 E->getOperatorDelete(), 01091 NewPtr, AllocSize); 01092 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) 01093 Cleanup->setPlacementArg(I, NewArgs[I+1].RV); 01094 01095 return; 01096 } 01097 01098 // Otherwise, we need to save all this stuff. 01099 DominatingValue<RValue>::saved_type SavedNewPtr = 01100 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr)); 01101 DominatingValue<RValue>::saved_type SavedAllocSize = 01102 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize)); 01103 01104 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack 01105 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup, 01106 E->getNumPlacementArgs(), 01107 E->getOperatorDelete(), 01108 SavedNewPtr, 01109 SavedAllocSize); 01110 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) 01111 Cleanup->setPlacementArg(I, 01112 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV)); 01113 01114 CGF.initFullExprCleanup(); 01115 } 01116 01117 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) { 01118 // The element type being allocated. 01119 QualType allocType = getContext().getBaseElementType(E->getAllocatedType()); 01120 01121 // 1. Build a call to the allocation function. 01122 FunctionDecl *allocator = E->getOperatorNew(); 01123 const FunctionProtoType *allocatorType = 01124 allocator->getType()->castAs<FunctionProtoType>(); 01125 01126 CallArgList allocatorArgs; 01127 01128 // The allocation size is the first argument. 01129 QualType sizeType = getContext().getSizeType(); 01130 01131 // If there is a brace-initializer, cannot allocate fewer elements than inits. 01132 unsigned minElements = 0; 01133 if (E->isArray() && E->hasInitializer()) { 01134 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer())) 01135 minElements = ILE->getNumInits(); 01136 } 01137 01138 llvm::Value *numElements = 0; 01139 llvm::Value *allocSizeWithoutCookie = 0; 01140 llvm::Value *allocSize = 01141 EmitCXXNewAllocSize(*this, E, minElements, numElements, 01142 allocSizeWithoutCookie); 01143 01144 allocatorArgs.add(RValue::get(allocSize), sizeType); 01145 01146 // Emit the rest of the arguments. 01147 // FIXME: Ideally, this should just use EmitCallArgs. 01148 CXXNewExpr::const_arg_iterator placementArg = E->placement_arg_begin(); 01149 01150 // First, use the types from the function type. 01151 // We start at 1 here because the first argument (the allocation size) 01152 // has already been emitted. 01153 for (unsigned i = 1, e = allocatorType->getNumArgs(); i != e; 01154 ++i, ++placementArg) { 01155 QualType argType = allocatorType->getArgType(i); 01156 01157 assert(getContext().hasSameUnqualifiedType(argType.getNonReferenceType(), 01158 placementArg->getType()) && 01159 "type mismatch in call argument!"); 01160 01161 EmitCallArg(allocatorArgs, *placementArg, argType); 01162 } 01163 01164 // Either we've emitted all the call args, or we have a call to a 01165 // variadic function. 01166 assert((placementArg == E->placement_arg_end() || 01167 allocatorType->isVariadic()) && 01168 "Extra arguments to non-variadic function!"); 01169 01170 // If we still have any arguments, emit them using the type of the argument. 01171 for (CXXNewExpr::const_arg_iterator placementArgsEnd = E->placement_arg_end(); 01172 placementArg != placementArgsEnd; ++placementArg) { 01173 EmitCallArg(allocatorArgs, *placementArg, placementArg->getType()); 01174 } 01175 01176 // Emit the allocation call. If the allocator is a global placement 01177 // operator, just "inline" it directly. 01178 RValue RV; 01179 if (allocator->isReservedGlobalPlacementOperator()) { 01180 assert(allocatorArgs.size() == 2); 01181 RV = allocatorArgs[1].RV; 01182 // TODO: kill any unnecessary computations done for the size 01183 // argument. 01184 } else { 01185 RV = EmitCall(CGM.getTypes().arrangeFunctionCall(allocatorArgs, 01186 allocatorType), 01187 CGM.GetAddrOfFunction(allocator), ReturnValueSlot(), 01188 allocatorArgs, allocator); 01189 } 01190 01191 // Emit a null check on the allocation result if the allocation 01192 // function is allowed to return null (because it has a non-throwing 01193 // exception spec; for this part, we inline 01194 // CXXNewExpr::shouldNullCheckAllocation()) and we have an 01195 // interesting initializer. 01196 bool nullCheck = allocatorType->isNothrow(getContext()) && 01197 (!allocType.isPODType(getContext()) || E->hasInitializer()); 01198 01199 llvm::BasicBlock *nullCheckBB = 0; 01200 llvm::BasicBlock *contBB = 0; 01201 01202 llvm::Value *allocation = RV.getScalarVal(); 01203 unsigned AS = 01204 cast<llvm::PointerType>(allocation->getType())->getAddressSpace(); 01205 01206 // The null-check means that the initializer is conditionally 01207 // evaluated. 01208 ConditionalEvaluation conditional(*this); 01209 01210 if (nullCheck) { 01211 conditional.begin(*this); 01212 01213 nullCheckBB = Builder.GetInsertBlock(); 01214 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull"); 01215 contBB = createBasicBlock("new.cont"); 01216 01217 llvm::Value *isNull = Builder.CreateIsNull(allocation, "new.isnull"); 01218 Builder.CreateCondBr(isNull, contBB, notNullBB); 01219 EmitBlock(notNullBB); 01220 } 01221 01222 // If there's an operator delete, enter a cleanup to call it if an 01223 // exception is thrown. 01224 EHScopeStack::stable_iterator operatorDeleteCleanup; 01225 llvm::Instruction *cleanupDominator = 0; 01226 if (E->getOperatorDelete() && 01227 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) { 01228 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs); 01229 operatorDeleteCleanup = EHStack.stable_begin(); 01230 cleanupDominator = Builder.CreateUnreachable(); 01231 } 01232 01233 assert((allocSize == allocSizeWithoutCookie) == 01234 CalculateCookiePadding(*this, E).isZero()); 01235 if (allocSize != allocSizeWithoutCookie) { 01236 assert(E->isArray()); 01237 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation, 01238 numElements, 01239 E, allocType); 01240 } 01241 01242 llvm::Type *elementPtrTy 01243 = ConvertTypeForMem(allocType)->getPointerTo(AS); 01244 llvm::Value *result = Builder.CreateBitCast(allocation, elementPtrTy); 01245 01246 EmitNewInitializer(*this, E, allocType, result, numElements, 01247 allocSizeWithoutCookie); 01248 if (E->isArray()) { 01249 // NewPtr is a pointer to the base element type. If we're 01250 // allocating an array of arrays, we'll need to cast back to the 01251 // array pointer type. 01252 llvm::Type *resultType = ConvertTypeForMem(E->getType()); 01253 if (result->getType() != resultType) 01254 result = Builder.CreateBitCast(result, resultType); 01255 } 01256 01257 // Deactivate the 'operator delete' cleanup if we finished 01258 // initialization. 01259 if (operatorDeleteCleanup.isValid()) { 01260 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator); 01261 cleanupDominator->eraseFromParent(); 01262 } 01263 01264 if (nullCheck) { 01265 conditional.end(*this); 01266 01267 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 01268 EmitBlock(contBB); 01269 01270 llvm::PHINode *PHI = Builder.CreatePHI(result->getType(), 2); 01271 PHI->addIncoming(result, notNullBB); 01272 PHI->addIncoming(llvm::Constant::getNullValue(result->getType()), 01273 nullCheckBB); 01274 01275 result = PHI; 01276 } 01277 01278 return result; 01279 } 01280 01281 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD, 01282 llvm::Value *Ptr, 01283 QualType DeleteTy) { 01284 assert(DeleteFD->getOverloadedOperator() == OO_Delete); 01285 01286 const FunctionProtoType *DeleteFTy = 01287 DeleteFD->getType()->getAs<FunctionProtoType>(); 01288 01289 CallArgList DeleteArgs; 01290 01291 // Check if we need to pass the size to the delete operator. 01292 llvm::Value *Size = 0; 01293 QualType SizeTy; 01294 if (DeleteFTy->getNumArgs() == 2) { 01295 SizeTy = DeleteFTy->getArgType(1); 01296 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy); 01297 Size = llvm::ConstantInt::get(ConvertType(SizeTy), 01298 DeleteTypeSize.getQuantity()); 01299 } 01300 01301 QualType ArgTy = DeleteFTy->getArgType(0); 01302 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy)); 01303 DeleteArgs.add(RValue::get(DeletePtr), ArgTy); 01304 01305 if (Size) 01306 DeleteArgs.add(RValue::get(Size), SizeTy); 01307 01308 // Emit the call to delete. 01309 EmitCall(CGM.getTypes().arrangeFunctionCall(DeleteArgs, DeleteFTy), 01310 CGM.GetAddrOfFunction(DeleteFD), ReturnValueSlot(), 01311 DeleteArgs, DeleteFD); 01312 } 01313 01314 namespace { 01315 /// Calls the given 'operator delete' on a single object. 01316 struct CallObjectDelete : EHScopeStack::Cleanup { 01317 llvm::Value *Ptr; 01318 const FunctionDecl *OperatorDelete; 01319 QualType ElementType; 01320 01321 CallObjectDelete(llvm::Value *Ptr, 01322 const FunctionDecl *OperatorDelete, 01323 QualType ElementType) 01324 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {} 01325 01326 void Emit(CodeGenFunction &CGF, Flags flags) { 01327 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType); 01328 } 01329 }; 01330 } 01331 01332 /// Emit the code for deleting a single object. 01333 static void EmitObjectDelete(CodeGenFunction &CGF, 01334 const FunctionDecl *OperatorDelete, 01335 llvm::Value *Ptr, 01336 QualType ElementType, 01337 bool UseGlobalDelete) { 01338 // Find the destructor for the type, if applicable. If the 01339 // destructor is virtual, we'll just emit the vcall and return. 01340 const CXXDestructorDecl *Dtor = 0; 01341 if (const RecordType *RT = ElementType->getAs<RecordType>()) { 01342 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 01343 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) { 01344 Dtor = RD->getDestructor(); 01345 01346 if (Dtor->isVirtual()) { 01347 if (UseGlobalDelete) { 01348 // If we're supposed to call the global delete, make sure we do so 01349 // even if the destructor throws. 01350 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 01351 Ptr, OperatorDelete, 01352 ElementType); 01353 } 01354 01355 llvm::Type *Ty = 01356 CGF.getTypes().GetFunctionType( 01357 CGF.getTypes().arrangeCXXDestructor(Dtor, Dtor_Complete)); 01358 01359 llvm::Value *Callee 01360 = CGF.BuildVirtualCall(Dtor, 01361 UseGlobalDelete? Dtor_Complete : Dtor_Deleting, 01362 Ptr, Ty); 01363 CGF.EmitCXXMemberCall(Dtor, Callee, ReturnValueSlot(), Ptr, /*VTT=*/0, 01364 0, 0); 01365 01366 if (UseGlobalDelete) { 01367 CGF.PopCleanupBlock(); 01368 } 01369 01370 return; 01371 } 01372 } 01373 } 01374 01375 // Make sure that we call delete even if the dtor throws. 01376 // This doesn't have to a conditional cleanup because we're going 01377 // to pop it off in a second. 01378 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, 01379 Ptr, OperatorDelete, ElementType); 01380 01381 if (Dtor) 01382 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 01383 /*ForVirtualBase=*/false, Ptr); 01384 else if (CGF.getLangOpts().ObjCAutoRefCount && 01385 ElementType->isObjCLifetimeType()) { 01386 switch (ElementType.getObjCLifetime()) { 01387 case Qualifiers::OCL_None: 01388 case Qualifiers::OCL_ExplicitNone: 01389 case Qualifiers::OCL_Autoreleasing: 01390 break; 01391 01392 case Qualifiers::OCL_Strong: { 01393 // Load the pointer value. 01394 llvm::Value *PtrValue = CGF.Builder.CreateLoad(Ptr, 01395 ElementType.isVolatileQualified()); 01396 01397 CGF.EmitARCRelease(PtrValue, /*precise*/ true); 01398 break; 01399 } 01400 01401 case Qualifiers::OCL_Weak: 01402 CGF.EmitARCDestroyWeak(Ptr); 01403 break; 01404 } 01405 } 01406 01407 CGF.PopCleanupBlock(); 01408 } 01409 01410 namespace { 01411 /// Calls the given 'operator delete' on an array of objects. 01412 struct CallArrayDelete : EHScopeStack::Cleanup { 01413 llvm::Value *Ptr; 01414 const FunctionDecl *OperatorDelete; 01415 llvm::Value *NumElements; 01416 QualType ElementType; 01417 CharUnits CookieSize; 01418 01419 CallArrayDelete(llvm::Value *Ptr, 01420 const FunctionDecl *OperatorDelete, 01421 llvm::Value *NumElements, 01422 QualType ElementType, 01423 CharUnits CookieSize) 01424 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements), 01425 ElementType(ElementType), CookieSize(CookieSize) {} 01426 01427 void Emit(CodeGenFunction &CGF, Flags flags) { 01428 const FunctionProtoType *DeleteFTy = 01429 OperatorDelete->getType()->getAs<FunctionProtoType>(); 01430 assert(DeleteFTy->getNumArgs() == 1 || DeleteFTy->getNumArgs() == 2); 01431 01432 CallArgList Args; 01433 01434 // Pass the pointer as the first argument. 01435 QualType VoidPtrTy = DeleteFTy->getArgType(0); 01436 llvm::Value *DeletePtr 01437 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy)); 01438 Args.add(RValue::get(DeletePtr), VoidPtrTy); 01439 01440 // Pass the original requested size as the second argument. 01441 if (DeleteFTy->getNumArgs() == 2) { 01442 QualType size_t = DeleteFTy->getArgType(1); 01443 llvm::IntegerType *SizeTy 01444 = cast<llvm::IntegerType>(CGF.ConvertType(size_t)); 01445 01446 CharUnits ElementTypeSize = 01447 CGF.CGM.getContext().getTypeSizeInChars(ElementType); 01448 01449 // The size of an element, multiplied by the number of elements. 01450 llvm::Value *Size 01451 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity()); 01452 Size = CGF.Builder.CreateMul(Size, NumElements); 01453 01454 // Plus the size of the cookie if applicable. 01455 if (!CookieSize.isZero()) { 01456 llvm::Value *CookieSizeV 01457 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()); 01458 Size = CGF.Builder.CreateAdd(Size, CookieSizeV); 01459 } 01460 01461 Args.add(RValue::get(Size), size_t); 01462 } 01463 01464 // Emit the call to delete. 01465 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Args, DeleteFTy), 01466 CGF.CGM.GetAddrOfFunction(OperatorDelete), 01467 ReturnValueSlot(), Args, OperatorDelete); 01468 } 01469 }; 01470 } 01471 01472 /// Emit the code for deleting an array of objects. 01473 static void EmitArrayDelete(CodeGenFunction &CGF, 01474 const CXXDeleteExpr *E, 01475 llvm::Value *deletedPtr, 01476 QualType elementType) { 01477 llvm::Value *numElements = 0; 01478 llvm::Value *allocatedPtr = 0; 01479 CharUnits cookieSize; 01480 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType, 01481 numElements, allocatedPtr, cookieSize); 01482 01483 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer"); 01484 01485 // Make sure that we call delete even if one of the dtors throws. 01486 const FunctionDecl *operatorDelete = E->getOperatorDelete(); 01487 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup, 01488 allocatedPtr, operatorDelete, 01489 numElements, elementType, 01490 cookieSize); 01491 01492 // Destroy the elements. 01493 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) { 01494 assert(numElements && "no element count for a type with a destructor!"); 01495 01496 llvm::Value *arrayEnd = 01497 CGF.Builder.CreateInBoundsGEP(deletedPtr, numElements, "delete.end"); 01498 01499 // Note that it is legal to allocate a zero-length array, and we 01500 // can never fold the check away because the length should always 01501 // come from a cookie. 01502 CGF.emitArrayDestroy(deletedPtr, arrayEnd, elementType, 01503 CGF.getDestroyer(dtorKind), 01504 /*checkZeroLength*/ true, 01505 CGF.needsEHCleanup(dtorKind)); 01506 } 01507 01508 // Pop the cleanup block. 01509 CGF.PopCleanupBlock(); 01510 } 01511 01512 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) { 01513 01514 // Get at the argument before we performed the implicit conversion 01515 // to void*. 01516 const Expr *Arg = E->getArgument(); 01517 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg)) { 01518 if (ICE->getCastKind() != CK_UserDefinedConversion && 01519 ICE->getType()->isVoidPointerType()) 01520 Arg = ICE->getSubExpr(); 01521 else 01522 break; 01523 } 01524 01525 llvm::Value *Ptr = EmitScalarExpr(Arg); 01526 01527 // Null check the pointer. 01528 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull"); 01529 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end"); 01530 01531 llvm::Value *IsNull = Builder.CreateIsNull(Ptr, "isnull"); 01532 01533 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull); 01534 EmitBlock(DeleteNotNull); 01535 01536 // We might be deleting a pointer to array. If so, GEP down to the 01537 // first non-array element. 01538 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*) 01539 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType(); 01540 if (DeleteTy->isConstantArrayType()) { 01541 llvm::Value *Zero = Builder.getInt32(0); 01542 SmallVector<llvm::Value*,8> GEP; 01543 01544 GEP.push_back(Zero); // point at the outermost array 01545 01546 // For each layer of array type we're pointing at: 01547 while (const ConstantArrayType *Arr 01548 = getContext().getAsConstantArrayType(DeleteTy)) { 01549 // 1. Unpeel the array type. 01550 DeleteTy = Arr->getElementType(); 01551 01552 // 2. GEP to the first element of the array. 01553 GEP.push_back(Zero); 01554 } 01555 01556 Ptr = Builder.CreateInBoundsGEP(Ptr, GEP, "del.first"); 01557 } 01558 01559 assert(ConvertTypeForMem(DeleteTy) == 01560 cast<llvm::PointerType>(Ptr->getType())->getElementType()); 01561 01562 if (E->isArrayForm()) { 01563 EmitArrayDelete(*this, E, Ptr, DeleteTy); 01564 } else { 01565 EmitObjectDelete(*this, E->getOperatorDelete(), Ptr, DeleteTy, 01566 E->isGlobalDelete()); 01567 } 01568 01569 EmitBlock(DeleteEnd); 01570 } 01571 01572 static llvm::Constant *getBadTypeidFn(CodeGenFunction &CGF) { 01573 // void __cxa_bad_typeid(); 01574 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 01575 01576 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_typeid"); 01577 } 01578 01579 static void EmitBadTypeidCall(CodeGenFunction &CGF) { 01580 llvm::Value *Fn = getBadTypeidFn(CGF); 01581 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn(); 01582 CGF.Builder.CreateUnreachable(); 01583 } 01584 01585 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, 01586 const Expr *E, 01587 llvm::Type *StdTypeInfoPtrTy) { 01588 // Get the vtable pointer. 01589 llvm::Value *ThisPtr = CGF.EmitLValue(E).getAddress(); 01590 01591 // C++ [expr.typeid]p2: 01592 // If the glvalue expression is obtained by applying the unary * operator to 01593 // a pointer and the pointer is a null pointer value, the typeid expression 01594 // throws the std::bad_typeid exception. 01595 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E->IgnoreParens())) { 01596 if (UO->getOpcode() == UO_Deref) { 01597 llvm::BasicBlock *BadTypeidBlock = 01598 CGF.createBasicBlock("typeid.bad_typeid"); 01599 llvm::BasicBlock *EndBlock = 01600 CGF.createBasicBlock("typeid.end"); 01601 01602 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr); 01603 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock); 01604 01605 CGF.EmitBlock(BadTypeidBlock); 01606 EmitBadTypeidCall(CGF); 01607 CGF.EmitBlock(EndBlock); 01608 } 01609 } 01610 01611 llvm::Value *Value = CGF.GetVTablePtr(ThisPtr, 01612 StdTypeInfoPtrTy->getPointerTo()); 01613 01614 // Load the type info. 01615 Value = CGF.Builder.CreateConstInBoundsGEP1_64(Value, -1ULL); 01616 return CGF.Builder.CreateLoad(Value); 01617 } 01618 01619 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) { 01620 llvm::Type *StdTypeInfoPtrTy = 01621 ConvertType(E->getType())->getPointerTo(); 01622 01623 if (E->isTypeOperand()) { 01624 llvm::Constant *TypeInfo = 01625 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand()); 01626 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy); 01627 } 01628 01629 // C++ [expr.typeid]p2: 01630 // When typeid is applied to a glvalue expression whose type is a 01631 // polymorphic class type, the result refers to a std::type_info object 01632 // representing the type of the most derived object (that is, the dynamic 01633 // type) to which the glvalue refers. 01634 if (E->getExprOperand()->isGLValue()) { 01635 if (const RecordType *RT = 01636 E->getExprOperand()->getType()->getAs<RecordType>()) { 01637 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 01638 if (RD->isPolymorphic()) 01639 return EmitTypeidFromVTable(*this, E->getExprOperand(), 01640 StdTypeInfoPtrTy); 01641 } 01642 } 01643 01644 QualType OperandTy = E->getExprOperand()->getType(); 01645 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy), 01646 StdTypeInfoPtrTy); 01647 } 01648 01649 static llvm::Constant *getDynamicCastFn(CodeGenFunction &CGF) { 01650 // void *__dynamic_cast(const void *sub, 01651 // const abi::__class_type_info *src, 01652 // const abi::__class_type_info *dst, 01653 // std::ptrdiff_t src2dst_offset); 01654 01655 llvm::Type *Int8PtrTy = CGF.Int8PtrTy; 01656 llvm::Type *PtrDiffTy = 01657 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 01658 01659 llvm::Type *Args[4] = { Int8PtrTy, Int8PtrTy, Int8PtrTy, PtrDiffTy }; 01660 01661 llvm::FunctionType *FTy = 01662 llvm::FunctionType::get(Int8PtrTy, Args, false); 01663 01664 return CGF.CGM.CreateRuntimeFunction(FTy, "__dynamic_cast"); 01665 } 01666 01667 static llvm::Constant *getBadCastFn(CodeGenFunction &CGF) { 01668 // void __cxa_bad_cast(); 01669 llvm::FunctionType *FTy = llvm::FunctionType::get(CGF.VoidTy, false); 01670 return CGF.CGM.CreateRuntimeFunction(FTy, "__cxa_bad_cast"); 01671 } 01672 01673 static void EmitBadCastCall(CodeGenFunction &CGF) { 01674 llvm::Value *Fn = getBadCastFn(CGF); 01675 CGF.EmitCallOrInvoke(Fn).setDoesNotReturn(); 01676 CGF.Builder.CreateUnreachable(); 01677 } 01678 01679 static llvm::Value * 01680 EmitDynamicCastCall(CodeGenFunction &CGF, llvm::Value *Value, 01681 QualType SrcTy, QualType DestTy, 01682 llvm::BasicBlock *CastEnd) { 01683 llvm::Type *PtrDiffLTy = 01684 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 01685 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 01686 01687 if (const PointerType *PTy = DestTy->getAs<PointerType>()) { 01688 if (PTy->getPointeeType()->isVoidType()) { 01689 // C++ [expr.dynamic.cast]p7: 01690 // If T is "pointer to cv void," then the result is a pointer to the 01691 // most derived object pointed to by v. 01692 01693 // Get the vtable pointer. 01694 llvm::Value *VTable = CGF.GetVTablePtr(Value, PtrDiffLTy->getPointerTo()); 01695 01696 // Get the offset-to-top from the vtable. 01697 llvm::Value *OffsetToTop = 01698 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, -2ULL); 01699 OffsetToTop = CGF.Builder.CreateLoad(OffsetToTop, "offset.to.top"); 01700 01701 // Finally, add the offset to the pointer. 01702 Value = CGF.EmitCastToVoidPtr(Value); 01703 Value = CGF.Builder.CreateInBoundsGEP(Value, OffsetToTop); 01704 01705 return CGF.Builder.CreateBitCast(Value, DestLTy); 01706 } 01707 } 01708 01709 QualType SrcRecordTy; 01710 QualType DestRecordTy; 01711 01712 if (const PointerType *DestPTy = DestTy->getAs<PointerType>()) { 01713 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType(); 01714 DestRecordTy = DestPTy->getPointeeType(); 01715 } else { 01716 SrcRecordTy = SrcTy; 01717 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType(); 01718 } 01719 01720 assert(SrcRecordTy->isRecordType() && "source type must be a record type!"); 01721 assert(DestRecordTy->isRecordType() && "dest type must be a record type!"); 01722 01723 llvm::Value *SrcRTTI = 01724 CGF.CGM.GetAddrOfRTTIDescriptor(SrcRecordTy.getUnqualifiedType()); 01725 llvm::Value *DestRTTI = 01726 CGF.CGM.GetAddrOfRTTIDescriptor(DestRecordTy.getUnqualifiedType()); 01727 01728 // FIXME: Actually compute a hint here. 01729 llvm::Value *OffsetHint = llvm::ConstantInt::get(PtrDiffLTy, -1ULL); 01730 01731 // Emit the call to __dynamic_cast. 01732 Value = CGF.EmitCastToVoidPtr(Value); 01733 Value = CGF.Builder.CreateCall4(getDynamicCastFn(CGF), Value, 01734 SrcRTTI, DestRTTI, OffsetHint); 01735 Value = CGF.Builder.CreateBitCast(Value, DestLTy); 01736 01737 /// C++ [expr.dynamic.cast]p9: 01738 /// A failed cast to reference type throws std::bad_cast 01739 if (DestTy->isReferenceType()) { 01740 llvm::BasicBlock *BadCastBlock = 01741 CGF.createBasicBlock("dynamic_cast.bad_cast"); 01742 01743 llvm::Value *IsNull = CGF.Builder.CreateIsNull(Value); 01744 CGF.Builder.CreateCondBr(IsNull, BadCastBlock, CastEnd); 01745 01746 CGF.EmitBlock(BadCastBlock); 01747 EmitBadCastCall(CGF); 01748 } 01749 01750 return Value; 01751 } 01752 01753 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF, 01754 QualType DestTy) { 01755 llvm::Type *DestLTy = CGF.ConvertType(DestTy); 01756 if (DestTy->isPointerType()) 01757 return llvm::Constant::getNullValue(DestLTy); 01758 01759 /// C++ [expr.dynamic.cast]p9: 01760 /// A failed cast to reference type throws std::bad_cast 01761 EmitBadCastCall(CGF); 01762 01763 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end")); 01764 return llvm::UndefValue::get(DestLTy); 01765 } 01766 01767 llvm::Value *CodeGenFunction::EmitDynamicCast(llvm::Value *Value, 01768 const CXXDynamicCastExpr *DCE) { 01769 QualType DestTy = DCE->getTypeAsWritten(); 01770 01771 if (DCE->isAlwaysNull()) 01772 return EmitDynamicCastToNull(*this, DestTy); 01773 01774 QualType SrcTy = DCE->getSubExpr()->getType(); 01775 01776 // C++ [expr.dynamic.cast]p4: 01777 // If the value of v is a null pointer value in the pointer case, the result 01778 // is the null pointer value of type T. 01779 bool ShouldNullCheckSrcValue = SrcTy->isPointerType(); 01780 01781 llvm::BasicBlock *CastNull = 0; 01782 llvm::BasicBlock *CastNotNull = 0; 01783 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end"); 01784 01785 if (ShouldNullCheckSrcValue) { 01786 CastNull = createBasicBlock("dynamic_cast.null"); 01787 CastNotNull = createBasicBlock("dynamic_cast.notnull"); 01788 01789 llvm::Value *IsNull = Builder.CreateIsNull(Value); 01790 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 01791 EmitBlock(CastNotNull); 01792 } 01793 01794 Value = EmitDynamicCastCall(*this, Value, SrcTy, DestTy, CastEnd); 01795 01796 if (ShouldNullCheckSrcValue) { 01797 EmitBranch(CastEnd); 01798 01799 EmitBlock(CastNull); 01800 EmitBranch(CastEnd); 01801 } 01802 01803 EmitBlock(CastEnd); 01804 01805 if (ShouldNullCheckSrcValue) { 01806 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 01807 PHI->addIncoming(Value, CastNotNull); 01808 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 01809 01810 Value = PHI; 01811 } 01812 01813 return Value; 01814 } 01815 01816 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) { 01817 RunCleanupsScope Scope(*this); 01818 LValue SlotLV = MakeAddrLValue(Slot.getAddr(), E->getType(), 01819 Slot.getAlignment()); 01820 01821 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin(); 01822 for (LambdaExpr::capture_init_iterator i = E->capture_init_begin(), 01823 e = E->capture_init_end(); 01824 i != e; ++i, ++CurField) { 01825 // Emit initialization 01826 01827 LValue LV = EmitLValueForFieldInitialization(SlotLV, &*CurField); 01828 ArrayRef<VarDecl *> ArrayIndexes; 01829 if (CurField->getType()->isArrayType()) 01830 ArrayIndexes = E->getCaptureInitIndexVars(i); 01831 EmitInitializerForField(&*CurField, LV, *i, ArrayIndexes); 01832 } 01833 }