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, VTable, CFITCK_NVCall, CE->getLocStart());
265 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
266 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
267 else if (!DevirtualizedMethod)
268 Callee = CGM.GetAddrOfFunction(MD, Ty);
270 Callee = CGM.GetAddrOfFunction(DevirtualizedMethod, Ty);
274 if (MD->isVirtual()) {
275 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
276 *this, MD, This, UseVirtualCall);
279 return EmitCXXMemberOrOperatorCall(MD, Callee, ReturnValue, This.getPointer(),
280 /*ImplicitParam=*/nullptr, QualType(), CE);
284 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
285 ReturnValueSlot ReturnValue) {
286 const BinaryOperator *BO =
287 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
288 const Expr *BaseExpr = BO->getLHS();
289 const Expr *MemFnExpr = BO->getRHS();
291 const MemberPointerType *MPT =
292 MemFnExpr->getType()->castAs<MemberPointerType>();
294 const FunctionProtoType *FPT =
295 MPT->getPointeeType()->castAs<FunctionProtoType>();
296 const CXXRecordDecl *RD =
297 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
299 // Get the member function pointer.
300 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
302 // Emit the 'this' pointer.
303 Address This = Address::invalid();
304 if (BO->getOpcode() == BO_PtrMemI)
305 This = EmitPointerWithAlignment(BaseExpr);
307 This = EmitLValue(BaseExpr).getAddress();
309 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
310 QualType(MPT->getClass(), 0));
312 // Ask the ABI to load the callee. Note that This is modified.
313 llvm::Value *ThisPtrForCall = nullptr;
314 llvm::Value *Callee =
315 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
316 ThisPtrForCall, MemFnPtr, MPT);
321 getContext().getPointerType(getContext().getTagDeclType(RD));
323 // Push the this ptr.
324 Args.add(RValue::get(ThisPtrForCall), ThisType);
326 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, 1);
328 // And the rest of the call args
329 EmitCallArgs(Args, FPT, E->arguments(), E->getDirectCallee());
330 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required),
331 Callee, ReturnValue, Args);
335 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
336 const CXXMethodDecl *MD,
337 ReturnValueSlot ReturnValue) {
338 assert(MD->isInstance() &&
339 "Trying to emit a member call expr on a static method!");
340 return EmitCXXMemberOrOperatorMemberCallExpr(
341 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
342 /*IsArrow=*/false, E->getArg(0));
345 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
346 ReturnValueSlot ReturnValue) {
347 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
350 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
352 const CXXRecordDecl *Base) {
356 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
358 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
359 CharUnits NVSize = Layout.getNonVirtualSize();
361 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
362 // present, they are initialized by the most derived class before calling the
364 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
365 Stores.emplace_back(CharUnits::Zero(), NVSize);
367 // Each store is split by the existence of a vbptr.
368 CharUnits VBPtrWidth = CGF.getPointerSize();
369 std::vector<CharUnits> VBPtrOffsets =
370 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
371 for (CharUnits VBPtrOffset : VBPtrOffsets) {
372 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
373 CharUnits LastStoreOffset = LastStore.first;
374 CharUnits LastStoreSize = LastStore.second;
376 CharUnits SplitBeforeOffset = LastStoreOffset;
377 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
378 assert(!SplitBeforeSize.isNegative() && "negative store size!");
379 if (!SplitBeforeSize.isZero())
380 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
382 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
383 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
384 assert(!SplitAfterSize.isNegative() && "negative store size!");
385 if (!SplitAfterSize.isZero())
386 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
389 // If the type contains a pointer to data member we can't memset it to zero.
390 // Instead, create a null constant and copy it to the destination.
391 // TODO: there are other patterns besides zero that we can usefully memset,
392 // like -1, which happens to be the pattern used by member-pointers.
393 // TODO: isZeroInitializable can be over-conservative in the case where a
394 // virtual base contains a member pointer.
395 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
396 if (!NullConstantForBase->isNullValue()) {
397 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
398 CGF.CGM.getModule(), NullConstantForBase->getType(),
399 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
400 NullConstantForBase, Twine());
402 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
403 DestPtr.getAlignment());
404 NullVariable->setAlignment(Align.getQuantity());
406 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
408 // Get and call the appropriate llvm.memcpy overload.
409 for (std::pair<CharUnits, CharUnits> Store : Stores) {
410 CharUnits StoreOffset = Store.first;
411 CharUnits StoreSize = Store.second;
412 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
413 CGF.Builder.CreateMemCpy(
414 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
415 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
419 // Otherwise, just memset the whole thing to zero. This is legal
420 // because in LLVM, all default initializers (other than the ones we just
421 // handled above) are guaranteed to have a bit pattern of all zeros.
423 for (std::pair<CharUnits, CharUnits> Store : Stores) {
424 CharUnits StoreOffset = Store.first;
425 CharUnits StoreSize = Store.second;
426 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
427 CGF.Builder.CreateMemSet(
428 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
429 CGF.Builder.getInt8(0), StoreSizeVal);
435 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
437 assert(!Dest.isIgnored() && "Must have a destination!");
438 const CXXConstructorDecl *CD = E->getConstructor();
440 // If we require zero initialization before (or instead of) calling the
441 // constructor, as can be the case with a non-user-provided default
442 // constructor, emit the zero initialization now, unless destination is
444 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
445 switch (E->getConstructionKind()) {
446 case CXXConstructExpr::CK_Delegating:
447 case CXXConstructExpr::CK_Complete:
448 EmitNullInitialization(Dest.getAddress(), E->getType());
450 case CXXConstructExpr::CK_VirtualBase:
451 case CXXConstructExpr::CK_NonVirtualBase:
452 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
458 // If this is a call to a trivial default constructor, do nothing.
459 if (CD->isTrivial() && CD->isDefaultConstructor())
462 // Elide the constructor if we're constructing from a temporary.
463 // The temporary check is required because Sema sets this on NRVO
465 if (getLangOpts().ElideConstructors && E->isElidable()) {
466 assert(getContext().hasSameUnqualifiedType(E->getType(),
467 E->getArg(0)->getType()));
468 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
469 EmitAggExpr(E->getArg(0), Dest);
474 if (const ConstantArrayType *arrayType
475 = getContext().getAsConstantArrayType(E->getType())) {
476 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
478 CXXCtorType Type = Ctor_Complete;
479 bool ForVirtualBase = false;
480 bool Delegating = false;
482 switch (E->getConstructionKind()) {
483 case CXXConstructExpr::CK_Delegating:
484 // We should be emitting a constructor; GlobalDecl will assert this
485 Type = CurGD.getCtorType();
489 case CXXConstructExpr::CK_Complete:
490 Type = Ctor_Complete;
493 case CXXConstructExpr::CK_VirtualBase:
494 ForVirtualBase = true;
497 case CXXConstructExpr::CK_NonVirtualBase:
501 // Call the constructor.
502 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
503 Dest.getAddress(), E);
507 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
509 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
510 Exp = E->getSubExpr();
511 assert(isa<CXXConstructExpr>(Exp) &&
512 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
513 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
514 const CXXConstructorDecl *CD = E->getConstructor();
515 RunCleanupsScope Scope(*this);
517 // If we require zero initialization before (or instead of) calling the
518 // constructor, as can be the case with a non-user-provided default
519 // constructor, emit the zero initialization now.
520 // FIXME. Do I still need this for a copy ctor synthesis?
521 if (E->requiresZeroInitialization())
522 EmitNullInitialization(Dest, E->getType());
524 assert(!getContext().getAsConstantArrayType(E->getType())
525 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
526 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
529 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
530 const CXXNewExpr *E) {
532 return CharUnits::Zero();
534 // No cookie is required if the operator new[] being used is the
535 // reserved placement operator new[].
536 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
537 return CharUnits::Zero();
539 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
542 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
544 unsigned minElements,
545 llvm::Value *&numElements,
546 llvm::Value *&sizeWithoutCookie) {
547 QualType type = e->getAllocatedType();
550 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
552 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
553 return sizeWithoutCookie;
556 // The width of size_t.
557 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
559 // Figure out the cookie size.
560 llvm::APInt cookieSize(sizeWidth,
561 CalculateCookiePadding(CGF, e).getQuantity());
563 // Emit the array size expression.
564 // We multiply the size of all dimensions for NumElements.
565 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
566 numElements = CGF.EmitScalarExpr(e->getArraySize());
567 assert(isa<llvm::IntegerType>(numElements->getType()));
569 // The number of elements can be have an arbitrary integer type;
570 // essentially, we need to multiply it by a constant factor, add a
571 // cookie size, and verify that the result is representable as a
572 // size_t. That's just a gloss, though, and it's wrong in one
573 // important way: if the count is negative, it's an error even if
574 // the cookie size would bring the total size >= 0.
576 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
577 llvm::IntegerType *numElementsType
578 = cast<llvm::IntegerType>(numElements->getType());
579 unsigned numElementsWidth = numElementsType->getBitWidth();
581 // Compute the constant factor.
582 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
583 while (const ConstantArrayType *CAT
584 = CGF.getContext().getAsConstantArrayType(type)) {
585 type = CAT->getElementType();
586 arraySizeMultiplier *= CAT->getSize();
589 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
590 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
591 typeSizeMultiplier *= arraySizeMultiplier;
593 // This will be a size_t.
596 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
597 // Don't bloat the -O0 code.
598 if (llvm::ConstantInt *numElementsC =
599 dyn_cast<llvm::ConstantInt>(numElements)) {
600 const llvm::APInt &count = numElementsC->getValue();
602 bool hasAnyOverflow = false;
604 // If 'count' was a negative number, it's an overflow.
605 if (isSigned && count.isNegative())
606 hasAnyOverflow = true;
608 // We want to do all this arithmetic in size_t. If numElements is
609 // wider than that, check whether it's already too big, and if so,
611 else if (numElementsWidth > sizeWidth &&
612 numElementsWidth - sizeWidth > count.countLeadingZeros())
613 hasAnyOverflow = true;
615 // Okay, compute a count at the right width.
616 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
618 // If there is a brace-initializer, we cannot allocate fewer elements than
619 // there are initializers. If we do, that's treated like an overflow.
620 if (adjustedCount.ult(minElements))
621 hasAnyOverflow = true;
623 // Scale numElements by that. This might overflow, but we don't
624 // care because it only overflows if allocationSize does, too, and
625 // if that overflows then we shouldn't use this.
626 numElements = llvm::ConstantInt::get(CGF.SizeTy,
627 adjustedCount * arraySizeMultiplier);
629 // Compute the size before cookie, and track whether it overflowed.
631 llvm::APInt allocationSize
632 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
633 hasAnyOverflow |= overflow;
635 // Add in the cookie, and check whether it's overflowed.
636 if (cookieSize != 0) {
637 // Save the current size without a cookie. This shouldn't be
638 // used if there was overflow.
639 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
641 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
642 hasAnyOverflow |= overflow;
645 // On overflow, produce a -1 so operator new will fail.
646 if (hasAnyOverflow) {
647 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
649 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
652 // Otherwise, we might need to use the overflow intrinsics.
654 // There are up to five conditions we need to test for:
655 // 1) if isSigned, we need to check whether numElements is negative;
656 // 2) if numElementsWidth > sizeWidth, we need to check whether
657 // numElements is larger than something representable in size_t;
658 // 3) if minElements > 0, we need to check whether numElements is smaller
660 // 4) we need to compute
661 // sizeWithoutCookie := numElements * typeSizeMultiplier
662 // and check whether it overflows; and
663 // 5) if we need a cookie, we need to compute
664 // size := sizeWithoutCookie + cookieSize
665 // and check whether it overflows.
667 llvm::Value *hasOverflow = nullptr;
669 // If numElementsWidth > sizeWidth, then one way or another, we're
670 // going to have to do a comparison for (2), and this happens to
671 // take care of (1), too.
672 if (numElementsWidth > sizeWidth) {
673 llvm::APInt threshold(numElementsWidth, 1);
674 threshold <<= sizeWidth;
676 llvm::Value *thresholdV
677 = llvm::ConstantInt::get(numElementsType, threshold);
679 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
680 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
682 // Otherwise, if we're signed, we want to sext up to size_t.
683 } else if (isSigned) {
684 if (numElementsWidth < sizeWidth)
685 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
687 // If there's a non-1 type size multiplier, then we can do the
688 // signedness check at the same time as we do the multiply
689 // because a negative number times anything will cause an
690 // unsigned overflow. Otherwise, we have to do it here. But at least
691 // in this case, we can subsume the >= minElements check.
692 if (typeSizeMultiplier == 1)
693 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
694 llvm::ConstantInt::get(CGF.SizeTy, minElements));
696 // Otherwise, zext up to size_t if necessary.
697 } else if (numElementsWidth < sizeWidth) {
698 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
701 assert(numElements->getType() == CGF.SizeTy);
704 // Don't allow allocation of fewer elements than we have initializers.
706 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
707 llvm::ConstantInt::get(CGF.SizeTy, minElements));
708 } else if (numElementsWidth > sizeWidth) {
709 // The other existing overflow subsumes this check.
710 // We do an unsigned comparison, since any signed value < -1 is
711 // taken care of either above or below.
712 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
713 CGF.Builder.CreateICmpULT(numElements,
714 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
720 // Multiply by the type size if necessary. This multiplier
721 // includes all the factors for nested arrays.
723 // This step also causes numElements to be scaled up by the
724 // nested-array factor if necessary. Overflow on this computation
725 // can be ignored because the result shouldn't be used if
727 if (typeSizeMultiplier != 1) {
728 llvm::Value *umul_with_overflow
729 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
732 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
733 llvm::Value *result =
734 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
736 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
738 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
740 hasOverflow = overflowed;
742 size = CGF.Builder.CreateExtractValue(result, 0);
744 // Also scale up numElements by the array size multiplier.
745 if (arraySizeMultiplier != 1) {
746 // If the base element type size is 1, then we can re-use the
747 // multiply we just did.
748 if (typeSize.isOne()) {
749 assert(arraySizeMultiplier == typeSizeMultiplier);
752 // Otherwise we need a separate multiply.
755 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
756 numElements = CGF.Builder.CreateMul(numElements, asmV);
760 // numElements doesn't need to be scaled.
761 assert(arraySizeMultiplier == 1);
764 // Add in the cookie size if necessary.
765 if (cookieSize != 0) {
766 sizeWithoutCookie = size;
768 llvm::Value *uadd_with_overflow
769 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
771 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
772 llvm::Value *result =
773 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
775 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
777 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
779 hasOverflow = overflowed;
781 size = CGF.Builder.CreateExtractValue(result, 0);
784 // If we had any possibility of dynamic overflow, make a select to
785 // overwrite 'size' with an all-ones value, which should cause
786 // operator new to throw.
788 size = CGF.Builder.CreateSelect(hasOverflow,
789 llvm::Constant::getAllOnesValue(CGF.SizeTy),
794 sizeWithoutCookie = size;
796 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
801 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
802 QualType AllocType, Address NewPtr) {
803 // FIXME: Refactor with EmitExprAsInit.
804 switch (CGF.getEvaluationKind(AllocType)) {
806 CGF.EmitScalarInit(Init, nullptr,
807 CGF.MakeAddrLValue(NewPtr, AllocType), false);
810 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
813 case TEK_Aggregate: {
815 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
816 AggValueSlot::IsDestructed,
817 AggValueSlot::DoesNotNeedGCBarriers,
818 AggValueSlot::IsNotAliased);
819 CGF.EmitAggExpr(Init, Slot);
823 llvm_unreachable("bad evaluation kind");
826 void CodeGenFunction::EmitNewArrayInitializer(
827 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
828 Address BeginPtr, llvm::Value *NumElements,
829 llvm::Value *AllocSizeWithoutCookie) {
830 // If we have a type with trivial initialization and no initializer,
831 // there's nothing to do.
832 if (!E->hasInitializer())
835 Address CurPtr = BeginPtr;
837 unsigned InitListElements = 0;
839 const Expr *Init = E->getInitializer();
840 Address EndOfInit = Address::invalid();
841 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
842 EHScopeStack::stable_iterator Cleanup;
843 llvm::Instruction *CleanupDominator = nullptr;
845 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
846 CharUnits ElementAlign =
847 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
849 // If the initializer is an initializer list, first do the explicit elements.
850 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
851 InitListElements = ILE->getNumInits();
853 // If this is a multi-dimensional array new, we will initialize multiple
854 // elements with each init list element.
855 QualType AllocType = E->getAllocatedType();
856 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
857 AllocType->getAsArrayTypeUnsafe())) {
858 ElementTy = ConvertTypeForMem(AllocType);
859 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
860 InitListElements *= getContext().getConstantArrayElementCount(CAT);
863 // Enter a partial-destruction Cleanup if necessary.
864 if (needsEHCleanup(DtorKind)) {
865 // In principle we could tell the Cleanup where we are more
866 // directly, but the control flow can get so varied here that it
867 // would actually be quite complex. Therefore we go through an
869 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
871 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
872 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
873 ElementType, ElementAlign,
874 getDestroyer(DtorKind));
875 Cleanup = EHStack.stable_begin();
878 CharUnits StartAlign = CurPtr.getAlignment();
879 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
880 // Tell the cleanup that it needs to destroy up to this
881 // element. TODO: some of these stores can be trivially
882 // observed to be unnecessary.
883 if (EndOfInit.isValid()) {
885 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
886 Builder.CreateStore(FinishedPtr, EndOfInit);
888 // FIXME: If the last initializer is an incomplete initializer list for
889 // an array, and we have an array filler, we can fold together the two
890 // initialization loops.
891 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
892 ILE->getInit(i)->getType(), CurPtr);
893 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
896 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
899 // The remaining elements are filled with the array filler expression.
900 Init = ILE->getArrayFiller();
902 // Extract the initializer for the individual array elements by pulling
903 // out the array filler from all the nested initializer lists. This avoids
904 // generating a nested loop for the initialization.
905 while (Init && Init->getType()->isConstantArrayType()) {
906 auto *SubILE = dyn_cast<InitListExpr>(Init);
909 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
910 Init = SubILE->getArrayFiller();
913 // Switch back to initializing one base element at a time.
914 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
917 // Attempt to perform zero-initialization using memset.
918 auto TryMemsetInitialization = [&]() -> bool {
919 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
920 // we can initialize with a memset to -1.
921 if (!CGM.getTypes().isZeroInitializable(ElementType))
924 // Optimization: since zero initialization will just set the memory
925 // to all zeroes, generate a single memset to do it in one shot.
927 // Subtract out the size of any elements we've already initialized.
928 auto *RemainingSize = AllocSizeWithoutCookie;
929 if (InitListElements) {
930 // We know this can't overflow; we check this when doing the allocation.
931 auto *InitializedSize = llvm::ConstantInt::get(
932 RemainingSize->getType(),
933 getContext().getTypeSizeInChars(ElementType).getQuantity() *
935 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
938 // Create the memset.
939 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
943 // If all elements have already been initialized, skip any further
945 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
946 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
947 // If there was a Cleanup, deactivate it.
948 if (CleanupDominator)
949 DeactivateCleanupBlock(Cleanup, CleanupDominator);
953 assert(Init && "have trailing elements to initialize but no initializer");
955 // If this is a constructor call, try to optimize it out, and failing that
956 // emit a single loop to initialize all remaining elements.
957 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
958 CXXConstructorDecl *Ctor = CCE->getConstructor();
959 if (Ctor->isTrivial()) {
960 // If new expression did not specify value-initialization, then there
961 // is no initialization.
962 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
965 if (TryMemsetInitialization())
969 // Store the new Cleanup position for irregular Cleanups.
971 // FIXME: Share this cleanup with the constructor call emission rather than
972 // having it create a cleanup of its own.
973 if (EndOfInit.isValid())
974 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
976 // Emit a constructor call loop to initialize the remaining elements.
977 if (InitListElements)
978 NumElements = Builder.CreateSub(
980 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
981 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
982 CCE->requiresZeroInitialization());
986 // If this is value-initialization, we can usually use memset.
987 ImplicitValueInitExpr IVIE(ElementType);
988 if (isa<ImplicitValueInitExpr>(Init)) {
989 if (TryMemsetInitialization())
992 // Switch to an ImplicitValueInitExpr for the element type. This handles
993 // only one case: multidimensional array new of pointers to members. In
994 // all other cases, we already have an initializer for the array element.
998 // At this point we should have found an initializer for the individual
999 // elements of the array.
1000 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1001 "got wrong type of element to initialize");
1003 // If we have an empty initializer list, we can usually use memset.
1004 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1005 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1008 // If we have a struct whose every field is value-initialized, we can
1009 // usually use memset.
1010 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1011 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1012 if (RType->getDecl()->isStruct()) {
1013 unsigned NumFields = 0;
1014 for (auto *Field : RType->getDecl()->fields())
1015 if (!Field->isUnnamedBitfield())
1017 if (ILE->getNumInits() == NumFields)
1018 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1019 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1021 if (ILE->getNumInits() == NumFields && TryMemsetInitialization())
1027 // Create the loop blocks.
1028 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1029 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1030 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1032 // Find the end of the array, hoisted out of the loop.
1033 llvm::Value *EndPtr =
1034 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1036 // If the number of elements isn't constant, we have to now check if there is
1037 // anything left to initialize.
1039 llvm::Value *IsEmpty =
1040 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1041 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1047 // Set up the current-element phi.
1048 llvm::PHINode *CurPtrPhi =
1049 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1050 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1052 CurPtr = Address(CurPtrPhi, ElementAlign);
1054 // Store the new Cleanup position for irregular Cleanups.
1055 if (EndOfInit.isValid())
1056 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1058 // Enter a partial-destruction Cleanup if necessary.
1059 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1060 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1061 ElementType, ElementAlign,
1062 getDestroyer(DtorKind));
1063 Cleanup = EHStack.stable_begin();
1064 CleanupDominator = Builder.CreateUnreachable();
1067 // Emit the initializer into this element.
1068 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
1070 // Leave the Cleanup if we entered one.
1071 if (CleanupDominator) {
1072 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1073 CleanupDominator->eraseFromParent();
1076 // Advance to the next element by adjusting the pointer type as necessary.
1077 llvm::Value *NextPtr =
1078 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1081 // Check whether we've gotten to the end of the array and, if so,
1083 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1084 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1085 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1090 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1091 QualType ElementType, llvm::Type *ElementTy,
1092 Address NewPtr, llvm::Value *NumElements,
1093 llvm::Value *AllocSizeWithoutCookie) {
1094 ApplyDebugLocation DL(CGF, E);
1096 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1097 AllocSizeWithoutCookie);
1098 else if (const Expr *Init = E->getInitializer())
1099 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
1102 /// Emit a call to an operator new or operator delete function, as implicitly
1103 /// created by new-expressions and delete-expressions.
1104 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1105 const FunctionDecl *Callee,
1106 const FunctionProtoType *CalleeType,
1107 const CallArgList &Args) {
1108 llvm::Instruction *CallOrInvoke;
1109 llvm::Value *CalleeAddr = CGF.CGM.GetAddrOfFunction(Callee);
1111 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1112 Args, CalleeType, /*chainCall=*/false),
1113 CalleeAddr, ReturnValueSlot(), Args, Callee, &CallOrInvoke);
1115 /// C++1y [expr.new]p10:
1116 /// [In a new-expression,] an implementation is allowed to omit a call
1117 /// to a replaceable global allocation function.
1119 /// We model such elidable calls with the 'builtin' attribute.
1120 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleeAddr);
1121 if (Callee->isReplaceableGlobalAllocationFunction() &&
1122 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1123 // FIXME: Add addAttribute to CallSite.
1124 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1125 CI->addAttribute(llvm::AttributeSet::FunctionIndex,
1126 llvm::Attribute::Builtin);
1127 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1128 II->addAttribute(llvm::AttributeSet::FunctionIndex,
1129 llvm::Attribute::Builtin);
1131 llvm_unreachable("unexpected kind of call instruction");
1137 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1141 const Stmt *ArgS = Arg;
1142 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1143 // Find the allocation or deallocation function that we're calling.
1144 ASTContext &Ctx = getContext();
1145 DeclarationName Name = Ctx.DeclarationNames
1146 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1147 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1148 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1149 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1150 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1151 llvm_unreachable("predeclared global operator new/delete is missing");
1155 /// A cleanup to call the given 'operator delete' function upon
1156 /// abnormal exit from a new expression.
1157 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1158 size_t NumPlacementArgs;
1159 const FunctionDecl *OperatorDelete;
1161 llvm::Value *AllocSize;
1163 RValue *getPlacementArgs() { return reinterpret_cast<RValue*>(this+1); }
1166 static size_t getExtraSize(size_t NumPlacementArgs) {
1167 return NumPlacementArgs * sizeof(RValue);
1170 CallDeleteDuringNew(size_t NumPlacementArgs,
1171 const FunctionDecl *OperatorDelete,
1173 llvm::Value *AllocSize)
1174 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1175 Ptr(Ptr), AllocSize(AllocSize) {}
1177 void setPlacementArg(unsigned I, RValue Arg) {
1178 assert(I < NumPlacementArgs && "index out of range");
1179 getPlacementArgs()[I] = Arg;
1182 void Emit(CodeGenFunction &CGF, Flags flags) override {
1183 const FunctionProtoType *FPT
1184 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1185 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1186 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1188 CallArgList DeleteArgs;
1190 // The first argument is always a void*.
1191 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
1192 DeleteArgs.add(RValue::get(Ptr), *AI++);
1194 // A member 'operator delete' can take an extra 'size_t' argument.
1195 if (FPT->getNumParams() == NumPlacementArgs + 2)
1196 DeleteArgs.add(RValue::get(AllocSize), *AI++);
1198 // Pass the rest of the arguments, which must match exactly.
1199 for (unsigned I = 0; I != NumPlacementArgs; ++I)
1200 DeleteArgs.add(getPlacementArgs()[I], *AI++);
1202 // Call 'operator delete'.
1203 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1207 /// A cleanup to call the given 'operator delete' function upon
1208 /// abnormal exit from a new expression when the new expression is
1210 class CallDeleteDuringConditionalNew final : public EHScopeStack::Cleanup {
1211 size_t NumPlacementArgs;
1212 const FunctionDecl *OperatorDelete;
1213 DominatingValue<RValue>::saved_type Ptr;
1214 DominatingValue<RValue>::saved_type AllocSize;
1216 DominatingValue<RValue>::saved_type *getPlacementArgs() {
1217 return reinterpret_cast<DominatingValue<RValue>::saved_type*>(this+1);
1221 static size_t getExtraSize(size_t NumPlacementArgs) {
1222 return NumPlacementArgs * sizeof(DominatingValue<RValue>::saved_type);
1225 CallDeleteDuringConditionalNew(size_t NumPlacementArgs,
1226 const FunctionDecl *OperatorDelete,
1227 DominatingValue<RValue>::saved_type Ptr,
1228 DominatingValue<RValue>::saved_type AllocSize)
1229 : NumPlacementArgs(NumPlacementArgs), OperatorDelete(OperatorDelete),
1230 Ptr(Ptr), AllocSize(AllocSize) {}
1232 void setPlacementArg(unsigned I, DominatingValue<RValue>::saved_type Arg) {
1233 assert(I < NumPlacementArgs && "index out of range");
1234 getPlacementArgs()[I] = Arg;
1237 void Emit(CodeGenFunction &CGF, Flags flags) override {
1238 const FunctionProtoType *FPT
1239 = OperatorDelete->getType()->getAs<FunctionProtoType>();
1240 assert(FPT->getNumParams() == NumPlacementArgs + 1 ||
1241 (FPT->getNumParams() == 2 && NumPlacementArgs == 0));
1243 CallArgList DeleteArgs;
1245 // The first argument is always a void*.
1246 FunctionProtoType::param_type_iterator AI = FPT->param_type_begin();
1247 DeleteArgs.add(Ptr.restore(CGF), *AI++);
1249 // A member 'operator delete' can take an extra 'size_t' argument.
1250 if (FPT->getNumParams() == NumPlacementArgs + 2) {
1251 RValue RV = AllocSize.restore(CGF);
1252 DeleteArgs.add(RV, *AI++);
1255 // Pass the rest of the arguments, which must match exactly.
1256 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1257 RValue RV = getPlacementArgs()[I].restore(CGF);
1258 DeleteArgs.add(RV, *AI++);
1261 // Call 'operator delete'.
1262 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1267 /// Enter a cleanup to call 'operator delete' if the initializer in a
1268 /// new-expression throws.
1269 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1270 const CXXNewExpr *E,
1272 llvm::Value *AllocSize,
1273 const CallArgList &NewArgs) {
1274 // If we're not inside a conditional branch, then the cleanup will
1275 // dominate and we can do the easier (and more efficient) thing.
1276 if (!CGF.isInConditionalBranch()) {
1277 CallDeleteDuringNew *Cleanup = CGF.EHStack
1278 .pushCleanupWithExtra<CallDeleteDuringNew>(EHCleanup,
1279 E->getNumPlacementArgs(),
1280 E->getOperatorDelete(),
1281 NewPtr.getPointer(),
1283 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1284 Cleanup->setPlacementArg(I, NewArgs[I+1].RV);
1289 // Otherwise, we need to save all this stuff.
1290 DominatingValue<RValue>::saved_type SavedNewPtr =
1291 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1292 DominatingValue<RValue>::saved_type SavedAllocSize =
1293 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1295 CallDeleteDuringConditionalNew *Cleanup = CGF.EHStack
1296 .pushCleanupWithExtra<CallDeleteDuringConditionalNew>(EHCleanup,
1297 E->getNumPlacementArgs(),
1298 E->getOperatorDelete(),
1301 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I)
1302 Cleanup->setPlacementArg(I,
1303 DominatingValue<RValue>::save(CGF, NewArgs[I+1].RV));
1305 CGF.initFullExprCleanup();
1308 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1309 // The element type being allocated.
1310 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1312 // 1. Build a call to the allocation function.
1313 FunctionDecl *allocator = E->getOperatorNew();
1315 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1316 unsigned minElements = 0;
1317 if (E->isArray() && E->hasInitializer()) {
1318 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer()))
1319 minElements = ILE->getNumInits();
1322 llvm::Value *numElements = nullptr;
1323 llvm::Value *allocSizeWithoutCookie = nullptr;
1324 llvm::Value *allocSize =
1325 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1326 allocSizeWithoutCookie);
1328 // Emit the allocation call. If the allocator is a global placement
1329 // operator, just "inline" it directly.
1330 Address allocation = Address::invalid();
1331 CallArgList allocatorArgs;
1332 if (allocator->isReservedGlobalPlacementOperator()) {
1333 assert(E->getNumPlacementArgs() == 1);
1334 const Expr *arg = *E->placement_arguments().begin();
1336 AlignmentSource alignSource;
1337 allocation = EmitPointerWithAlignment(arg, &alignSource);
1339 // The pointer expression will, in many cases, be an opaque void*.
1340 // In these cases, discard the computed alignment and use the
1341 // formal alignment of the allocated type.
1342 if (alignSource != AlignmentSource::Decl) {
1343 allocation = Address(allocation.getPointer(),
1344 getContext().getTypeAlignInChars(allocType));
1347 // Set up allocatorArgs for the call to operator delete if it's not
1348 // the reserved global operator.
1349 if (E->getOperatorDelete() &&
1350 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1351 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1352 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1356 const FunctionProtoType *allocatorType =
1357 allocator->getType()->castAs<FunctionProtoType>();
1359 // The allocation size is the first argument.
1360 QualType sizeType = getContext().getSizeType();
1361 allocatorArgs.add(RValue::get(allocSize), sizeType);
1363 // We start at 1 here because the first argument (the allocation size)
1364 // has already been emitted.
1365 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1366 /* CalleeDecl */ nullptr,
1367 /*ParamsToSkip*/ 1);
1370 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1372 // For now, only assume that the allocation function returns
1373 // something satisfactorily aligned for the element type, plus
1374 // the cookie if we have one.
1375 CharUnits allocationAlign =
1376 getContext().getTypeAlignInChars(allocType);
1377 if (allocSize != allocSizeWithoutCookie) {
1378 CharUnits cookieAlign = getSizeAlign(); // FIXME?
1379 allocationAlign = std::max(allocationAlign, cookieAlign);
1382 allocation = Address(RV.getScalarVal(), allocationAlign);
1385 // Emit a null check on the allocation result if the allocation
1386 // function is allowed to return null (because it has a non-throwing
1387 // exception spec or is the reserved placement new) and we have an
1388 // interesting initializer.
1389 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
1390 (!allocType.isPODType(getContext()) || E->hasInitializer());
1392 llvm::BasicBlock *nullCheckBB = nullptr;
1393 llvm::BasicBlock *contBB = nullptr;
1395 // The null-check means that the initializer is conditionally
1397 ConditionalEvaluation conditional(*this);
1400 conditional.begin(*this);
1402 nullCheckBB = Builder.GetInsertBlock();
1403 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1404 contBB = createBasicBlock("new.cont");
1406 llvm::Value *isNull =
1407 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1408 Builder.CreateCondBr(isNull, contBB, notNullBB);
1409 EmitBlock(notNullBB);
1412 // If there's an operator delete, enter a cleanup to call it if an
1413 // exception is thrown.
1414 EHScopeStack::stable_iterator operatorDeleteCleanup;
1415 llvm::Instruction *cleanupDominator = nullptr;
1416 if (E->getOperatorDelete() &&
1417 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1418 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocatorArgs);
1419 operatorDeleteCleanup = EHStack.stable_begin();
1420 cleanupDominator = Builder.CreateUnreachable();
1423 assert((allocSize == allocSizeWithoutCookie) ==
1424 CalculateCookiePadding(*this, E).isZero());
1425 if (allocSize != allocSizeWithoutCookie) {
1426 assert(E->isArray());
1427 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1432 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1433 Address result = Builder.CreateElementBitCast(allocation, elementTy);
1435 // Passing pointer through invariant.group.barrier to avoid propagation of
1436 // vptrs information which may be included in previous type.
1437 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1438 CGM.getCodeGenOpts().OptimizationLevel > 0 &&
1439 allocator->isReservedGlobalPlacementOperator())
1440 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1441 result.getAlignment());
1443 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1444 allocSizeWithoutCookie);
1446 // NewPtr is a pointer to the base element type. If we're
1447 // allocating an array of arrays, we'll need to cast back to the
1448 // array pointer type.
1449 llvm::Type *resultType = ConvertTypeForMem(E->getType());
1450 if (result.getType() != resultType)
1451 result = Builder.CreateBitCast(result, resultType);
1454 // Deactivate the 'operator delete' cleanup if we finished
1456 if (operatorDeleteCleanup.isValid()) {
1457 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1458 cleanupDominator->eraseFromParent();
1461 llvm::Value *resultPtr = result.getPointer();
1463 conditional.end(*this);
1465 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1468 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1469 PHI->addIncoming(resultPtr, notNullBB);
1470 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1479 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1481 QualType DeleteTy) {
1482 assert(DeleteFD->getOverloadedOperator() == OO_Delete);
1484 const FunctionProtoType *DeleteFTy =
1485 DeleteFD->getType()->getAs<FunctionProtoType>();
1487 CallArgList DeleteArgs;
1489 // Check if we need to pass the size to the delete operator.
1490 llvm::Value *Size = nullptr;
1492 if (DeleteFTy->getNumParams() == 2) {
1493 SizeTy = DeleteFTy->getParamType(1);
1494 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1495 Size = llvm::ConstantInt::get(ConvertType(SizeTy),
1496 DeleteTypeSize.getQuantity());
1499 QualType ArgTy = DeleteFTy->getParamType(0);
1500 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1501 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1504 DeleteArgs.add(RValue::get(Size), SizeTy);
1506 // Emit the call to delete.
1507 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1511 /// Calls the given 'operator delete' on a single object.
1512 struct CallObjectDelete final : EHScopeStack::Cleanup {
1514 const FunctionDecl *OperatorDelete;
1515 QualType ElementType;
1517 CallObjectDelete(llvm::Value *Ptr,
1518 const FunctionDecl *OperatorDelete,
1519 QualType ElementType)
1520 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1522 void Emit(CodeGenFunction &CGF, Flags flags) override {
1523 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1529 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1530 llvm::Value *CompletePtr,
1531 QualType ElementType) {
1532 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1533 OperatorDelete, ElementType);
1536 /// Emit the code for deleting a single object.
1537 static void EmitObjectDelete(CodeGenFunction &CGF,
1538 const CXXDeleteExpr *DE,
1540 QualType ElementType) {
1541 // Find the destructor for the type, if applicable. If the
1542 // destructor is virtual, we'll just emit the vcall and return.
1543 const CXXDestructorDecl *Dtor = nullptr;
1544 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1545 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1546 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1547 Dtor = RD->getDestructor();
1549 if (Dtor->isVirtual()) {
1550 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1557 // Make sure that we call delete even if the dtor throws.
1558 // This doesn't have to a conditional cleanup because we're going
1559 // to pop it off in a second.
1560 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1561 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1563 OperatorDelete, ElementType);
1566 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1567 /*ForVirtualBase=*/false,
1568 /*Delegating=*/false,
1570 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1572 case Qualifiers::OCL_None:
1573 case Qualifiers::OCL_ExplicitNone:
1574 case Qualifiers::OCL_Autoreleasing:
1577 case Qualifiers::OCL_Strong:
1578 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1581 case Qualifiers::OCL_Weak:
1582 CGF.EmitARCDestroyWeak(Ptr);
1587 CGF.PopCleanupBlock();
1591 /// Calls the given 'operator delete' on an array of objects.
1592 struct CallArrayDelete final : EHScopeStack::Cleanup {
1594 const FunctionDecl *OperatorDelete;
1595 llvm::Value *NumElements;
1596 QualType ElementType;
1597 CharUnits CookieSize;
1599 CallArrayDelete(llvm::Value *Ptr,
1600 const FunctionDecl *OperatorDelete,
1601 llvm::Value *NumElements,
1602 QualType ElementType,
1603 CharUnits CookieSize)
1604 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1605 ElementType(ElementType), CookieSize(CookieSize) {}
1607 void Emit(CodeGenFunction &CGF, Flags flags) override {
1608 const FunctionProtoType *DeleteFTy =
1609 OperatorDelete->getType()->getAs<FunctionProtoType>();
1610 assert(DeleteFTy->getNumParams() == 1 || DeleteFTy->getNumParams() == 2);
1614 // Pass the pointer as the first argument.
1615 QualType VoidPtrTy = DeleteFTy->getParamType(0);
1616 llvm::Value *DeletePtr
1617 = CGF.Builder.CreateBitCast(Ptr, CGF.ConvertType(VoidPtrTy));
1618 Args.add(RValue::get(DeletePtr), VoidPtrTy);
1620 // Pass the original requested size as the second argument.
1621 if (DeleteFTy->getNumParams() == 2) {
1622 QualType size_t = DeleteFTy->getParamType(1);
1623 llvm::IntegerType *SizeTy
1624 = cast<llvm::IntegerType>(CGF.ConvertType(size_t));
1626 CharUnits ElementTypeSize =
1627 CGF.CGM.getContext().getTypeSizeInChars(ElementType);
1629 // The size of an element, multiplied by the number of elements.
1631 = llvm::ConstantInt::get(SizeTy, ElementTypeSize.getQuantity());
1633 Size = CGF.Builder.CreateMul(Size, NumElements);
1635 // Plus the size of the cookie if applicable.
1636 if (!CookieSize.isZero()) {
1637 llvm::Value *CookieSizeV
1638 = llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity());
1639 Size = CGF.Builder.CreateAdd(Size, CookieSizeV);
1642 Args.add(RValue::get(Size), size_t);
1645 // Emit the call to delete.
1646 EmitNewDeleteCall(CGF, OperatorDelete, DeleteFTy, Args);
1651 /// Emit the code for deleting an array of objects.
1652 static void EmitArrayDelete(CodeGenFunction &CGF,
1653 const CXXDeleteExpr *E,
1655 QualType elementType) {
1656 llvm::Value *numElements = nullptr;
1657 llvm::Value *allocatedPtr = nullptr;
1658 CharUnits cookieSize;
1659 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1660 numElements, allocatedPtr, cookieSize);
1662 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
1664 // Make sure that we call delete even if one of the dtors throws.
1665 const FunctionDecl *operatorDelete = E->getOperatorDelete();
1666 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1667 allocatedPtr, operatorDelete,
1668 numElements, elementType,
1671 // Destroy the elements.
1672 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1673 assert(numElements && "no element count for a type with a destructor!");
1675 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1676 CharUnits elementAlign =
1677 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1679 llvm::Value *arrayBegin = deletedPtr.getPointer();
1680 llvm::Value *arrayEnd =
1681 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
1683 // Note that it is legal to allocate a zero-length array, and we
1684 // can never fold the check away because the length should always
1685 // come from a cookie.
1686 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1687 CGF.getDestroyer(dtorKind),
1688 /*checkZeroLength*/ true,
1689 CGF.needsEHCleanup(dtorKind));
1692 // Pop the cleanup block.
1693 CGF.PopCleanupBlock();
1696 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1697 const Expr *Arg = E->getArgument();
1698 Address Ptr = EmitPointerWithAlignment(Arg);
1700 // Null check the pointer.
1701 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1702 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1704 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
1706 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1707 EmitBlock(DeleteNotNull);
1709 // We might be deleting a pointer to array. If so, GEP down to the
1710 // first non-array element.
1711 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1712 QualType DeleteTy = Arg->getType()->getAs<PointerType>()->getPointeeType();
1713 if (DeleteTy->isConstantArrayType()) {
1714 llvm::Value *Zero = Builder.getInt32(0);
1715 SmallVector<llvm::Value*,8> GEP;
1717 GEP.push_back(Zero); // point at the outermost array
1719 // For each layer of array type we're pointing at:
1720 while (const ConstantArrayType *Arr
1721 = getContext().getAsConstantArrayType(DeleteTy)) {
1722 // 1. Unpeel the array type.
1723 DeleteTy = Arr->getElementType();
1725 // 2. GEP to the first element of the array.
1726 GEP.push_back(Zero);
1729 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
1730 Ptr.getAlignment());
1733 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
1735 if (E->isArrayForm()) {
1736 EmitArrayDelete(*this, E, Ptr, DeleteTy);
1738 EmitObjectDelete(*this, E, Ptr, DeleteTy);
1741 EmitBlock(DeleteEnd);
1744 static bool isGLValueFromPointerDeref(const Expr *E) {
1745 E = E->IgnoreParens();
1747 if (const auto *CE = dyn_cast<CastExpr>(E)) {
1748 if (!CE->getSubExpr()->isGLValue())
1750 return isGLValueFromPointerDeref(CE->getSubExpr());
1753 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
1754 return isGLValueFromPointerDeref(OVE->getSourceExpr());
1756 if (const auto *BO = dyn_cast<BinaryOperator>(E))
1757 if (BO->getOpcode() == BO_Comma)
1758 return isGLValueFromPointerDeref(BO->getRHS());
1760 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
1761 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
1762 isGLValueFromPointerDeref(ACO->getFalseExpr());
1764 // C++11 [expr.sub]p1:
1765 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
1766 if (isa<ArraySubscriptExpr>(E))
1769 if (const auto *UO = dyn_cast<UnaryOperator>(E))
1770 if (UO->getOpcode() == UO_Deref)
1776 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
1777 llvm::Type *StdTypeInfoPtrTy) {
1778 // Get the vtable pointer.
1779 Address ThisPtr = CGF.EmitLValue(E).getAddress();
1781 // C++ [expr.typeid]p2:
1782 // If the glvalue expression is obtained by applying the unary * operator to
1783 // a pointer and the pointer is a null pointer value, the typeid expression
1784 // throws the std::bad_typeid exception.
1786 // However, this paragraph's intent is not clear. We choose a very generous
1787 // interpretation which implores us to consider comma operators, conditional
1788 // operators, parentheses and other such constructs.
1789 QualType SrcRecordTy = E->getType();
1790 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
1791 isGLValueFromPointerDeref(E), SrcRecordTy)) {
1792 llvm::BasicBlock *BadTypeidBlock =
1793 CGF.createBasicBlock("typeid.bad_typeid");
1794 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
1796 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
1797 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
1799 CGF.EmitBlock(BadTypeidBlock);
1800 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
1801 CGF.EmitBlock(EndBlock);
1804 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
1808 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
1809 llvm::Type *StdTypeInfoPtrTy =
1810 ConvertType(E->getType())->getPointerTo();
1812 if (E->isTypeOperand()) {
1813 llvm::Constant *TypeInfo =
1814 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
1815 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
1818 // C++ [expr.typeid]p2:
1819 // When typeid is applied to a glvalue expression whose type is a
1820 // polymorphic class type, the result refers to a std::type_info object
1821 // representing the type of the most derived object (that is, the dynamic
1822 // type) to which the glvalue refers.
1823 if (E->isPotentiallyEvaluated())
1824 return EmitTypeidFromVTable(*this, E->getExprOperand(),
1827 QualType OperandTy = E->getExprOperand()->getType();
1828 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
1832 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
1834 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
1835 if (DestTy->isPointerType())
1836 return llvm::Constant::getNullValue(DestLTy);
1838 /// C++ [expr.dynamic.cast]p9:
1839 /// A failed cast to reference type throws std::bad_cast
1840 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
1843 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
1844 return llvm::UndefValue::get(DestLTy);
1847 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
1848 const CXXDynamicCastExpr *DCE) {
1849 CGM.EmitExplicitCastExprType(DCE, this);
1850 QualType DestTy = DCE->getTypeAsWritten();
1852 if (DCE->isAlwaysNull())
1853 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
1856 QualType SrcTy = DCE->getSubExpr()->getType();
1858 // C++ [expr.dynamic.cast]p7:
1859 // If T is "pointer to cv void," then the result is a pointer to the most
1860 // derived object pointed to by v.
1861 const PointerType *DestPTy = DestTy->getAs<PointerType>();
1863 bool isDynamicCastToVoid;
1864 QualType SrcRecordTy;
1865 QualType DestRecordTy;
1867 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
1868 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
1869 DestRecordTy = DestPTy->getPointeeType();
1871 isDynamicCastToVoid = false;
1872 SrcRecordTy = SrcTy;
1873 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
1876 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
1878 // C++ [expr.dynamic.cast]p4:
1879 // If the value of v is a null pointer value in the pointer case, the result
1880 // is the null pointer value of type T.
1881 bool ShouldNullCheckSrcValue =
1882 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
1885 llvm::BasicBlock *CastNull = nullptr;
1886 llvm::BasicBlock *CastNotNull = nullptr;
1887 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
1889 if (ShouldNullCheckSrcValue) {
1890 CastNull = createBasicBlock("dynamic_cast.null");
1891 CastNotNull = createBasicBlock("dynamic_cast.notnull");
1893 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
1894 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
1895 EmitBlock(CastNotNull);
1899 if (isDynamicCastToVoid) {
1900 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
1903 assert(DestRecordTy->isRecordType() &&
1904 "destination type must be a record type!");
1905 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
1906 DestTy, DestRecordTy, CastEnd);
1907 CastNotNull = Builder.GetInsertBlock();
1910 if (ShouldNullCheckSrcValue) {
1911 EmitBranch(CastEnd);
1913 EmitBlock(CastNull);
1914 EmitBranch(CastEnd);
1919 if (ShouldNullCheckSrcValue) {
1920 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
1921 PHI->addIncoming(Value, CastNotNull);
1922 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
1930 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
1931 RunCleanupsScope Scope(*this);
1932 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
1934 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
1935 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
1936 e = E->capture_init_end();
1937 i != e; ++i, ++CurField) {
1938 // Emit initialization
1939 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
1940 if (CurField->hasCapturedVLAType()) {
1941 auto VAT = CurField->getCapturedVLAType();
1942 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
1944 ArrayRef<VarDecl *> ArrayIndexes;
1945 if (CurField->getType()->isArrayType())
1946 ArrayIndexes = E->getCaptureInitIndexVars(i);
1947 EmitInitializerForField(*CurField, LV, *i, ArrayIndexes);