1 //===--- CGExprCXX.cpp - Emit LLVM Code for C++ expressions ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code dealing with code generation of C++ expressions
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CGCUDARuntime.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"
24 using namespace clang;
25 using namespace CodeGen;
27 static RequiredArgs commonEmitCXXMemberOrOperatorCall(
28 CodeGenFunction &CGF, const CXXMethodDecl *MD, llvm::Value *Callee,
29 ReturnValueSlot ReturnValue, llvm::Value *This, llvm::Value *ImplicitParam,
30 QualType ImplicitParamTy, const CallExpr *CE, CallArgList &Args) {
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!");
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;
41 CallLoc = CE->getExprLoc();
43 isa<CXXConstructorDecl>(MD) ? CodeGenFunction::TCK_ConstructorCall
44 : CodeGenFunction::TCK_MemberCall,
45 CallLoc, This, CGF.getContext().getRecordType(MD->getParent()));
48 Args.add(RValue::get(This), MD->getThisType(CGF.getContext()));
50 // If there is an implicit parameter (e.g. VTT), emit it.
52 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
55 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
56 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size());
58 // And the rest of the call args.
60 // Special case: skip first argument of CXXOperatorCall (it is "this").
61 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
62 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
63 CE->getDirectCallee());
66 FPT->getNumParams() == 0 &&
67 "No CallExpr specified for function with non-zero number of arguments");
72 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
73 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
74 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
76 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
78 RequiredArgs required = commonEmitCXXMemberOrOperatorCall(
79 *this, MD, Callee, ReturnValue, This, ImplicitParam, ImplicitParamTy, CE,
81 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
82 Callee, ReturnValue, Args, MD);
85 RValue CodeGenFunction::EmitCXXStructorCall(
86 const CXXMethodDecl *MD, llvm::Value *Callee, ReturnValueSlot ReturnValue,
87 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
88 const CallExpr *CE, StructorType Type) {
90 commonEmitCXXMemberOrOperatorCall(*this, MD, Callee, ReturnValue, This,
91 ImplicitParam, ImplicitParamTy, CE, Args);
92 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(MD, Type),
93 Callee, ReturnValue, Args, MD);
96 static CXXRecordDecl *getCXXRecord(const Expr *E) {
97 QualType T = E->getType();
98 if (const PointerType *PTy = T->getAs<PointerType>())
99 T = PTy->getPointeeType();
100 const RecordType *Ty = T->castAs<RecordType>();
101 return cast<CXXRecordDecl>(Ty->getDecl());
104 // Note: This function also emit constructor calls to support a MSVC
105 // extensions allowing explicit constructor function call.
106 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
107 ReturnValueSlot ReturnValue) {
108 const Expr *callee = CE->getCallee()->IgnoreParens();
110 if (isa<BinaryOperator>(callee))
111 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
113 const MemberExpr *ME = cast<MemberExpr>(callee);
114 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
116 if (MD->isStatic()) {
117 // The method is static, emit it as we would a regular call.
118 llvm::Value *Callee = CGM.GetAddrOfFunction(MD);
119 return EmitCall(getContext().getPointerType(MD->getType()), Callee, CE,
123 bool HasQualifier = ME->hasQualifier();
124 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
125 bool IsArrow = ME->isArrow();
126 const Expr *Base = ME->getBase();
128 return EmitCXXMemberOrOperatorMemberCallExpr(
129 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
132 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
133 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
134 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
136 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
138 // Compute the object pointer.
139 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
141 const CXXMethodDecl *DevirtualizedMethod = nullptr;
142 if (CanUseVirtualCall && CanDevirtualizeMemberFunctionCall(Base, MD)) {
143 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
144 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
145 assert(DevirtualizedMethod);
146 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
147 const Expr *Inner = Base->ignoreParenBaseCasts();
148 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
149 MD->getReturnType().getCanonicalType())
150 // If the return types are not the same, this might be a case where more
151 // code needs to run to compensate for it. For example, the derived
152 // method might return a type that inherits form from the return
153 // type of MD and has a prefix.
154 // For now we just avoid devirtualizing these covariant cases.
155 DevirtualizedMethod = nullptr;
156 else if (getCXXRecord(Inner) == DevirtualizedClass)
157 // If the class of the Inner expression is where the dynamic method
158 // is defined, build the this pointer from it.
160 else if (getCXXRecord(Base) != DevirtualizedClass) {
161 // If the method is defined in a class that is not the best dynamic
162 // one or the one of the full expression, we would have to build
163 // a derived-to-base cast to compute the correct this pointer, but
164 // we don't have support for that yet, so do a virtual call.
165 DevirtualizedMethod = nullptr;
169 Address This = Address::invalid();
171 This = EmitPointerWithAlignment(Base);
173 This = EmitLValue(Base).getAddress();
176 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
177 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
178 if (isa<CXXConstructorDecl>(MD) &&
179 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
180 return RValue::get(nullptr);
182 if (!MD->getParent()->mayInsertExtraPadding()) {
183 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
184 // We don't like to generate the trivial copy/move assignment operator
185 // when it isn't necessary; just produce the proper effect here.
186 // Special case: skip first argument of CXXOperatorCall (it is "this").
187 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
188 Address RHS = EmitLValue(*(CE->arg_begin() + ArgsToSkip)).getAddress();
189 EmitAggregateAssign(This, RHS, CE->getType());
190 return RValue::get(This.getPointer());
193 if (isa<CXXConstructorDecl>(MD) &&
194 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
195 // Trivial move and copy ctor are the same.
196 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
197 Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
198 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
199 return RValue::get(This.getPointer());
201 llvm_unreachable("unknown trivial member function");
205 // Compute the function type we're calling.
206 const CXXMethodDecl *CalleeDecl =
207 DevirtualizedMethod ? DevirtualizedMethod : MD;
208 const CGFunctionInfo *FInfo = nullptr;
209 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
210 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
211 Dtor, StructorType::Complete);
212 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
213 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
214 Ctor, StructorType::Complete);
216 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
218 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
220 // C++ [class.virtual]p12:
221 // Explicit qualification with the scope operator (5.1) suppresses the
222 // virtual call mechanism.
224 // We also don't emit a virtual call if the base expression has a record type
225 // because then we know what the type is.
226 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
229 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
230 assert(CE->arg_begin() == CE->arg_end() &&
231 "Destructor shouldn't have explicit parameters");
232 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
233 if (UseVirtualCall) {
234 CGM.getCXXABI().EmitVirtualDestructorCall(
235 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
237 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
238 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
239 else if (!DevirtualizedMethod)
241 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty);
243 const CXXDestructorDecl *DDtor =
244 cast<CXXDestructorDecl>(DevirtualizedMethod);
245 Callee = CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty);
247 EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
248 /*ImplicitParam=*/nullptr, QualType(), CE);
250 return RValue::get(nullptr);
253 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
254 Callee = CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty);
255 } else if (UseVirtualCall) {
256 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
259 if (SanOpts.has(SanitizerKind::CFINVCall) &&
260 MD->getParent()->isDynamicClass()) {
261 llvm::Value *VTable = GetVTablePtr(This, Int8PtrTy, MD->getParent());
262 EmitVTablePtrCheckForCall(MD->getParent(), VTable, CFITCK_NVCall,
266 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
267 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
268 else if (!DevirtualizedMethod)
269 Callee = CGM.GetAddrOfFunction(MD, Ty);
271 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
275 if (MD->isVirtual()) {
276 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
277 *this, MD, This, UseVirtualCall);
280 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
281 /*ImplicitParam=*/nullptr, QualType(), CE);
285 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
286 ReturnValueSlot ReturnValue) {
287 const BinaryOperator *BO =
288 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
289 const Expr *BaseExpr = BO->getLHS();
290 const Expr *MemFnExpr = BO->getRHS();
292 const MemberPointerType *MPT =
293 MemFnExpr->getType()->castAs<MemberPointerType>();
295 const FunctionProtoType *FPT =
296 MPT->getPointeeType()->castAs<FunctionProtoType>();
297 const CXXRecordDecl *RD =
298 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
300 // Get the member function pointer.
301 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
303 // Emit the 'this' pointer.
304 Address This = Address::invalid();
305 if (BO->getOpcode() == BO_PtrMemI)
306 This = EmitPointerWithAlignment(BaseExpr);
308 This = EmitLValue(BaseExpr).getAddress();
310 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
311 QualType(MPT->getClass(), 0));
313 // Ask the ABI to load the callee. Note that This is modified.
314 llvm::Value *ThisPtrForCall = nullptr;
315 llvm::Value *Callee =
316 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
317 ThisPtrForCall, MemFnPtr, MPT);
322 getContext().getPointerType(getContext().getTagDeclType(RD));
324 // Push the this ptr.
325 Args.add(RValue::get(ThisPtrForCall), ThisType);
327 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
329 // And the rest of the call args
330 EmitCallArgs(Args, FPT, E->arguments(), E->getDirectCallee());
331 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
332 Callee, ReturnValue, Args);
336 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
337 const CXXMethodDecl *MD,
338 ReturnValueSlot ReturnValue) {
339 assert(MD->isInstance() &&
340 "Trying to emit a member call expr on a static method!");
341 return EmitCXXMemberOrOperatorMemberCallExpr(
342 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
343 /*IsArrow=*/false, E->getArg(0));
346 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
347 ReturnValueSlot ReturnValue) {
348 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
351 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
353 const CXXRecordDecl *Base) {
357 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
359 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
360 CharUnits NVSize = Layout.getNonVirtualSize();
362 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
363 // present, they are initialized by the most derived class before calling the
365 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
366 Stores.emplace_back(CharUnits::Zero(), NVSize);
368 // Each store is split by the existence of a vbptr.
369 CharUnits VBPtrWidth = CGF.getPointerSize();
370 std::vector<CharUnits> VBPtrOffsets =
371 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
372 for (CharUnits VBPtrOffset : VBPtrOffsets) {
373 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
374 CharUnits LastStoreOffset = LastStore.first;
375 CharUnits LastStoreSize = LastStore.second;
377 CharUnits SplitBeforeOffset = LastStoreOffset;
378 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
379 assert(!SplitBeforeSize.isNegative() && "negative store size!");
380 if (!SplitBeforeSize.isZero())
381 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
383 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
384 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
385 assert(!SplitAfterSize.isNegative() && "negative store size!");
386 if (!SplitAfterSize.isZero())
387 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
390 // If the type contains a pointer to data member we can't memset it to zero.
391 // Instead, create a null constant and copy it to the destination.
392 // TODO: there are other patterns besides zero that we can usefully memset,
393 // like -1, which happens to be the pattern used by member-pointers.
394 // TODO: isZeroInitializable can be over-conservative in the case where a
395 // virtual base contains a member pointer.
396 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
397 if (!NullConstantForBase->isNullValue()) {
398 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
399 CGF.CGM.getModule(), NullConstantForBase->getType(),
400 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
401 NullConstantForBase, Twine());
403 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
404 DestPtr.getAlignment());
405 NullVariable->setAlignment(Align.getQuantity());
407 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
409 // Get and call the appropriate llvm.memcpy overload.
410 for (std::pair<CharUnits, CharUnits> Store : Stores) {
411 CharUnits StoreOffset = Store.first;
412 CharUnits StoreSize = Store.second;
413 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
414 CGF.Builder.CreateMemCpy(
415 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
416 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
420 // Otherwise, just memset the whole thing to zero. This is legal
421 // because in LLVM, all default initializers (other than the ones we just
422 // handled above) are guaranteed to have a bit pattern of all zeros.
424 for (std::pair<CharUnits, CharUnits> Store : Stores) {
425 CharUnits StoreOffset = Store.first;
426 CharUnits StoreSize = Store.second;
427 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
428 CGF.Builder.CreateMemSet(
429 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
430 CGF.Builder.getInt8(0), StoreSizeVal);
436 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
438 assert(!Dest.isIgnored() && "Must have a destination!");
439 const CXXConstructorDecl *CD = E->getConstructor();
441 // If we require zero initialization before (or instead of) calling the
442 // constructor, as can be the case with a non-user-provided default
443 // constructor, emit the zero initialization now, unless destination is
445 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
446 switch (E->getConstructionKind()) {
447 case CXXConstructExpr::CK_Delegating:
448 case CXXConstructExpr::CK_Complete:
449 EmitNullInitialization(Dest.getAddress(), E->getType());
451 case CXXConstructExpr::CK_VirtualBase:
452 case CXXConstructExpr::CK_NonVirtualBase:
453 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
459 // If this is a call to a trivial default constructor, do nothing.
460 if (CD->isTrivial() && CD->isDefaultConstructor())
463 // Elide the constructor if we're constructing from a temporary.
464 // The temporary check is required because Sema sets this on NRVO
466 if (getLangOpts().ElideConstructors && E->isElidable()) {
467 assert(getContext().hasSameUnqualifiedType(E->getType(),
468 E->getArg(0)->getType()));
469 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
470 EmitAggExpr(E->getArg(0), Dest);
475 if (const ConstantArrayType *arrayType
476 = getContext().getAsConstantArrayType(E->getType())) {
477 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
479 CXXCtorType Type = Ctor_Complete;
480 bool ForVirtualBase = false;
481 bool Delegating = false;
483 switch (E->getConstructionKind()) {
484 case CXXConstructExpr::CK_Delegating:
485 // We should be emitting a constructor; GlobalDecl will assert this
486 Type = CurGD.getCtorType();
490 case CXXConstructExpr::CK_Complete:
491 Type = Ctor_Complete;
494 case CXXConstructExpr::CK_VirtualBase:
495 ForVirtualBase = true;
498 case CXXConstructExpr::CK_NonVirtualBase:
502 // Call the constructor.
503 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
504 Dest.getAddress(), E);
508 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
510 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
511 Exp = E->getSubExpr();
512 assert(isa<CXXConstructExpr>(Exp) &&
513 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
514 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
515 const CXXConstructorDecl *CD = E->getConstructor();
516 RunCleanupsScope Scope(*this);
518 // If we require zero initialization before (or instead of) calling the
519 // constructor, as can be the case with a non-user-provided default
520 // constructor, emit the zero initialization now.
521 // FIXME. Do I still need this for a copy ctor synthesis?
522 if (E->requiresZeroInitialization())
523 EmitNullInitialization(Dest, E->getType());
525 assert(!getContext().getAsConstantArrayType(E->getType())
526 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
527 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
530 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
531 const CXXNewExpr *E) {
533 return CharUnits::Zero();
535 // No cookie is required if the operator new[] being used is the
536 // reserved placement operator new[].
537 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
538 return CharUnits::Zero();
540 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
543 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
545 unsigned minElements,
546 llvm::Value *&numElements,
547 llvm::Value *&sizeWithoutCookie) {
548 QualType type = e->getAllocatedType();
551 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
553 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
554 return sizeWithoutCookie;
557 // The width of size_t.
558 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
560 // Figure out the cookie size.
561 llvm::APInt cookieSize(sizeWidth,
562 CalculateCookiePadding(CGF, e).getQuantity());
564 // Emit the array size expression.
565 // We multiply the size of all dimensions for NumElements.
566 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
567 numElements = CGF.EmitScalarExpr(e->getArraySize());
568 assert(isa<llvm::IntegerType>(numElements->getType()));
570 // The number of elements can be have an arbitrary integer type;
571 // essentially, we need to multiply it by a constant factor, add a
572 // cookie size, and verify that the result is representable as a
573 // size_t. That's just a gloss, though, and it's wrong in one
574 // important way: if the count is negative, it's an error even if
575 // the cookie size would bring the total size >= 0.
577 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
578 llvm::IntegerType *numElementsType
579 = cast<llvm::IntegerType>(numElements->getType());
580 unsigned numElementsWidth = numElementsType->getBitWidth();
582 // Compute the constant factor.
583 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
584 while (const ConstantArrayType *CAT
585 = CGF.getContext().getAsConstantArrayType(type)) {
586 type = CAT->getElementType();
587 arraySizeMultiplier *= CAT->getSize();
590 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
591 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
592 typeSizeMultiplier *= arraySizeMultiplier;
594 // This will be a size_t.
597 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
598 // Don't bloat the -O0 code.
599 if (llvm::ConstantInt *numElementsC =
600 dyn_cast<llvm::ConstantInt>(numElements)) {
601 const llvm::APInt &count = numElementsC->getValue();
603 bool hasAnyOverflow = false;
605 // If 'count' was a negative number, it's an overflow.
606 if (isSigned && count.isNegative())
607 hasAnyOverflow = true;
609 // We want to do all this arithmetic in size_t. If numElements is
610 // wider than that, check whether it's already too big, and if so,
612 else if (numElementsWidth > sizeWidth &&
613 numElementsWidth - sizeWidth > count.countLeadingZeros())
614 hasAnyOverflow = true;
616 // Okay, compute a count at the right width.
617 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
619 // If there is a brace-initializer, we cannot allocate fewer elements than
620 // there are initializers. If we do, that's treated like an overflow.
621 if (adjustedCount.ult(minElements))
622 hasAnyOverflow = true;
624 // Scale numElements by that. This might overflow, but we don't
625 // care because it only overflows if allocationSize does, too, and
626 // if that overflows then we shouldn't use this.
627 numElements = llvm::ConstantInt::get(CGF.SizeTy,
628 adjustedCount * arraySizeMultiplier);
630 // Compute the size before cookie, and track whether it overflowed.
632 llvm::APInt allocationSize
633 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
634 hasAnyOverflow |= overflow;
636 // Add in the cookie, and check whether it's overflowed.
637 if (cookieSize != 0) {
638 // Save the current size without a cookie. This shouldn't be
639 // used if there was overflow.
640 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
642 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
643 hasAnyOverflow |= overflow;
646 // On overflow, produce a -1 so operator new will fail.
647 if (hasAnyOverflow) {
648 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
650 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
653 // Otherwise, we might need to use the overflow intrinsics.
655 // There are up to five conditions we need to test for:
656 // 1) if isSigned, we need to check whether numElements is negative;
657 // 2) if numElementsWidth > sizeWidth, we need to check whether
658 // numElements is larger than something representable in size_t;
659 // 3) if minElements > 0, we need to check whether numElements is smaller
661 // 4) we need to compute
662 // sizeWithoutCookie := numElements * typeSizeMultiplier
663 // and check whether it overflows; and
664 // 5) if we need a cookie, we need to compute
665 // size := sizeWithoutCookie + cookieSize
666 // and check whether it overflows.
668 llvm::Value *hasOverflow = nullptr;
670 // If numElementsWidth > sizeWidth, then one way or another, we're
671 // going to have to do a comparison for (2), and this happens to
672 // take care of (1), too.
673 if (numElementsWidth > sizeWidth) {
674 llvm::APInt threshold(numElementsWidth, 1);
675 threshold <<= sizeWidth;
677 llvm::Value *thresholdV
678 = llvm::ConstantInt::get(numElementsType, threshold);
680 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
681 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
683 // Otherwise, if we're signed, we want to sext up to size_t.
684 } else if (isSigned) {
685 if (numElementsWidth < sizeWidth)
686 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
688 // If there's a non-1 type size multiplier, then we can do the
689 // signedness check at the same time as we do the multiply
690 // because a negative number times anything will cause an
691 // unsigned overflow. Otherwise, we have to do it here. But at least
692 // in this case, we can subsume the >= minElements check.
693 if (typeSizeMultiplier == 1)
694 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
695 llvm::ConstantInt::get(CGF.SizeTy, minElements));
697 // Otherwise, zext up to size_t if necessary.
698 } else if (numElementsWidth < sizeWidth) {
699 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
702 assert(numElements->getType() == CGF.SizeTy);
705 // Don't allow allocation of fewer elements than we have initializers.
707 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
708 llvm::ConstantInt::get(CGF.SizeTy, minElements));
709 } else if (numElementsWidth > sizeWidth) {
710 // The other existing overflow subsumes this check.
711 // We do an unsigned comparison, since any signed value < -1 is
712 // taken care of either above or below.
713 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
714 CGF.Builder.CreateICmpULT(numElements,
715 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
721 // Multiply by the type size if necessary. This multiplier
722 // includes all the factors for nested arrays.
724 // This step also causes numElements to be scaled up by the
725 // nested-array factor if necessary. Overflow on this computation
726 // can be ignored because the result shouldn't be used if
728 if (typeSizeMultiplier != 1) {
729 llvm::Value *umul_with_overflow
730 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
733 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
734 llvm::Value *result =
735 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
737 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
739 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
741 hasOverflow = overflowed;
743 size = CGF.Builder.CreateExtractValue(result, 0);
745 // Also scale up numElements by the array size multiplier.
746 if (arraySizeMultiplier != 1) {
747 // If the base element type size is 1, then we can re-use the
748 // multiply we just did.
749 if (typeSize.isOne()) {
750 assert(arraySizeMultiplier == typeSizeMultiplier);
753 // Otherwise we need a separate multiply.
756 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
757 numElements = CGF.Builder.CreateMul(numElements, asmV);
761 // numElements doesn't need to be scaled.
762 assert(arraySizeMultiplier == 1);
765 // Add in the cookie size if necessary.
766 if (cookieSize != 0) {
767 sizeWithoutCookie = size;
769 llvm::Value *uadd_with_overflow
770 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
772 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
773 llvm::Value *result =
774 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
776 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
778 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
780 hasOverflow = overflowed;
782 size = CGF.Builder.CreateExtractValue(result, 0);
785 // If we had any possibility of dynamic overflow, make a select to
786 // overwrite 'size' with an all-ones value, which should cause
787 // operator new to throw.
789 size = CGF.Builder.CreateSelect(hasOverflow,
790 llvm::Constant::getAllOnesValue(CGF.SizeTy),
795 sizeWithoutCookie = size;
797 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
802 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
803 QualType AllocType, Address NewPtr) {
804 // FIXME: Refactor with EmitExprAsInit.
805 switch (CGF.getEvaluationKind(AllocType)) {
807 CGF.EmitScalarInit(Init, nullptr,
808 CGF.MakeAddrLValue(NewPtr, AllocType), false);
811 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
814 case TEK_Aggregate: {
816 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
817 AggValueSlot::IsDestructed,
818 AggValueSlot::DoesNotNeedGCBarriers,
819 AggValueSlot::IsNotAliased);
820 CGF.EmitAggExpr(Init, Slot);
824 llvm_unreachable("bad evaluation kind");
827 void CodeGenFunction::EmitNewArrayInitializer(
828 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
829 Address BeginPtr, llvm::Value *NumElements,
830 llvm::Value *AllocSizeWithoutCookie) {
831 // If we have a type with trivial initialization and no initializer,
832 // there's nothing to do.
833 if (!E->hasInitializer())
836 Address CurPtr = BeginPtr;
838 unsigned InitListElements = 0;
840 const Expr *Init = E->getInitializer();
841 Address EndOfInit = Address::invalid();
842 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
843 EHScopeStack::stable_iterator Cleanup;
844 llvm::Instruction *CleanupDominator = nullptr;
846 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
847 CharUnits ElementAlign =
848 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
850 // If the initializer is an initializer list, first do the explicit elements.
851 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
852 InitListElements = ILE->getNumInits();
854 // If this is a multi-dimensional array new, we will initialize multiple
855 // elements with each init list element.
856 QualType AllocType = E->getAllocatedType();
857 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
858 AllocType->getAsArrayTypeUnsafe())) {
859 ElementTy = ConvertTypeForMem(AllocType);
860 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
861 InitListElements *= getContext().getConstantArrayElementCount(CAT);
864 // Enter a partial-destruction Cleanup if necessary.
865 if (needsEHCleanup(DtorKind)) {
866 // In principle we could tell the Cleanup where we are more
867 // directly, but the control flow can get so varied here that it
868 // would actually be quite complex. Therefore we go through an
870 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
872 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
873 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
874 ElementType, ElementAlign,
875 getDestroyer(DtorKind));
876 Cleanup = EHStack.stable_begin();
879 CharUnits StartAlign = CurPtr.getAlignment();
880 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
881 // Tell the cleanup that it needs to destroy up to this
882 // element. TODO: some of these stores can be trivially
883 // observed to be unnecessary.
884 if (EndOfInit.isValid()) {
886 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
887 Builder.CreateStore(FinishedPtr, EndOfInit);
889 // FIXME: If the last initializer is an incomplete initializer list for
890 // an array, and we have an array filler, we can fold together the two
891 // initialization loops.
892 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
893 ILE->getInit(i)->getType(), CurPtr);
894 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
897 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
900 // The remaining elements are filled with the array filler expression.
901 Init = ILE->getArrayFiller();
903 // Extract the initializer for the individual array elements by pulling
904 // out the array filler from all the nested initializer lists. This avoids
905 // generating a nested loop for the initialization.
906 while (Init && Init->getType()->isConstantArrayType()) {
907 auto *SubILE = dyn_cast<InitListExpr>(Init);
910 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
911 Init = SubILE->getArrayFiller();
914 // Switch back to initializing one base element at a time.
915 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
918 // Attempt to perform zero-initialization using memset.
919 auto TryMemsetInitialization = [&]() -> bool {
920 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
921 // we can initialize with a memset to -1.
922 if (!CGM.getTypes().isZeroInitializable(ElementType))
925 // Optimization: since zero initialization will just set the memory
926 // to all zeroes, generate a single memset to do it in one shot.
928 // Subtract out the size of any elements we've already initialized.
929 auto *RemainingSize = AllocSizeWithoutCookie;
930 if (InitListElements) {
931 // We know this can't overflow; we check this when doing the allocation.
932 auto *InitializedSize = llvm::ConstantInt::get(
933 RemainingSize->getType(),
934 getContext().getTypeSizeInChars(ElementType).getQuantity() *
936 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
939 // Create the memset.
940 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
944 // If all elements have already been initialized, skip any further
946 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
947 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
948 // If there was a Cleanup, deactivate it.
949 if (CleanupDominator)
950 DeactivateCleanupBlock(Cleanup, CleanupDominator);
954 assert(Init && "have trailing elements to initialize but no initializer");
956 // If this is a constructor call, try to optimize it out, and failing that
957 // emit a single loop to initialize all remaining elements.
958 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
959 CXXConstructorDecl *Ctor = CCE->getConstructor();
960 if (Ctor->isTrivial()) {
961 // If new expression did not specify value-initialization, then there
962 // is no initialization.
963 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
966 if (TryMemsetInitialization())
970 // Store the new Cleanup position for irregular Cleanups.
972 // FIXME: Share this cleanup with the constructor call emission rather than
973 // having it create a cleanup of its own.
974 if (EndOfInit.isValid())
975 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
977 // Emit a constructor call loop to initialize the remaining elements.
978 if (InitListElements)
979 NumElements = Builder.CreateSub(
981 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
982 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
983 CCE->requiresZeroInitialization());
987 // If this is value-initialization, we can usually use memset.
988 ImplicitValueInitExpr IVIE(ElementType);
989 if (isa<ImplicitValueInitExpr>(Init)) {
990 if (TryMemsetInitialization())
993 // Switch to an ImplicitValueInitExpr for the element type. This handles
994 // only one case: multidimensional array new of pointers to members. In
995 // all other cases, we already have an initializer for the array element.
999 // At this point we should have found an initializer for the individual
1000 // elements of the array.
1001 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1002 "got wrong type of element to initialize");
1004 // If we have an empty initializer list, we can usually use memset.
1005 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1006 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1009 // If we have a struct whose every field is value-initialized, we can
1010 // usually use memset.
1011 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1012 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1013 if (RType->getDecl()->isStruct()) {
1014 unsigned NumFields = 0;
1015 for (auto *Field : RType->getDecl()->fields())
1016 if (!Field->isUnnamedBitfield())
1018 if (ILE->getNumInits() == NumFields)
1019 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1020 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1022 if (ILE->getNumInits() == NumFields && TryMemsetInitialization())
1028 // Create the loop blocks.
1029 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1030 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1031 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1033 // Find the end of the array, hoisted out of the loop.
1034 llvm::Value *EndPtr =
1035 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1037 // If the number of elements isn't constant, we have to now check if there is
1038 // anything left to initialize.
1040 llvm::Value *IsEmpty =
1041 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1042 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1048 // Set up the current-element phi.
1049 llvm::PHINode *CurPtrPhi =
1050 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1051 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1053 CurPtr = Address(CurPtrPhi, ElementAlign);
1055 // Store the new Cleanup position for irregular Cleanups.
1056 if (EndOfInit.isValid())
1057 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1059 // Enter a partial-destruction Cleanup if necessary.
1060 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1061 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1062 ElementType, ElementAlign,
1063 getDestroyer(DtorKind));
1064 Cleanup = EHStack.stable_begin();
1065 CleanupDominator = Builder.CreateUnreachable();
1068 // Emit the initializer into this element.
1069 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
1071 // Leave the Cleanup if we entered one.
1072 if (CleanupDominator) {
1073 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1074 CleanupDominator->eraseFromParent();
1077 // Advance to the next element by adjusting the pointer type as necessary.
1078 llvm::Value *NextPtr =
1079 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1082 // Check whether we've gotten to the end of the array and, if so,
1084 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1085 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1086 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1091 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1092 QualType ElementType, llvm::Type *ElementTy,
1093 Address NewPtr, llvm::Value *NumElements,
1094 llvm::Value *AllocSizeWithoutCookie) {
1095 ApplyDebugLocation DL(CGF, E);
1097 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1098 AllocSizeWithoutCookie);
1099 else if (const Expr *Init = E->getInitializer())
1100 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
1103 /// Emit a call to an operator new or operator delete function, as implicitly
1104 /// created by new-expressions and delete-expressions.
1105 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1106 const FunctionDecl *Callee,
1107 const FunctionProtoType *CalleeType,
1108 const CallArgList &Args) {
1109 llvm::Instruction *CallOrInvoke;
1110 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
1112 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1113 Args, CalleeType, /*chainCall=*/false),
1114 CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
1116 /// C++1y [expr.new]p10:
1117 /// [In a new-expression,] an implementation is allowed to omit a call
1118 /// to a replaceable global allocation function.
1120 /// We model such elidable calls with the 'builtin' attribute.
1121 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
1122 if (Callee->isReplaceableGlobalAllocationFunction() &&
1123 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1124 // FIXME: Add addAttribute to CallSite.
1125 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1126 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1127 llvm::Attribute::Builtin);
1128 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1129 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1130 llvm::Attribute::Builtin);
1132 llvm_unreachable("unexpected kind of call instruction");
1138 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1142 const Stmt *ArgS = Arg;
1143 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1144 // Find the allocation or deallocation function that we're calling.
1145 ASTContext &Ctx = getContext();
1146 DeclarationName Name = Ctx.DeclarationNames
1147 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1148 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1149 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1150 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1151 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1152 llvm_unreachable("predeclared global operator new/delete is missing");
1156 /// A cleanup to call the given 'operator delete' function upon
1157 /// abnormal exit from a new expression.
1158 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1159 size_t NumPlacementArgs;
1160 const FunctionDecl *OperatorDelete;
1162 llvm::Value *AllocSize;
1164 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1167 static size_t getExtraSize(size_t NumPlacementArgs) {
1168 return NumPlacementArgs * sizeof(RValue);
1171 CallDeleteDuringNew(size_t NumPlacementArgs,
1172 const FunctionDecl *OperatorDelete,
1174 llvm::Value *AllocSize)
1175 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1176 Ptr(Ptr), AllocSize(AllocSize) {}
1178 void setPlacementArg(unsigned I, RValue Arg) {
1179 assert(I < NumPlacementArgs && "index out of range");
1180 getPlacementArgs()[I] = Arg;
1183 void Emit(CodeGenFunction &CGF, Flags flags) override {
1184 const FunctionProtoType *FPT
1185 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1186 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1187 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1189 CallArgList DeleteArgs;
1191 // The first argument is always a void*.
1192 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
1193 DeleteArgs.add(RValue::get(Ptr), *AI++);
1195 // A member 'operator delete' can take an extra 'size_t' argument.
1196 if (FPT->getNumParams() == NumPlacementArgs + 2)
1197 DeleteArgs.add(RValue::get(AllocSize), *AI++);
1199 // Pass the rest of the arguments, which must match exactly.
1200 for (unsigned I = 0; I != NumPlacementArgs; ++I)
1201 DeleteArgs.add(getPlacementArgs()[I], *AI++);
1203 // Call 'operator delete'.
1204 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1208 /// A cleanup to call the given 'operator delete' function upon
1209 /// abnormal exit from a new expression when the new expression is
1211 class CallDeleteDuringConditionalNew final : public EHScopeStack::Cleanup {
1212 size_t NumPlacementArgs;
1213 const FunctionDecl *OperatorDelete;
1214 DominatingValue<RValue>::saved_type Ptr;
1215 DominatingValue<RValue>::saved_type AllocSize;
1217 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1218 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
1222 static size_t getExtraSize(size_t NumPlacementArgs) {
1223 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
1226 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1227 const FunctionDecl *OperatorDelete,
1228 DominatingValue<RValue>::saved_type Ptr,
1229 DominatingValue<RValue>::saved_type AllocSize)
1230 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1231 Ptr(Ptr), AllocSize(AllocSize) {}
1233 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
1234 assert(I < NumPlacementArgs && "index out of range");
1235 getPlacementArgs()[I] = Arg;
1238 void Emit(CodeGenFunction &CGF, Flags flags) override {
1239 const FunctionProtoType *FPT
1240 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1241 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1242 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1244 CallArgList DeleteArgs;
1246 // The first argument is always a void*.
1247 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
1248 DeleteArgs.add(Ptr.restore(CGF), *AI++);
1250 // A member 'operator delete' can take an extra 'size_t' argument.
1251 if (FPT->getNumParams() == NumPlacementArgs + 2) {
1252 RValue RV = AllocSize.restore(CGF);
1253 DeleteArgs.add(RV, *AI++);
1256 // Pass the rest of the arguments, which must match exactly.
1257 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1258 RValue RV = getPlacementArgs()[I].restore(CGF);
1259 DeleteArgs.add(RV, *AI++);
1262 // Call 'operator delete'.
1263 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1268 /// Enter a cleanup to call 'operator delete' if the initializer in a
1269 /// new-expression throws.
1270 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1271 const CXXNewExpr *E,
1273 llvm::Value *AllocSize,
1274 const CallArgList &NewArgs) {
1275 // If we're not inside a conditional branch, then the cleanup will
1276 // dominate and we can do the easier (and more efficient) thing.
1277 if (!CGF.isInConditionalBranch()) {
1278 CallDeleteDuringNew *Cleanup = CGF.EHStack
1279 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1280 E->getNumPlacementArgs(),
1281 E->getOperatorDelete(),
1282 NewPtr.getPointer(),
1284 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1285 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
1290 // Otherwise, we need to save all this stuff.
1291 DominatingValue<RValue>::saved_type SavedNewPtr =
1292 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1293 DominatingValue<RValue>::saved_type SavedAllocSize =
1294 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1296 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1297 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
1298 E->getNumPlacementArgs(),
1299 E->getOperatorDelete(),
1302 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1303 Cleanup->setPlacementArg(I,
1304 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
1306 CGF.initFullExprCleanup();
1309 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1310 // The element type being allocated.
1311 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1313 // 1. Build a call to the allocation function.
1314 FunctionDecl *allocator = E->getOperatorNew();
1316 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1317 unsigned minElements = 0;
1318 if (E->isArray() && E->hasInitializer()) {
1319 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1320 minElements = ILE->getNumInits();
1323 llvm::Value *numElements = nullptr;
1324 llvm::Value *allocSizeWithoutCookie = nullptr;
1325 llvm::Value *allocSize =
1326 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1327 allocSizeWithoutCookie);
1329 // Emit the allocation call. If the allocator is a global placement
1330 // operator, just "inline" it directly.
1331 Address allocation = Address::invalid();
1332 CallArgList allocatorArgs;
1333 if (allocator->isReservedGlobalPlacementOperator()) {
1334 assert(E->getNumPlacementArgs() == 1);
1335 const Expr *arg = *E->placement_arguments().begin();
1337 AlignmentSource alignSource;
1338 allocation = EmitPointerWithAlignment(arg, &alignSource);
1340 // The pointer expression will, in many cases, be an opaque void*.
1341 // In these cases, discard the computed alignment and use the
1342 // formal alignment of the allocated type.
1343 if (alignSource != AlignmentSource::Decl) {
1344 allocation = Address(allocation.getPointer(),
1345 getContext().getTypeAlignInChars(allocType));
1348 // Set up allocatorArgs for the call to operator delete if it's not
1349 // the reserved global operator.
1350 if (E->getOperatorDelete() &&
1351 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1352 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1353 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1357 const FunctionProtoType *allocatorType =
1358 allocator->getType()->castAs<FunctionProtoType>();
1360 // The allocation size is the first argument.
1361 QualType sizeType = getContext().getSizeType();
1362 allocatorArgs.add(RValue::get(allocSize), sizeType);
1364 // We start at 1 here because the first argument (the allocation size)
1365 // has already been emitted.
1366 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1367 /* CalleeDecl */ nullptr,
1368 /*ParamsToSkip*/ 1);
1371 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1373 // For now, only assume that the allocation function returns
1374 // something satisfactorily aligned for the element type, plus
1375 // the cookie if we have one.
1376 CharUnits allocationAlign =
1377 getContext().getTypeAlignInChars(allocType);
1378 if (allocSize != allocSizeWithoutCookie) {
1379 CharUnits cookieAlign = getSizeAlign(); // FIXME?
1380 allocationAlign = std::max(allocationAlign, cookieAlign);
1383 allocation = Address(RV.getScalarVal(), allocationAlign);
1386 // Emit a null check on the allocation result if the allocation
1387 // function is allowed to return null (because it has a non-throwing
1388 // exception spec or is the reserved placement new) and we have an
1389 // interesting initializer.
1390 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
1391 (!allocType.isPODType(getContext()) || E->hasInitializer());
1393 llvm::BasicBlock *nullCheckBB = nullptr;
1394 llvm::BasicBlock *contBB = nullptr;
1396 // The null-check means that the initializer is conditionally
1398 ConditionalEvaluation conditional(*this);
1401 conditional.begin(*this);
1403 nullCheckBB = Builder.GetInsertBlock();
1404 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1405 contBB = createBasicBlock("new.cont");
1407 llvm::Value *isNull =
1408 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1409 Builder.CreateCondBr(isNull, contBB, notNullBB);
1410 EmitBlock(notNullBB);
1413 // If there's an operator delete, enter a cleanup to call it if an
1414 // exception is thrown.
1415 EHScopeStack::stable_iterator operatorDeleteCleanup;
1416 llvm::Instruction *cleanupDominator = nullptr;
1417 if (E->getOperatorDelete() &&
1418 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1419 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1420 operatorDeleteCleanup = EHStack.stable_begin();
1421 cleanupDominator = Builder.CreateUnreachable();
1424 assert((allocSize == allocSizeWithoutCookie) ==
1425 CalculateCookiePadding(*this, E).isZero());
1426 if (allocSize != allocSizeWithoutCookie) {
1427 assert(E->isArray());
1428 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1433 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1434 Address result = Builder.CreateElementBitCast(allocation, elementTy);
1436 // Passing pointer through invariant.group.barrier to avoid propagation of
1437 // vptrs information which may be included in previous type.
1438 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1439 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1440 allocator->isReservedGlobalPlacementOperator())
1441 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1442 result.getAlignment());
1444 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1445 allocSizeWithoutCookie);
1447 // NewPtr is a pointer to the base element type. If we're
1448 // allocating an array of arrays, we'll need to cast back to the
1449 // array pointer type.
1450 llvm::Type *resultType = ConvertTypeForMem(E->getType());
1451 if (result.getType() != resultType)
1452 result = Builder.CreateBitCast(result, resultType);
1455 // Deactivate the 'operator delete' cleanup if we finished
1457 if (operatorDeleteCleanup.isValid()) {
1458 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1459 cleanupDominator->eraseFromParent();
1462 llvm::Value *resultPtr = result.getPointer();
1464 conditional.end(*this);
1466 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1469 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1470 PHI->addIncoming(resultPtr, notNullBB);
1471 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1480 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1482 QualType DeleteTy) {
1483 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1485 const FunctionProtoType *DeleteFTy =
1486 DeleteFD->getType()->getAs<FunctionProtoType>();
1488 CallArgList DeleteArgs;
1490 // Check if we need to pass the size to the delete operator.
1491 llvm::Value *Size = nullptr;
1493 if (DeleteFTy->getNumParams() == 2) {
1494 SizeTy = DeleteFTy->getParamType(1);
1495 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1496 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1497 DeleteTypeSize.getQuantity());
1500 QualType ArgTy = DeleteFTy->getParamType(0);
1501 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1502 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1505 DeleteArgs.add(RValue::get(Size), SizeTy);
1507 // Emit the call to delete.
1508 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1512 /// Calls the given 'operator delete' on a single object.
1513 struct CallObjectDelete final : EHScopeStack::Cleanup {
1515 const FunctionDecl *OperatorDelete;
1516 QualType ElementType;
1518 CallObjectDelete(llvm::Value *Ptr,
1519 const FunctionDecl *OperatorDelete,
1520 QualType ElementType)
1521 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1523 void Emit(CodeGenFunction &CGF, Flags flags) override {
1524 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1530 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1531 llvm::Value *CompletePtr,
1532 QualType ElementType) {
1533 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1534 OperatorDelete, ElementType);
1537 /// Emit the code for deleting a single object.
1538 static void EmitObjectDelete(CodeGenFunction &CGF,
1539 const CXXDeleteExpr *DE,
1541 QualType ElementType) {
1542 // Find the destructor for the type, if applicable. If the
1543 // destructor is virtual, we'll just emit the vcall and return.
1544 const CXXDestructorDecl *Dtor = nullptr;
1545 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1546 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1547 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1548 Dtor = RD->getDestructor();
1550 if (Dtor->isVirtual()) {
1551 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1558 // Make sure that we call delete even if the dtor throws.
1559 // This doesn't have to a conditional cleanup because we're going
1560 // to pop it off in a second.
1561 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1562 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1564 OperatorDelete, ElementType);
1567 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1568 /*ForVirtualBase=*/false,
1569 /*Delegating=*/false,
1571 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1573 case Qualifiers::OCL_None:
1574 case Qualifiers::OCL_ExplicitNone:
1575 case Qualifiers::OCL_Autoreleasing:
1578 case Qualifiers::OCL_Strong:
1579 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1582 case Qualifiers::OCL_Weak:
1583 CGF.EmitARCDestroyWeak(Ptr);
1588 CGF.PopCleanupBlock();
1592 /// Calls the given 'operator delete' on an array of objects.
1593 struct CallArrayDelete final : EHScopeStack::Cleanup {
1595 const FunctionDecl *OperatorDelete;
1596 llvm::Value *NumElements;
1597 QualType ElementType;
1598 CharUnits CookieSize;
1600 CallArrayDelete(llvm::Value *Ptr,
1601 const FunctionDecl *OperatorDelete,
1602 llvm::Value *NumElements,
1603 QualType ElementType,
1604 CharUnits CookieSize)
1605 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1606 ElementType(ElementType), CookieSize(CookieSize) {}
1608 void Emit(CodeGenFunction &CGF, Flags flags) override {
1609 const FunctionProtoType *DeleteFTy =
1610 OperatorDelete->getType()->getAs<FunctionProtoType>();
1611 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
1615 // Pass the pointer as the first argument.
1616 QualType VoidPtrTy = DeleteFTy->getParamType(0);
1617 llvm::Value *DeletePtr
1618 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1619 Args.add(RValue::get(DeletePtr), VoidPtrTy);
1621 // Pass the original requested size as the second argument.
1622 if (DeleteFTy->getNumParams() == 2) {
1623 QualType size_t = DeleteFTy->getParamType(1);
1624 llvm::IntegerType *SizeTy
1625 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1627 CharUnits ElementTypeSize =
1628 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1630 // The size of an element, multiplied by the number of elements.
1632 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1634 Size = CGF.Builder.CreateMul(Size, NumElements);
1636 // Plus the size of the cookie if applicable.
1637 if (!CookieSize.isZero()) {
1638 llvm::Value *CookieSizeV
1639 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1640 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1643 Args.add(RValue::get(Size), size_t);
1646 // Emit the call to delete.
1647 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
1652 /// Emit the code for deleting an array of objects.
1653 static void EmitArrayDelete(CodeGenFunction &CGF,
1654 const CXXDeleteExpr *E,
1656 QualType elementType) {
1657 llvm::Value *numElements = nullptr;
1658 llvm::Value *allocatedPtr = nullptr;
1659 CharUnits cookieSize;
1660 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1661 numElements, allocatedPtr, cookieSize);
1663 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
1665 // Make sure that we call delete even if one of the dtors throws.
1666 const FunctionDecl *operatorDelete = E->getOperatorDelete();
1667 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1668 allocatedPtr, operatorDelete,
1669 numElements, elementType,
1672 // Destroy the elements.
1673 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1674 assert(numElements && "no element count for a type with a destructor!");
1676 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1677 CharUnits elementAlign =
1678 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1680 llvm::Value *arrayBegin = deletedPtr.getPointer();
1681 llvm::Value *arrayEnd =
1682 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
1684 // Note that it is legal to allocate a zero-length array, and we
1685 // can never fold the check away because the length should always
1686 // come from a cookie.
1687 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1688 CGF.getDestroyer(dtorKind),
1689 /*checkZeroLength*/ true,
1690 CGF.needsEHCleanup(dtorKind));
1693 // Pop the cleanup block.
1694 CGF.PopCleanupBlock();
1697 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1698 const Expr *Arg = E->getArgument();
1699 Address Ptr = EmitPointerWithAlignment(Arg);
1701 // Null check the pointer.
1702 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1703 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1705 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
1707 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1708 EmitBlock(DeleteNotNull);
1710 // We might be deleting a pointer to array. If so, GEP down to the
1711 // first non-array element.
1712 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1713 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1714 if (DeleteTy->isConstantArrayType()) {
1715 llvm::Value *Zero = Builder.getInt32(0);
1716 SmallVector<llvm::Value*,8> GEP;
1718 GEP.push_back(Zero); // point at the outermost array
1720 // For each layer of array type we're pointing at:
1721 while (const ConstantArrayType *Arr
1722 = getContext().getAsConstantArrayType(DeleteTy)) {
1723 // 1. Unpeel the array type.
1724 DeleteTy = Arr->getElementType();
1726 // 2. GEP to the first element of the array.
1727 GEP.push_back(Zero);
1730 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
1731 Ptr.getAlignment());
1734 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
1736 if (E->isArrayForm()) {
1737 EmitArrayDelete(*this, E, Ptr, DeleteTy);
1739 EmitObjectDelete(*this, E, Ptr, DeleteTy);
1742 EmitBlock(DeleteEnd);
1745 static bool isGLValueFromPointerDeref(const Expr *E) {
1746 E = E->IgnoreParens();
1748 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1749 if (!CE->getSubExpr()->isGLValue())
1751 return isGLValueFromPointerDeref(CE->getSubExpr());
1754 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1755 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1757 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1758 if (BO->getOpcode() == BO_Comma)
1759 return isGLValueFromPointerDeref(BO->getRHS());
1761 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1762 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1763 isGLValueFromPointerDeref(ACO->getFalseExpr());
1765 // C++11 [expr.sub]p1:
1766 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1767 if (isa<ArraySubscriptExpr>(E))
1770 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1771 if (UO->getOpcode() == UO_Deref)
1777 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
1778 llvm::Type *StdTypeInfoPtrTy) {
1779 // Get the vtable pointer.
1780 Address ThisPtr = CGF.EmitLValue(E).getAddress();
1782 // C++ [expr.typeid]p2:
1783 // If the glvalue expression is obtained by applying the unary * operator to
1784 // a pointer and the pointer is a null pointer value, the typeid expression
1785 // throws the std::bad_typeid exception.
1787 // However, this paragraph's intent is not clear. We choose a very generous
1788 // interpretation which implores us to consider comma operators, conditional
1789 // operators, parentheses and other such constructs.
1790 QualType SrcRecordTy = E->getType();
1791 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1792 isGLValueFromPointerDeref(E), SrcRecordTy)) {
1793 llvm::BasicBlock *BadTypeidBlock =
1794 CGF.createBasicBlock("typeid.bad_typeid");
1795 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1797 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
1798 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1800 CGF.EmitBlock(BadTypeidBlock);
1801 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1802 CGF.EmitBlock(EndBlock);
1805 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1809 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1810 llvm::Type *StdTypeInfoPtrTy =
1811 ConvertType(E->getType())->getPointerTo();
1813 if (E->isTypeOperand()) {
1814 llvm::Constant *TypeInfo =
1815 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1816 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
1819 // C++ [expr.typeid]p2:
1820 // When typeid is applied to a glvalue expression whose type is a
1821 // polymorphic class type, the result refers to a std::type_info object
1822 // representing the type of the most derived object (that is, the dynamic
1823 // type) to which the glvalue refers.
1824 if (E->isPotentiallyEvaluated())
1825 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1828 QualType OperandTy = E->getExprOperand()->getType();
1829 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1833 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1835 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1836 if (DestTy->isPointerType())
1837 return llvm::Constant::getNullValue(DestLTy);
1839 /// C++ [expr.dynamic.cast]p9:
1840 /// A failed cast to reference type throws std::bad_cast
1841 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1844 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1845 return llvm::UndefValue::get(DestLTy);
1848 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
1849 const CXXDynamicCastExpr *DCE) {
1850 CGM.EmitExplicitCastExprType(DCE, this);
1851 QualType DestTy = DCE->getTypeAsWritten();
1853 if (DCE->isAlwaysNull())
1854 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1857 QualType SrcTy = DCE->getSubExpr()->getType();
1859 // C++ [expr.dynamic.cast]p7:
1860 // If T is "pointer to cv void," then the result is a pointer to the most
1861 // derived object pointed to by v.
1862 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1864 bool isDynamicCastToVoid;
1865 QualType SrcRecordTy;
1866 QualType DestRecordTy;
1868 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1869 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1870 DestRecordTy = DestPTy->getPointeeType();
1872 isDynamicCastToVoid = false;
1873 SrcRecordTy = SrcTy;
1874 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1877 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1879 // C++ [expr.dynamic.cast]p4:
1880 // If the value of v is a null pointer value in the pointer case, the result
1881 // is the null pointer value of type T.
1882 bool ShouldNullCheckSrcValue =
1883 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1886 llvm::BasicBlock *CastNull = nullptr;
1887 llvm::BasicBlock *CastNotNull = nullptr;
1888 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1890 if (ShouldNullCheckSrcValue) {
1891 CastNull = createBasicBlock("dynamic_cast.null");
1892 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1894 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
1895 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1896 EmitBlock(CastNotNull);
1900 if (isDynamicCastToVoid) {
1901 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
1904 assert(DestRecordTy->isRecordType() &&
1905 "destination type must be a record type!");
1906 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
1907 DestTy, DestRecordTy, CastEnd);
1908 CastNotNull = Builder.GetInsertBlock();
1911 if (ShouldNullCheckSrcValue) {
1912 EmitBranch(CastEnd);
1914 EmitBlock(CastNull);
1915 EmitBranch(CastEnd);
1920 if (ShouldNullCheckSrcValue) {
1921 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1922 PHI->addIncoming(Value, CastNotNull);
1923 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1931 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
1932 RunCleanupsScope Scope(*this);
1933 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
1935 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1936 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
1937 e = E->capture_init_end();
1938 i != e; ++i, ++CurField) {
1939 // Emit initialization
1940 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
1941 if (CurField->hasCapturedVLAType()) {
1942 auto VAT = CurField->getCapturedVLAType();
1943 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1945 ArrayRef<VarDecl *> ArrayIndexes;
1946 if (CurField->getType()->isArrayType())
1947 ArrayIndexes = E->getCaptureInitIndexVars(i);
1948 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);