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 "ConstantEmitter.h"
20 #include "clang/CodeGen/CGFunctionInfo.h"
21 #include "clang/Frontend/CodeGenOptions.h"
22 #include "llvm/IR/CallSite.h"
23 #include "llvm/IR/Intrinsics.h"
25 using namespace clang;
26 using namespace CodeGen;
29 struct MemberCallInfo {
31 // Number of prefix arguments for the call. Ignores the `this` pointer.
37 commonEmitCXXMemberOrOperatorCall(CodeGenFunction &CGF, const CXXMethodDecl *MD,
38 llvm::Value *This, llvm::Value *ImplicitParam,
39 QualType ImplicitParamTy, const CallExpr *CE,
40 CallArgList &Args, CallArgList *RtlArgs) {
41 assert(CE == nullptr || isa<CXXMemberCallExpr>(CE) ||
42 isa<CXXOperatorCallExpr>(CE));
43 assert(MD->isInstance() &&
44 "Trying to emit a member or operator call expr on a static method!");
45 ASTContext &C = CGF.getContext();
48 const CXXRecordDecl *RD =
49 CGF.CGM.getCXXABI().getThisArgumentTypeForMethod(MD);
50 Args.add(RValue::get(This),
51 RD ? C.getPointerType(C.getTypeDeclType(RD)) : C.VoidPtrTy);
53 // If there is an implicit parameter (e.g. VTT), emit it.
55 Args.add(RValue::get(ImplicitParam), ImplicitParamTy);
58 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
59 RequiredArgs required = RequiredArgs::forPrototypePlus(FPT, Args.size(), MD);
60 unsigned PrefixSize = Args.size() - 1;
62 // And the rest of the call args.
64 // Special case: if the caller emitted the arguments right-to-left already
65 // (prior to emitting the *this argument), we're done. This happens for
66 // assignment operators.
67 Args.addFrom(*RtlArgs);
69 // Special case: skip first argument of CXXOperatorCall (it is "this").
70 unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(CE) ? 1 : 0;
71 CGF.EmitCallArgs(Args, FPT, drop_begin(CE->arguments(), ArgsToSkip),
72 CE->getDirectCallee());
75 FPT->getNumParams() == 0 &&
76 "No CallExpr specified for function with non-zero number of arguments");
78 return {required, PrefixSize};
81 RValue CodeGenFunction::EmitCXXMemberOrOperatorCall(
82 const CXXMethodDecl *MD, const CGCallee &Callee,
83 ReturnValueSlot ReturnValue,
84 llvm::Value *This, llvm::Value *ImplicitParam, QualType ImplicitParamTy,
85 const CallExpr *CE, CallArgList *RtlArgs) {
86 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
88 MemberCallInfo CallInfo = commonEmitCXXMemberOrOperatorCall(
89 *this, MD, This, ImplicitParam, ImplicitParamTy, CE, Args, RtlArgs);
90 auto &FnInfo = CGM.getTypes().arrangeCXXMethodCall(
91 Args, FPT, CallInfo.ReqArgs, CallInfo.PrefixSize);
92 return EmitCall(FnInfo, Callee, ReturnValue, Args, nullptr,
93 CE ? CE->getExprLoc() : SourceLocation());
96 RValue CodeGenFunction::EmitCXXDestructorCall(
97 const CXXDestructorDecl *DD, const CGCallee &Callee, llvm::Value *This,
98 llvm::Value *ImplicitParam, QualType ImplicitParamTy, const CallExpr *CE,
101 commonEmitCXXMemberOrOperatorCall(*this, DD, This, ImplicitParam,
102 ImplicitParamTy, CE, Args, nullptr);
103 return EmitCall(CGM.getTypes().arrangeCXXStructorDeclaration(DD, Type),
104 Callee, ReturnValueSlot(), Args);
107 RValue CodeGenFunction::EmitCXXPseudoDestructorExpr(
108 const CXXPseudoDestructorExpr *E) {
109 QualType DestroyedType = E->getDestroyedType();
110 if (DestroyedType.hasStrongOrWeakObjCLifetime()) {
111 // Automatic Reference Counting:
112 // If the pseudo-expression names a retainable object with weak or
113 // strong lifetime, the object shall be released.
114 Expr *BaseExpr = E->getBase();
115 Address BaseValue = Address::invalid();
116 Qualifiers BaseQuals;
118 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
120 BaseValue = EmitPointerWithAlignment(BaseExpr);
121 const PointerType *PTy = BaseExpr->getType()->getAs<PointerType>();
122 BaseQuals = PTy->getPointeeType().getQualifiers();
124 LValue BaseLV = EmitLValue(BaseExpr);
125 BaseValue = BaseLV.getAddress();
126 QualType BaseTy = BaseExpr->getType();
127 BaseQuals = BaseTy.getQualifiers();
130 switch (DestroyedType.getObjCLifetime()) {
131 case Qualifiers::OCL_None:
132 case Qualifiers::OCL_ExplicitNone:
133 case Qualifiers::OCL_Autoreleasing:
136 case Qualifiers::OCL_Strong:
137 EmitARCRelease(Builder.CreateLoad(BaseValue,
138 DestroyedType.isVolatileQualified()),
142 case Qualifiers::OCL_Weak:
143 EmitARCDestroyWeak(BaseValue);
147 // C++ [expr.pseudo]p1:
148 // The result shall only be used as the operand for the function call
149 // operator (), and the result of such a call has type void. The only
150 // effect is the evaluation of the postfix-expression before the dot or
152 EmitIgnoredExpr(E->getBase());
155 return RValue::get(nullptr);
158 static CXXRecordDecl *getCXXRecord(const Expr *E) {
159 QualType T = E->getType();
160 if (const PointerType *PTy = T->getAs<PointerType>())
161 T = PTy->getPointeeType();
162 const RecordType *Ty = T->castAs<RecordType>();
163 return cast<CXXRecordDecl>(Ty->getDecl());
166 // Note: This function also emit constructor calls to support a MSVC
167 // extensions allowing explicit constructor function call.
168 RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE,
169 ReturnValueSlot ReturnValue) {
170 const Expr *callee = CE->getCallee()->IgnoreParens();
172 if (isa<BinaryOperator>(callee))
173 return EmitCXXMemberPointerCallExpr(CE, ReturnValue);
175 const MemberExpr *ME = cast<MemberExpr>(callee);
176 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl());
178 if (MD->isStatic()) {
179 // The method is static, emit it as we would a regular call.
180 CGCallee callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD), MD);
181 return EmitCall(getContext().getPointerType(MD->getType()), callee, CE,
185 bool HasQualifier = ME->hasQualifier();
186 NestedNameSpecifier *Qualifier = HasQualifier ? ME->getQualifier() : nullptr;
187 bool IsArrow = ME->isArrow();
188 const Expr *Base = ME->getBase();
190 return EmitCXXMemberOrOperatorMemberCallExpr(
191 CE, MD, ReturnValue, HasQualifier, Qualifier, IsArrow, Base);
194 RValue CodeGenFunction::EmitCXXMemberOrOperatorMemberCallExpr(
195 const CallExpr *CE, const CXXMethodDecl *MD, ReturnValueSlot ReturnValue,
196 bool HasQualifier, NestedNameSpecifier *Qualifier, bool IsArrow,
198 assert(isa<CXXMemberCallExpr>(CE) || isa<CXXOperatorCallExpr>(CE));
200 // Compute the object pointer.
201 bool CanUseVirtualCall = MD->isVirtual() && !HasQualifier;
203 const CXXMethodDecl *DevirtualizedMethod = nullptr;
204 if (CanUseVirtualCall &&
205 MD->getDevirtualizedMethod(Base, getLangOpts().AppleKext)) {
206 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType();
207 DevirtualizedMethod = MD->getCorrespondingMethodInClass(BestDynamicDecl);
208 assert(DevirtualizedMethod);
209 const CXXRecordDecl *DevirtualizedClass = DevirtualizedMethod->getParent();
210 const Expr *Inner = Base->ignoreParenBaseCasts();
211 if (DevirtualizedMethod->getReturnType().getCanonicalType() !=
212 MD->getReturnType().getCanonicalType())
213 // If the return types are not the same, this might be a case where more
214 // code needs to run to compensate for it. For example, the derived
215 // method might return a type that inherits form from the return
216 // type of MD and has a prefix.
217 // For now we just avoid devirtualizing these covariant cases.
218 DevirtualizedMethod = nullptr;
219 else if (getCXXRecord(Inner) == DevirtualizedClass)
220 // If the class of the Inner expression is where the dynamic method
221 // is defined, build the this pointer from it.
223 else if (getCXXRecord(Base) != DevirtualizedClass) {
224 // If the method is defined in a class that is not the best dynamic
225 // one or the one of the full expression, we would have to build
226 // a derived-to-base cast to compute the correct this pointer, but
227 // we don't have support for that yet, so do a virtual call.
228 DevirtualizedMethod = nullptr;
232 // C++17 demands that we evaluate the RHS of a (possibly-compound) assignment
233 // operator before the LHS.
234 CallArgList RtlArgStorage;
235 CallArgList *RtlArgs = nullptr;
236 if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(CE)) {
237 if (OCE->isAssignmentOp()) {
238 RtlArgs = &RtlArgStorage;
239 EmitCallArgs(*RtlArgs, MD->getType()->castAs<FunctionProtoType>(),
240 drop_begin(CE->arguments(), 1), CE->getDirectCallee(),
241 /*ParamsToSkip*/0, EvaluationOrder::ForceRightToLeft);
245 Address This = Address::invalid();
247 This = EmitPointerWithAlignment(Base);
249 This = EmitLValue(Base).getAddress();
252 if (MD->isTrivial() || (MD->isDefaulted() && MD->getParent()->isUnion())) {
253 if (isa<CXXDestructorDecl>(MD)) return RValue::get(nullptr);
254 if (isa<CXXConstructorDecl>(MD) &&
255 cast<CXXConstructorDecl>(MD)->isDefaultConstructor())
256 return RValue::get(nullptr);
258 if (!MD->getParent()->mayInsertExtraPadding()) {
259 if (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()) {
260 // We don't like to generate the trivial copy/move assignment operator
261 // when it isn't necessary; just produce the proper effect here.
262 LValue RHS = isa<CXXOperatorCallExpr>(CE)
263 ? MakeNaturalAlignAddrLValue(
264 (*RtlArgs)[0].RV.getScalarVal(),
265 (*(CE->arg_begin() + 1))->getType())
266 : EmitLValue(*CE->arg_begin());
267 EmitAggregateAssign(This, RHS.getAddress(), CE->getType());
268 return RValue::get(This.getPointer());
271 if (isa<CXXConstructorDecl>(MD) &&
272 cast<CXXConstructorDecl>(MD)->isCopyOrMoveConstructor()) {
273 // Trivial move and copy ctor are the same.
274 assert(CE->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
275 Address RHS = EmitLValue(*CE->arg_begin()).getAddress();
276 EmitAggregateCopy(This, RHS, (*CE->arg_begin())->getType());
277 return RValue::get(This.getPointer());
279 llvm_unreachable("unknown trivial member function");
283 // Compute the function type we're calling.
284 const CXXMethodDecl *CalleeDecl =
285 DevirtualizedMethod ? DevirtualizedMethod : MD;
286 const CGFunctionInfo *FInfo = nullptr;
287 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(CalleeDecl))
288 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
289 Dtor, StructorType::Complete);
290 else if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(CalleeDecl))
291 FInfo = &CGM.getTypes().arrangeCXXStructorDeclaration(
292 Ctor, StructorType::Complete);
294 FInfo = &CGM.getTypes().arrangeCXXMethodDeclaration(CalleeDecl);
296 llvm::FunctionType *Ty = CGM.getTypes().GetFunctionType(*FInfo);
298 // C++11 [class.mfct.non-static]p2:
299 // If a non-static member function of a class X is called for an object that
300 // is not of type X, or of a type derived from X, the behavior is undefined.
301 SourceLocation CallLoc;
302 ASTContext &C = getContext();
304 CallLoc = CE->getExprLoc();
306 SanitizerSet SkippedChecks;
307 if (const auto *CMCE = dyn_cast<CXXMemberCallExpr>(CE)) {
308 auto *IOA = CMCE->getImplicitObjectArgument();
309 bool IsImplicitObjectCXXThis = IsWrappedCXXThis(IOA);
310 if (IsImplicitObjectCXXThis)
311 SkippedChecks.set(SanitizerKind::Alignment, true);
312 if (IsImplicitObjectCXXThis || isa<DeclRefExpr>(IOA))
313 SkippedChecks.set(SanitizerKind::Null, true);
316 isa<CXXConstructorDecl>(CalleeDecl) ? CodeGenFunction::TCK_ConstructorCall
317 : CodeGenFunction::TCK_MemberCall,
318 CallLoc, This.getPointer(), C.getRecordType(CalleeDecl->getParent()),
319 /*Alignment=*/CharUnits::Zero(), SkippedChecks);
321 // FIXME: Uses of 'MD' past this point need to be audited. We may need to use
322 // 'CalleeDecl' instead.
324 // C++ [class.virtual]p12:
325 // Explicit qualification with the scope operator (5.1) suppresses the
326 // virtual call mechanism.
328 // We also don't emit a virtual call if the base expression has a record type
329 // because then we know what the type is.
330 bool UseVirtualCall = CanUseVirtualCall && !DevirtualizedMethod;
332 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(MD)) {
333 assert(CE->arg_begin() == CE->arg_end() &&
334 "Destructor shouldn't have explicit parameters");
335 assert(ReturnValue.isNull() && "Destructor shouldn't have return value");
336 if (UseVirtualCall) {
337 CGM.getCXXABI().EmitVirtualDestructorCall(
338 *this, Dtor, Dtor_Complete, This, cast<CXXMemberCallExpr>(CE));
341 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
342 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
343 else if (!DevirtualizedMethod)
344 Callee = CGCallee::forDirect(
345 CGM.getAddrOfCXXStructor(Dtor, StructorType::Complete, FInfo, Ty),
348 const CXXDestructorDecl *DDtor =
349 cast<CXXDestructorDecl>(DevirtualizedMethod);
350 Callee = CGCallee::forDirect(
351 CGM.GetAddrOfFunction(GlobalDecl(DDtor, Dtor_Complete), Ty),
354 EmitCXXMemberOrOperatorCall(
355 CalleeDecl, Callee, ReturnValue, This.getPointer(),
356 /*ImplicitParam=*/nullptr, QualType(), CE, nullptr);
358 return RValue::get(nullptr);
362 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(MD)) {
363 Callee = CGCallee::forDirect(
364 CGM.GetAddrOfFunction(GlobalDecl(Ctor, Ctor_Complete), Ty),
366 } else if (UseVirtualCall) {
367 Callee = CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, Ty,
370 if (SanOpts.has(SanitizerKind::CFINVCall) &&
371 MD->getParent()->isDynamicClass()) {
373 const CXXRecordDecl *RD;
374 std::tie(VTable, RD) =
375 CGM.getCXXABI().LoadVTablePtr(*this, This, MD->getParent());
376 EmitVTablePtrCheckForCall(RD, VTable, CFITCK_NVCall, CE->getLocStart());
379 if (getLangOpts().AppleKext && MD->isVirtual() && HasQualifier)
380 Callee = BuildAppleKextVirtualCall(MD, Qualifier, Ty);
381 else if (!DevirtualizedMethod)
382 Callee = CGCallee::forDirect(CGM.GetAddrOfFunction(MD, Ty), MD);
384 Callee = CGCallee::forDirect(
385 CGM.GetAddrOfFunction(DevirtualizedMethod, Ty),
386 DevirtualizedMethod);
390 if (MD->isVirtual()) {
391 This = CGM.getCXXABI().adjustThisArgumentForVirtualFunctionCall(
392 *this, CalleeDecl, This, UseVirtualCall);
395 return EmitCXXMemberOrOperatorCall(
396 CalleeDecl, Callee, ReturnValue, This.getPointer(),
397 /*ImplicitParam=*/nullptr, QualType(), CE, RtlArgs);
401 CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E,
402 ReturnValueSlot ReturnValue) {
403 const BinaryOperator *BO =
404 cast<BinaryOperator>(E->getCallee()->IgnoreParens());
405 const Expr *BaseExpr = BO->getLHS();
406 const Expr *MemFnExpr = BO->getRHS();
408 const MemberPointerType *MPT =
409 MemFnExpr->getType()->castAs<MemberPointerType>();
411 const FunctionProtoType *FPT =
412 MPT->getPointeeType()->castAs<FunctionProtoType>();
413 const CXXRecordDecl *RD =
414 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl());
416 // Emit the 'this' pointer.
417 Address This = Address::invalid();
418 if (BO->getOpcode() == BO_PtrMemI)
419 This = EmitPointerWithAlignment(BaseExpr);
421 This = EmitLValue(BaseExpr).getAddress();
423 EmitTypeCheck(TCK_MemberCall, E->getExprLoc(), This.getPointer(),
424 QualType(MPT->getClass(), 0));
426 // Get the member function pointer.
427 llvm::Value *MemFnPtr = EmitScalarExpr(MemFnExpr);
429 // Ask the ABI to load the callee. Note that This is modified.
430 llvm::Value *ThisPtrForCall = nullptr;
432 CGM.getCXXABI().EmitLoadOfMemberFunctionPointer(*this, BO, This,
433 ThisPtrForCall, MemFnPtr, MPT);
438 getContext().getPointerType(getContext().getTagDeclType(RD));
440 // Push the this ptr.
441 Args.add(RValue::get(ThisPtrForCall), ThisType);
443 RequiredArgs required =
444 RequiredArgs::forPrototypePlus(FPT, 1, /*FD=*/nullptr);
446 // And the rest of the call args
447 EmitCallArgs(Args, FPT, E->arguments());
448 return EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, required,
450 Callee, ReturnValue, Args, nullptr, E->getExprLoc());
454 CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E,
455 const CXXMethodDecl *MD,
456 ReturnValueSlot ReturnValue) {
457 assert(MD->isInstance() &&
458 "Trying to emit a member call expr on a static method!");
459 return EmitCXXMemberOrOperatorMemberCallExpr(
460 E, MD, ReturnValue, /*HasQualifier=*/false, /*Qualifier=*/nullptr,
461 /*IsArrow=*/false, E->getArg(0));
464 RValue CodeGenFunction::EmitCUDAKernelCallExpr(const CUDAKernelCallExpr *E,
465 ReturnValueSlot ReturnValue) {
466 return CGM.getCUDARuntime().EmitCUDAKernelCallExpr(*this, E, ReturnValue);
469 static void EmitNullBaseClassInitialization(CodeGenFunction &CGF,
471 const CXXRecordDecl *Base) {
475 DestPtr = CGF.Builder.CreateElementBitCast(DestPtr, CGF.Int8Ty);
477 const ASTRecordLayout &Layout = CGF.getContext().getASTRecordLayout(Base);
478 CharUnits NVSize = Layout.getNonVirtualSize();
480 // We cannot simply zero-initialize the entire base sub-object if vbptrs are
481 // present, they are initialized by the most derived class before calling the
483 SmallVector<std::pair<CharUnits, CharUnits>, 1> Stores;
484 Stores.emplace_back(CharUnits::Zero(), NVSize);
486 // Each store is split by the existence of a vbptr.
487 CharUnits VBPtrWidth = CGF.getPointerSize();
488 std::vector<CharUnits> VBPtrOffsets =
489 CGF.CGM.getCXXABI().getVBPtrOffsets(Base);
490 for (CharUnits VBPtrOffset : VBPtrOffsets) {
491 // Stop before we hit any virtual base pointers located in virtual bases.
492 if (VBPtrOffset >= NVSize)
494 std::pair<CharUnits, CharUnits> LastStore = Stores.pop_back_val();
495 CharUnits LastStoreOffset = LastStore.first;
496 CharUnits LastStoreSize = LastStore.second;
498 CharUnits SplitBeforeOffset = LastStoreOffset;
499 CharUnits SplitBeforeSize = VBPtrOffset - SplitBeforeOffset;
500 assert(!SplitBeforeSize.isNegative() && "negative store size!");
501 if (!SplitBeforeSize.isZero())
502 Stores.emplace_back(SplitBeforeOffset, SplitBeforeSize);
504 CharUnits SplitAfterOffset = VBPtrOffset + VBPtrWidth;
505 CharUnits SplitAfterSize = LastStoreSize - SplitAfterOffset;
506 assert(!SplitAfterSize.isNegative() && "negative store size!");
507 if (!SplitAfterSize.isZero())
508 Stores.emplace_back(SplitAfterOffset, SplitAfterSize);
511 // If the type contains a pointer to data member we can't memset it to zero.
512 // Instead, create a null constant and copy it to the destination.
513 // TODO: there are other patterns besides zero that we can usefully memset,
514 // like -1, which happens to be the pattern used by member-pointers.
515 // TODO: isZeroInitializable can be over-conservative in the case where a
516 // virtual base contains a member pointer.
517 llvm::Constant *NullConstantForBase = CGF.CGM.EmitNullConstantForBase(Base);
518 if (!NullConstantForBase->isNullValue()) {
519 llvm::GlobalVariable *NullVariable = new llvm::GlobalVariable(
520 CGF.CGM.getModule(), NullConstantForBase->getType(),
521 /*isConstant=*/true, llvm::GlobalVariable::PrivateLinkage,
522 NullConstantForBase, Twine());
524 CharUnits Align = std::max(Layout.getNonVirtualAlignment(),
525 DestPtr.getAlignment());
526 NullVariable->setAlignment(Align.getQuantity());
528 Address SrcPtr = Address(CGF.EmitCastToVoidPtr(NullVariable), Align);
530 // Get and call the appropriate llvm.memcpy overload.
531 for (std::pair<CharUnits, CharUnits> Store : Stores) {
532 CharUnits StoreOffset = Store.first;
533 CharUnits StoreSize = Store.second;
534 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
535 CGF.Builder.CreateMemCpy(
536 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
537 CGF.Builder.CreateConstInBoundsByteGEP(SrcPtr, StoreOffset),
541 // Otherwise, just memset the whole thing to zero. This is legal
542 // because in LLVM, all default initializers (other than the ones we just
543 // handled above) are guaranteed to have a bit pattern of all zeros.
545 for (std::pair<CharUnits, CharUnits> Store : Stores) {
546 CharUnits StoreOffset = Store.first;
547 CharUnits StoreSize = Store.second;
548 llvm::Value *StoreSizeVal = CGF.CGM.getSize(StoreSize);
549 CGF.Builder.CreateMemSet(
550 CGF.Builder.CreateConstInBoundsByteGEP(DestPtr, StoreOffset),
551 CGF.Builder.getInt8(0), StoreSizeVal);
557 CodeGenFunction::EmitCXXConstructExpr(const CXXConstructExpr *E,
559 assert(!Dest.isIgnored() && "Must have a destination!");
560 const CXXConstructorDecl *CD = E->getConstructor();
562 // If we require zero initialization before (or instead of) calling the
563 // constructor, as can be the case with a non-user-provided default
564 // constructor, emit the zero initialization now, unless destination is
566 if (E->requiresZeroInitialization() && !Dest.isZeroed()) {
567 switch (E->getConstructionKind()) {
568 case CXXConstructExpr::CK_Delegating:
569 case CXXConstructExpr::CK_Complete:
570 EmitNullInitialization(Dest.getAddress(), E->getType());
572 case CXXConstructExpr::CK_VirtualBase:
573 case CXXConstructExpr::CK_NonVirtualBase:
574 EmitNullBaseClassInitialization(*this, Dest.getAddress(),
580 // If this is a call to a trivial default constructor, do nothing.
581 if (CD->isTrivial() && CD->isDefaultConstructor())
584 // Elide the constructor if we're constructing from a temporary.
585 // The temporary check is required because Sema sets this on NRVO
587 if (getLangOpts().ElideConstructors && E->isElidable()) {
588 assert(getContext().hasSameUnqualifiedType(E->getType(),
589 E->getArg(0)->getType()));
590 if (E->getArg(0)->isTemporaryObject(getContext(), CD->getParent())) {
591 EmitAggExpr(E->getArg(0), Dest);
596 if (const ArrayType *arrayType
597 = getContext().getAsArrayType(E->getType())) {
598 EmitCXXAggrConstructorCall(CD, arrayType, Dest.getAddress(), E);
600 CXXCtorType Type = Ctor_Complete;
601 bool ForVirtualBase = false;
602 bool Delegating = false;
604 switch (E->getConstructionKind()) {
605 case CXXConstructExpr::CK_Delegating:
606 // We should be emitting a constructor; GlobalDecl will assert this
607 Type = CurGD.getCtorType();
611 case CXXConstructExpr::CK_Complete:
612 Type = Ctor_Complete;
615 case CXXConstructExpr::CK_VirtualBase:
616 ForVirtualBase = true;
619 case CXXConstructExpr::CK_NonVirtualBase:
623 // Call the constructor.
624 EmitCXXConstructorCall(CD, Type, ForVirtualBase, Delegating,
625 Dest.getAddress(), E);
629 void CodeGenFunction::EmitSynthesizedCXXCopyCtor(Address Dest, Address Src,
631 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(Exp))
632 Exp = E->getSubExpr();
633 assert(isa<CXXConstructExpr>(Exp) &&
634 "EmitSynthesizedCXXCopyCtor - unknown copy ctor expr");
635 const CXXConstructExpr* E = cast<CXXConstructExpr>(Exp);
636 const CXXConstructorDecl *CD = E->getConstructor();
637 RunCleanupsScope Scope(*this);
639 // If we require zero initialization before (or instead of) calling the
640 // constructor, as can be the case with a non-user-provided default
641 // constructor, emit the zero initialization now.
642 // FIXME. Do I still need this for a copy ctor synthesis?
643 if (E->requiresZeroInitialization())
644 EmitNullInitialization(Dest, E->getType());
646 assert(!getContext().getAsConstantArrayType(E->getType())
647 && "EmitSynthesizedCXXCopyCtor - Copied-in Array");
648 EmitSynthesizedCXXCopyCtorCall(CD, Dest, Src, E);
651 static CharUnits CalculateCookiePadding(CodeGenFunction &CGF,
652 const CXXNewExpr *E) {
654 return CharUnits::Zero();
656 // No cookie is required if the operator new[] being used is the
657 // reserved placement operator new[].
658 if (E->getOperatorNew()->isReservedGlobalPlacementOperator())
659 return CharUnits::Zero();
661 return CGF.CGM.getCXXABI().GetArrayCookieSize(E);
664 static llvm::Value *EmitCXXNewAllocSize(CodeGenFunction &CGF,
666 unsigned minElements,
667 llvm::Value *&numElements,
668 llvm::Value *&sizeWithoutCookie) {
669 QualType type = e->getAllocatedType();
672 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
674 = llvm::ConstantInt::get(CGF.SizeTy, typeSize.getQuantity());
675 return sizeWithoutCookie;
678 // The width of size_t.
679 unsigned sizeWidth = CGF.SizeTy->getBitWidth();
681 // Figure out the cookie size.
682 llvm::APInt cookieSize(sizeWidth,
683 CalculateCookiePadding(CGF, e).getQuantity());
685 // Emit the array size expression.
686 // We multiply the size of all dimensions for NumElements.
687 // e.g for 'int[2][3]', ElemType is 'int' and NumElements is 6.
689 ConstantEmitter(CGF).tryEmitAbstract(e->getArraySize(), e->getType());
691 numElements = CGF.EmitScalarExpr(e->getArraySize());
692 assert(isa<llvm::IntegerType>(numElements->getType()));
694 // The number of elements can be have an arbitrary integer type;
695 // essentially, we need to multiply it by a constant factor, add a
696 // cookie size, and verify that the result is representable as a
697 // size_t. That's just a gloss, though, and it's wrong in one
698 // important way: if the count is negative, it's an error even if
699 // the cookie size would bring the total size >= 0.
701 = e->getArraySize()->getType()->isSignedIntegerOrEnumerationType();
702 llvm::IntegerType *numElementsType
703 = cast<llvm::IntegerType>(numElements->getType());
704 unsigned numElementsWidth = numElementsType->getBitWidth();
706 // Compute the constant factor.
707 llvm::APInt arraySizeMultiplier(sizeWidth, 1);
708 while (const ConstantArrayType *CAT
709 = CGF.getContext().getAsConstantArrayType(type)) {
710 type = CAT->getElementType();
711 arraySizeMultiplier *= CAT->getSize();
714 CharUnits typeSize = CGF.getContext().getTypeSizeInChars(type);
715 llvm::APInt typeSizeMultiplier(sizeWidth, typeSize.getQuantity());
716 typeSizeMultiplier *= arraySizeMultiplier;
718 // This will be a size_t.
721 // If someone is doing 'new int[42]' there is no need to do a dynamic check.
722 // Don't bloat the -O0 code.
723 if (llvm::ConstantInt *numElementsC =
724 dyn_cast<llvm::ConstantInt>(numElements)) {
725 const llvm::APInt &count = numElementsC->getValue();
727 bool hasAnyOverflow = false;
729 // If 'count' was a negative number, it's an overflow.
730 if (isSigned && count.isNegative())
731 hasAnyOverflow = true;
733 // We want to do all this arithmetic in size_t. If numElements is
734 // wider than that, check whether it's already too big, and if so,
736 else if (numElementsWidth > sizeWidth &&
737 numElementsWidth - sizeWidth > count.countLeadingZeros())
738 hasAnyOverflow = true;
740 // Okay, compute a count at the right width.
741 llvm::APInt adjustedCount = count.zextOrTrunc(sizeWidth);
743 // If there is a brace-initializer, we cannot allocate fewer elements than
744 // there are initializers. If we do, that's treated like an overflow.
745 if (adjustedCount.ult(minElements))
746 hasAnyOverflow = true;
748 // Scale numElements by that. This might overflow, but we don't
749 // care because it only overflows if allocationSize does, too, and
750 // if that overflows then we shouldn't use this.
751 numElements = llvm::ConstantInt::get(CGF.SizeTy,
752 adjustedCount * arraySizeMultiplier);
754 // Compute the size before cookie, and track whether it overflowed.
756 llvm::APInt allocationSize
757 = adjustedCount.umul_ov(typeSizeMultiplier, overflow);
758 hasAnyOverflow |= overflow;
760 // Add in the cookie, and check whether it's overflowed.
761 if (cookieSize != 0) {
762 // Save the current size without a cookie. This shouldn't be
763 // used if there was overflow.
764 sizeWithoutCookie = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
766 allocationSize = allocationSize.uadd_ov(cookieSize, overflow);
767 hasAnyOverflow |= overflow;
770 // On overflow, produce a -1 so operator new will fail.
771 if (hasAnyOverflow) {
772 size = llvm::Constant::getAllOnesValue(CGF.SizeTy);
774 size = llvm::ConstantInt::get(CGF.SizeTy, allocationSize);
777 // Otherwise, we might need to use the overflow intrinsics.
779 // There are up to five conditions we need to test for:
780 // 1) if isSigned, we need to check whether numElements is negative;
781 // 2) if numElementsWidth > sizeWidth, we need to check whether
782 // numElements is larger than something representable in size_t;
783 // 3) if minElements > 0, we need to check whether numElements is smaller
785 // 4) we need to compute
786 // sizeWithoutCookie := numElements * typeSizeMultiplier
787 // and check whether it overflows; and
788 // 5) if we need a cookie, we need to compute
789 // size := sizeWithoutCookie + cookieSize
790 // and check whether it overflows.
792 llvm::Value *hasOverflow = nullptr;
794 // If numElementsWidth > sizeWidth, then one way or another, we're
795 // going to have to do a comparison for (2), and this happens to
796 // take care of (1), too.
797 if (numElementsWidth > sizeWidth) {
798 llvm::APInt threshold(numElementsWidth, 1);
799 threshold <<= sizeWidth;
801 llvm::Value *thresholdV
802 = llvm::ConstantInt::get(numElementsType, threshold);
804 hasOverflow = CGF.Builder.CreateICmpUGE(numElements, thresholdV);
805 numElements = CGF.Builder.CreateTrunc(numElements, CGF.SizeTy);
807 // Otherwise, if we're signed, we want to sext up to size_t.
808 } else if (isSigned) {
809 if (numElementsWidth < sizeWidth)
810 numElements = CGF.Builder.CreateSExt(numElements, CGF.SizeTy);
812 // If there's a non-1 type size multiplier, then we can do the
813 // signedness check at the same time as we do the multiply
814 // because a negative number times anything will cause an
815 // unsigned overflow. Otherwise, we have to do it here. But at least
816 // in this case, we can subsume the >= minElements check.
817 if (typeSizeMultiplier == 1)
818 hasOverflow = CGF.Builder.CreateICmpSLT(numElements,
819 llvm::ConstantInt::get(CGF.SizeTy, minElements));
821 // Otherwise, zext up to size_t if necessary.
822 } else if (numElementsWidth < sizeWidth) {
823 numElements = CGF.Builder.CreateZExt(numElements, CGF.SizeTy);
826 assert(numElements->getType() == CGF.SizeTy);
829 // Don't allow allocation of fewer elements than we have initializers.
831 hasOverflow = CGF.Builder.CreateICmpULT(numElements,
832 llvm::ConstantInt::get(CGF.SizeTy, minElements));
833 } else if (numElementsWidth > sizeWidth) {
834 // The other existing overflow subsumes this check.
835 // We do an unsigned comparison, since any signed value < -1 is
836 // taken care of either above or below.
837 hasOverflow = CGF.Builder.CreateOr(hasOverflow,
838 CGF.Builder.CreateICmpULT(numElements,
839 llvm::ConstantInt::get(CGF.SizeTy, minElements)));
845 // Multiply by the type size if necessary. This multiplier
846 // includes all the factors for nested arrays.
848 // This step also causes numElements to be scaled up by the
849 // nested-array factor if necessary. Overflow on this computation
850 // can be ignored because the result shouldn't be used if
852 if (typeSizeMultiplier != 1) {
853 llvm::Value *umul_with_overflow
854 = CGF.CGM.getIntrinsic(llvm::Intrinsic::umul_with_overflow, CGF.SizeTy);
857 llvm::ConstantInt::get(CGF.SizeTy, typeSizeMultiplier);
858 llvm::Value *result =
859 CGF.Builder.CreateCall(umul_with_overflow, {size, tsmV});
861 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
863 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
865 hasOverflow = overflowed;
867 size = CGF.Builder.CreateExtractValue(result, 0);
869 // Also scale up numElements by the array size multiplier.
870 if (arraySizeMultiplier != 1) {
871 // If the base element type size is 1, then we can re-use the
872 // multiply we just did.
873 if (typeSize.isOne()) {
874 assert(arraySizeMultiplier == typeSizeMultiplier);
877 // Otherwise we need a separate multiply.
880 llvm::ConstantInt::get(CGF.SizeTy, arraySizeMultiplier);
881 numElements = CGF.Builder.CreateMul(numElements, asmV);
885 // numElements doesn't need to be scaled.
886 assert(arraySizeMultiplier == 1);
889 // Add in the cookie size if necessary.
890 if (cookieSize != 0) {
891 sizeWithoutCookie = size;
893 llvm::Value *uadd_with_overflow
894 = CGF.CGM.getIntrinsic(llvm::Intrinsic::uadd_with_overflow, CGF.SizeTy);
896 llvm::Value *cookieSizeV = llvm::ConstantInt::get(CGF.SizeTy, cookieSize);
897 llvm::Value *result =
898 CGF.Builder.CreateCall(uadd_with_overflow, {size, cookieSizeV});
900 llvm::Value *overflowed = CGF.Builder.CreateExtractValue(result, 1);
902 hasOverflow = CGF.Builder.CreateOr(hasOverflow, overflowed);
904 hasOverflow = overflowed;
906 size = CGF.Builder.CreateExtractValue(result, 0);
909 // If we had any possibility of dynamic overflow, make a select to
910 // overwrite 'size' with an all-ones value, which should cause
911 // operator new to throw.
913 size = CGF.Builder.CreateSelect(hasOverflow,
914 llvm::Constant::getAllOnesValue(CGF.SizeTy),
919 sizeWithoutCookie = size;
921 assert(sizeWithoutCookie && "didn't set sizeWithoutCookie?");
926 static void StoreAnyExprIntoOneUnit(CodeGenFunction &CGF, const Expr *Init,
927 QualType AllocType, Address NewPtr) {
928 // FIXME: Refactor with EmitExprAsInit.
929 switch (CGF.getEvaluationKind(AllocType)) {
931 CGF.EmitScalarInit(Init, nullptr,
932 CGF.MakeAddrLValue(NewPtr, AllocType), false);
935 CGF.EmitComplexExprIntoLValue(Init, CGF.MakeAddrLValue(NewPtr, AllocType),
938 case TEK_Aggregate: {
940 = AggValueSlot::forAddr(NewPtr, AllocType.getQualifiers(),
941 AggValueSlot::IsDestructed,
942 AggValueSlot::DoesNotNeedGCBarriers,
943 AggValueSlot::IsNotAliased);
944 CGF.EmitAggExpr(Init, Slot);
948 llvm_unreachable("bad evaluation kind");
951 void CodeGenFunction::EmitNewArrayInitializer(
952 const CXXNewExpr *E, QualType ElementType, llvm::Type *ElementTy,
953 Address BeginPtr, llvm::Value *NumElements,
954 llvm::Value *AllocSizeWithoutCookie) {
955 // If we have a type with trivial initialization and no initializer,
956 // there's nothing to do.
957 if (!E->hasInitializer())
960 Address CurPtr = BeginPtr;
962 unsigned InitListElements = 0;
964 const Expr *Init = E->getInitializer();
965 Address EndOfInit = Address::invalid();
966 QualType::DestructionKind DtorKind = ElementType.isDestructedType();
967 EHScopeStack::stable_iterator Cleanup;
968 llvm::Instruction *CleanupDominator = nullptr;
970 CharUnits ElementSize = getContext().getTypeSizeInChars(ElementType);
971 CharUnits ElementAlign =
972 BeginPtr.getAlignment().alignmentOfArrayElement(ElementSize);
974 // Attempt to perform zero-initialization using memset.
975 auto TryMemsetInitialization = [&]() -> bool {
976 // FIXME: If the type is a pointer-to-data-member under the Itanium ABI,
977 // we can initialize with a memset to -1.
978 if (!CGM.getTypes().isZeroInitializable(ElementType))
981 // Optimization: since zero initialization will just set the memory
982 // to all zeroes, generate a single memset to do it in one shot.
984 // Subtract out the size of any elements we've already initialized.
985 auto *RemainingSize = AllocSizeWithoutCookie;
986 if (InitListElements) {
987 // We know this can't overflow; we check this when doing the allocation.
988 auto *InitializedSize = llvm::ConstantInt::get(
989 RemainingSize->getType(),
990 getContext().getTypeSizeInChars(ElementType).getQuantity() *
992 RemainingSize = Builder.CreateSub(RemainingSize, InitializedSize);
995 // Create the memset.
996 Builder.CreateMemSet(CurPtr, Builder.getInt8(0), RemainingSize, false);
1000 // If the initializer is an initializer list, first do the explicit elements.
1001 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(Init)) {
1002 // Initializing from a (braced) string literal is a special case; the init
1003 // list element does not initialize a (single) array element.
1004 if (ILE->isStringLiteralInit()) {
1005 // Initialize the initial portion of length equal to that of the string
1006 // literal. The allocation must be for at least this much; we emitted a
1007 // check for that earlier.
1009 AggValueSlot::forAddr(CurPtr, ElementType.getQualifiers(),
1010 AggValueSlot::IsDestructed,
1011 AggValueSlot::DoesNotNeedGCBarriers,
1012 AggValueSlot::IsNotAliased);
1013 EmitAggExpr(ILE->getInit(0), Slot);
1015 // Move past these elements.
1017 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1018 ->getSize().getZExtValue();
1020 Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1021 Builder.getSize(InitListElements),
1023 CurPtr.getAlignment().alignmentAtOffset(InitListElements *
1026 // Zero out the rest, if any remain.
1027 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1028 if (!ConstNum || !ConstNum->equalsInt(InitListElements)) {
1029 bool OK = TryMemsetInitialization();
1031 assert(OK && "couldn't memset character type?");
1036 InitListElements = ILE->getNumInits();
1038 // If this is a multi-dimensional array new, we will initialize multiple
1039 // elements with each init list element.
1040 QualType AllocType = E->getAllocatedType();
1041 if (const ConstantArrayType *CAT = dyn_cast_or_null<ConstantArrayType>(
1042 AllocType->getAsArrayTypeUnsafe())) {
1043 ElementTy = ConvertTypeForMem(AllocType);
1044 CurPtr = Builder.CreateElementBitCast(CurPtr, ElementTy);
1045 InitListElements *= getContext().getConstantArrayElementCount(CAT);
1048 // Enter a partial-destruction Cleanup if necessary.
1049 if (needsEHCleanup(DtorKind)) {
1050 // In principle we could tell the Cleanup where we are more
1051 // directly, but the control flow can get so varied here that it
1052 // would actually be quite complex. Therefore we go through an
1054 EndOfInit = CreateTempAlloca(BeginPtr.getType(), getPointerAlign(),
1056 CleanupDominator = Builder.CreateStore(BeginPtr.getPointer(), EndOfInit);
1057 pushIrregularPartialArrayCleanup(BeginPtr.getPointer(), EndOfInit,
1058 ElementType, ElementAlign,
1059 getDestroyer(DtorKind));
1060 Cleanup = EHStack.stable_begin();
1063 CharUnits StartAlign = CurPtr.getAlignment();
1064 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i) {
1065 // Tell the cleanup that it needs to destroy up to this
1066 // element. TODO: some of these stores can be trivially
1067 // observed to be unnecessary.
1068 if (EndOfInit.isValid()) {
1070 Builder.CreateBitCast(CurPtr.getPointer(), BeginPtr.getType());
1071 Builder.CreateStore(FinishedPtr, EndOfInit);
1073 // FIXME: If the last initializer is an incomplete initializer list for
1074 // an array, and we have an array filler, we can fold together the two
1075 // initialization loops.
1076 StoreAnyExprIntoOneUnit(*this, ILE->getInit(i),
1077 ILE->getInit(i)->getType(), CurPtr);
1078 CurPtr = Address(Builder.CreateInBoundsGEP(CurPtr.getPointer(),
1081 StartAlign.alignmentAtOffset((i + 1) * ElementSize));
1084 // The remaining elements are filled with the array filler expression.
1085 Init = ILE->getArrayFiller();
1087 // Extract the initializer for the individual array elements by pulling
1088 // out the array filler from all the nested initializer lists. This avoids
1089 // generating a nested loop for the initialization.
1090 while (Init && Init->getType()->isConstantArrayType()) {
1091 auto *SubILE = dyn_cast<InitListExpr>(Init);
1094 assert(SubILE->getNumInits() == 0 && "explicit inits in array filler?");
1095 Init = SubILE->getArrayFiller();
1098 // Switch back to initializing one base element at a time.
1099 CurPtr = Builder.CreateBitCast(CurPtr, BeginPtr.getType());
1102 // If all elements have already been initialized, skip any further
1104 llvm::ConstantInt *ConstNum = dyn_cast<llvm::ConstantInt>(NumElements);
1105 if (ConstNum && ConstNum->getZExtValue() <= InitListElements) {
1106 // If there was a Cleanup, deactivate it.
1107 if (CleanupDominator)
1108 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1112 assert(Init && "have trailing elements to initialize but no initializer");
1114 // If this is a constructor call, try to optimize it out, and failing that
1115 // emit a single loop to initialize all remaining elements.
1116 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
1117 CXXConstructorDecl *Ctor = CCE->getConstructor();
1118 if (Ctor->isTrivial()) {
1119 // If new expression did not specify value-initialization, then there
1120 // is no initialization.
1121 if (!CCE->requiresZeroInitialization() || Ctor->getParent()->isEmpty())
1124 if (TryMemsetInitialization())
1128 // Store the new Cleanup position for irregular Cleanups.
1130 // FIXME: Share this cleanup with the constructor call emission rather than
1131 // having it create a cleanup of its own.
1132 if (EndOfInit.isValid())
1133 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1135 // Emit a constructor call loop to initialize the remaining elements.
1136 if (InitListElements)
1137 NumElements = Builder.CreateSub(
1139 llvm::ConstantInt::get(NumElements->getType(), InitListElements));
1140 EmitCXXAggrConstructorCall(Ctor, NumElements, CurPtr, CCE,
1141 CCE->requiresZeroInitialization());
1145 // If this is value-initialization, we can usually use memset.
1146 ImplicitValueInitExpr IVIE(ElementType);
1147 if (isa<ImplicitValueInitExpr>(Init)) {
1148 if (TryMemsetInitialization())
1151 // Switch to an ImplicitValueInitExpr for the element type. This handles
1152 // only one case: multidimensional array new of pointers to members. In
1153 // all other cases, we already have an initializer for the array element.
1157 // At this point we should have found an initializer for the individual
1158 // elements of the array.
1159 assert(getContext().hasSameUnqualifiedType(ElementType, Init->getType()) &&
1160 "got wrong type of element to initialize");
1162 // If we have an empty initializer list, we can usually use memset.
1163 if (auto *ILE = dyn_cast<InitListExpr>(Init))
1164 if (ILE->getNumInits() == 0 && TryMemsetInitialization())
1167 // If we have a struct whose every field is value-initialized, we can
1168 // usually use memset.
1169 if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
1170 if (const RecordType *RType = ILE->getType()->getAs<RecordType>()) {
1171 if (RType->getDecl()->isStruct()) {
1172 unsigned NumElements = 0;
1173 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RType->getDecl()))
1174 NumElements = CXXRD->getNumBases();
1175 for (auto *Field : RType->getDecl()->fields())
1176 if (!Field->isUnnamedBitfield())
1178 // FIXME: Recurse into nested InitListExprs.
1179 if (ILE->getNumInits() == NumElements)
1180 for (unsigned i = 0, e = ILE->getNumInits(); i != e; ++i)
1181 if (!isa<ImplicitValueInitExpr>(ILE->getInit(i)))
1183 if (ILE->getNumInits() == NumElements && TryMemsetInitialization())
1189 // Create the loop blocks.
1190 llvm::BasicBlock *EntryBB = Builder.GetInsertBlock();
1191 llvm::BasicBlock *LoopBB = createBasicBlock("new.loop");
1192 llvm::BasicBlock *ContBB = createBasicBlock("new.loop.end");
1194 // Find the end of the array, hoisted out of the loop.
1195 llvm::Value *EndPtr =
1196 Builder.CreateInBoundsGEP(BeginPtr.getPointer(), NumElements, "array.end");
1198 // If the number of elements isn't constant, we have to now check if there is
1199 // anything left to initialize.
1201 llvm::Value *IsEmpty =
1202 Builder.CreateICmpEQ(CurPtr.getPointer(), EndPtr, "array.isempty");
1203 Builder.CreateCondBr(IsEmpty, ContBB, LoopBB);
1209 // Set up the current-element phi.
1210 llvm::PHINode *CurPtrPhi =
1211 Builder.CreatePHI(CurPtr.getType(), 2, "array.cur");
1212 CurPtrPhi->addIncoming(CurPtr.getPointer(), EntryBB);
1214 CurPtr = Address(CurPtrPhi, ElementAlign);
1216 // Store the new Cleanup position for irregular Cleanups.
1217 if (EndOfInit.isValid())
1218 Builder.CreateStore(CurPtr.getPointer(), EndOfInit);
1220 // Enter a partial-destruction Cleanup if necessary.
1221 if (!CleanupDominator && needsEHCleanup(DtorKind)) {
1222 pushRegularPartialArrayCleanup(BeginPtr.getPointer(), CurPtr.getPointer(),
1223 ElementType, ElementAlign,
1224 getDestroyer(DtorKind));
1225 Cleanup = EHStack.stable_begin();
1226 CleanupDominator = Builder.CreateUnreachable();
1229 // Emit the initializer into this element.
1230 StoreAnyExprIntoOneUnit(*this, Init, Init->getType(), CurPtr);
1232 // Leave the Cleanup if we entered one.
1233 if (CleanupDominator) {
1234 DeactivateCleanupBlock(Cleanup, CleanupDominator);
1235 CleanupDominator->eraseFromParent();
1238 // Advance to the next element by adjusting the pointer type as necessary.
1239 llvm::Value *NextPtr =
1240 Builder.CreateConstInBoundsGEP1_32(ElementTy, CurPtr.getPointer(), 1,
1243 // Check whether we've gotten to the end of the array and, if so,
1245 llvm::Value *IsEnd = Builder.CreateICmpEQ(NextPtr, EndPtr, "array.atend");
1246 Builder.CreateCondBr(IsEnd, ContBB, LoopBB);
1247 CurPtrPhi->addIncoming(NextPtr, Builder.GetInsertBlock());
1252 static void EmitNewInitializer(CodeGenFunction &CGF, const CXXNewExpr *E,
1253 QualType ElementType, llvm::Type *ElementTy,
1254 Address NewPtr, llvm::Value *NumElements,
1255 llvm::Value *AllocSizeWithoutCookie) {
1256 ApplyDebugLocation DL(CGF, E);
1258 CGF.EmitNewArrayInitializer(E, ElementType, ElementTy, NewPtr, NumElements,
1259 AllocSizeWithoutCookie);
1260 else if (const Expr *Init = E->getInitializer())
1261 StoreAnyExprIntoOneUnit(CGF, Init, E->getAllocatedType(), NewPtr);
1264 /// Emit a call to an operator new or operator delete function, as implicitly
1265 /// created by new-expressions and delete-expressions.
1266 static RValue EmitNewDeleteCall(CodeGenFunction &CGF,
1267 const FunctionDecl *CalleeDecl,
1268 const FunctionProtoType *CalleeType,
1269 const CallArgList &Args) {
1270 llvm::Instruction *CallOrInvoke;
1271 llvm::Constant *CalleePtr = CGF.CGM.GetAddrOfFunction(CalleeDecl);
1272 CGCallee Callee = CGCallee::forDirect(CalleePtr, CalleeDecl);
1274 CGF.EmitCall(CGF.CGM.getTypes().arrangeFreeFunctionCall(
1275 Args, CalleeType, /*chainCall=*/false),
1276 Callee, ReturnValueSlot(), Args, &CallOrInvoke);
1278 /// C++1y [expr.new]p10:
1279 /// [In a new-expression,] an implementation is allowed to omit a call
1280 /// to a replaceable global allocation function.
1282 /// We model such elidable calls with the 'builtin' attribute.
1283 llvm::Function *Fn = dyn_cast<llvm::Function>(CalleePtr);
1284 if (CalleeDecl->isReplaceableGlobalAllocationFunction() &&
1285 Fn && Fn->hasFnAttribute(llvm::Attribute::NoBuiltin)) {
1286 // FIXME: Add addAttribute to CallSite.
1287 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(CallOrInvoke))
1288 CI->addAttribute(llvm::AttributeList::FunctionIndex,
1289 llvm::Attribute::Builtin);
1290 else if (llvm::InvokeInst *II = dyn_cast<llvm::InvokeInst>(CallOrInvoke))
1291 II->addAttribute(llvm::AttributeList::FunctionIndex,
1292 llvm::Attribute::Builtin);
1294 llvm_unreachable("unexpected kind of call instruction");
1300 RValue CodeGenFunction::EmitBuiltinNewDeleteCall(const FunctionProtoType *Type,
1304 const Stmt *ArgS = Arg;
1305 EmitCallArgs(Args, *Type->param_type_begin(), llvm::makeArrayRef(ArgS));
1306 // Find the allocation or deallocation function that we're calling.
1307 ASTContext &Ctx = getContext();
1308 DeclarationName Name = Ctx.DeclarationNames
1309 .getCXXOperatorName(IsDelete ? OO_Delete : OO_New);
1310 for (auto *Decl : Ctx.getTranslationUnitDecl()->lookup(Name))
1311 if (auto *FD = dyn_cast<FunctionDecl>(Decl))
1312 if (Ctx.hasSameType(FD->getType(), QualType(Type, 0)))
1313 return EmitNewDeleteCall(*this, cast<FunctionDecl>(Decl), Type, Args);
1314 llvm_unreachable("predeclared global operator new/delete is missing");
1318 /// The parameters to pass to a usual operator delete.
1319 struct UsualDeleteParams {
1320 bool DestroyingDelete = false;
1322 bool Alignment = false;
1326 static UsualDeleteParams getUsualDeleteParams(const FunctionDecl *FD) {
1327 UsualDeleteParams Params;
1329 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
1330 auto AI = FPT->param_type_begin(), AE = FPT->param_type_end();
1332 // The first argument is always a void*.
1335 // The next parameter may be a std::destroying_delete_t.
1336 if (FD->isDestroyingOperatorDelete()) {
1337 Params.DestroyingDelete = true;
1342 // Figure out what other parameters we should be implicitly passing.
1343 if (AI != AE && (*AI)->isIntegerType()) {
1348 if (AI != AE && (*AI)->isAlignValT()) {
1349 Params.Alignment = true;
1353 assert(AI == AE && "unexpected usual deallocation function parameter");
1358 /// A cleanup to call the given 'operator delete' function upon abnormal
1359 /// exit from a new expression. Templated on a traits type that deals with
1360 /// ensuring that the arguments dominate the cleanup if necessary.
1361 template<typename Traits>
1362 class CallDeleteDuringNew final : public EHScopeStack::Cleanup {
1363 /// Type used to hold llvm::Value*s.
1364 typedef typename Traits::ValueTy ValueTy;
1365 /// Type used to hold RValues.
1366 typedef typename Traits::RValueTy RValueTy;
1367 struct PlacementArg {
1372 unsigned NumPlacementArgs : 31;
1373 unsigned PassAlignmentToPlacementDelete : 1;
1374 const FunctionDecl *OperatorDelete;
1377 CharUnits AllocAlign;
1379 PlacementArg *getPlacementArgs() {
1380 return reinterpret_cast<PlacementArg *>(this + 1);
1384 static size_t getExtraSize(size_t NumPlacementArgs) {
1385 return NumPlacementArgs * sizeof(PlacementArg);
1388 CallDeleteDuringNew(size_t NumPlacementArgs,
1389 const FunctionDecl *OperatorDelete, ValueTy Ptr,
1390 ValueTy AllocSize, bool PassAlignmentToPlacementDelete,
1391 CharUnits AllocAlign)
1392 : NumPlacementArgs(NumPlacementArgs),
1393 PassAlignmentToPlacementDelete(PassAlignmentToPlacementDelete),
1394 OperatorDelete(OperatorDelete), Ptr(Ptr), AllocSize(AllocSize),
1395 AllocAlign(AllocAlign) {}
1397 void setPlacementArg(unsigned I, RValueTy Arg, QualType Type) {
1398 assert(I < NumPlacementArgs && "index out of range");
1399 getPlacementArgs()[I] = {Arg, Type};
1402 void Emit(CodeGenFunction &CGF, Flags flags) override {
1403 const FunctionProtoType *FPT =
1404 OperatorDelete->getType()->getAs<FunctionProtoType>();
1405 CallArgList DeleteArgs;
1407 // The first argument is always a void* (or C* for a destroying operator
1408 // delete for class type C).
1409 DeleteArgs.add(Traits::get(CGF, Ptr), FPT->getParamType(0));
1411 // Figure out what other parameters we should be implicitly passing.
1412 UsualDeleteParams Params;
1413 if (NumPlacementArgs) {
1414 // A placement deallocation function is implicitly passed an alignment
1415 // if the placement allocation function was, but is never passed a size.
1416 Params.Alignment = PassAlignmentToPlacementDelete;
1418 // For a non-placement new-expression, 'operator delete' can take a
1419 // size and/or an alignment if it has the right parameters.
1420 Params = getUsualDeleteParams(OperatorDelete);
1423 assert(!Params.DestroyingDelete &&
1424 "should not call destroying delete in a new-expression");
1426 // The second argument can be a std::size_t (for non-placement delete).
1428 DeleteArgs.add(Traits::get(CGF, AllocSize),
1429 CGF.getContext().getSizeType());
1431 // The next (second or third) argument can be a std::align_val_t, which
1432 // is an enum whose underlying type is std::size_t.
1433 // FIXME: Use the right type as the parameter type. Note that in a call
1434 // to operator delete(size_t, ...), we may not have it available.
1435 if (Params.Alignment)
1436 DeleteArgs.add(RValue::get(llvm::ConstantInt::get(
1437 CGF.SizeTy, AllocAlign.getQuantity())),
1438 CGF.getContext().getSizeType());
1440 // Pass the rest of the arguments, which must match exactly.
1441 for (unsigned I = 0; I != NumPlacementArgs; ++I) {
1442 auto Arg = getPlacementArgs()[I];
1443 DeleteArgs.add(Traits::get(CGF, Arg.ArgValue), Arg.ArgType);
1446 // Call 'operator delete'.
1447 EmitNewDeleteCall(CGF, OperatorDelete, FPT, DeleteArgs);
1452 /// Enter a cleanup to call 'operator delete' if the initializer in a
1453 /// new-expression throws.
1454 static void EnterNewDeleteCleanup(CodeGenFunction &CGF,
1455 const CXXNewExpr *E,
1457 llvm::Value *AllocSize,
1458 CharUnits AllocAlign,
1459 const CallArgList &NewArgs) {
1460 unsigned NumNonPlacementArgs = E->passAlignment() ? 2 : 1;
1462 // If we're not inside a conditional branch, then the cleanup will
1463 // dominate and we can do the easier (and more efficient) thing.
1464 if (!CGF.isInConditionalBranch()) {
1465 struct DirectCleanupTraits {
1466 typedef llvm::Value *ValueTy;
1467 typedef RValue RValueTy;
1468 static RValue get(CodeGenFunction &, ValueTy V) { return RValue::get(V); }
1469 static RValue get(CodeGenFunction &, RValueTy V) { return V; }
1472 typedef CallDeleteDuringNew<DirectCleanupTraits> DirectCleanup;
1474 DirectCleanup *Cleanup = CGF.EHStack
1475 .pushCleanupWithExtra<DirectCleanup>(EHCleanup,
1476 E->getNumPlacementArgs(),
1477 E->getOperatorDelete(),
1478 NewPtr.getPointer(),
1482 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1483 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1484 Cleanup->setPlacementArg(I, Arg.RV, Arg.Ty);
1490 // Otherwise, we need to save all this stuff.
1491 DominatingValue<RValue>::saved_type SavedNewPtr =
1492 DominatingValue<RValue>::save(CGF, RValue::get(NewPtr.getPointer()));
1493 DominatingValue<RValue>::saved_type SavedAllocSize =
1494 DominatingValue<RValue>::save(CGF, RValue::get(AllocSize));
1496 struct ConditionalCleanupTraits {
1497 typedef DominatingValue<RValue>::saved_type ValueTy;
1498 typedef DominatingValue<RValue>::saved_type RValueTy;
1499 static RValue get(CodeGenFunction &CGF, ValueTy V) {
1500 return V.restore(CGF);
1503 typedef CallDeleteDuringNew<ConditionalCleanupTraits> ConditionalCleanup;
1505 ConditionalCleanup *Cleanup = CGF.EHStack
1506 .pushCleanupWithExtra<ConditionalCleanup>(EHCleanup,
1507 E->getNumPlacementArgs(),
1508 E->getOperatorDelete(),
1513 for (unsigned I = 0, N = E->getNumPlacementArgs(); I != N; ++I) {
1514 auto &Arg = NewArgs[I + NumNonPlacementArgs];
1515 Cleanup->setPlacementArg(I, DominatingValue<RValue>::save(CGF, Arg.RV),
1519 CGF.initFullExprCleanup();
1522 llvm::Value *CodeGenFunction::EmitCXXNewExpr(const CXXNewExpr *E) {
1523 // The element type being allocated.
1524 QualType allocType = getContext().getBaseElementType(E->getAllocatedType());
1526 // 1. Build a call to the allocation function.
1527 FunctionDecl *allocator = E->getOperatorNew();
1529 // If there is a brace-initializer, cannot allocate fewer elements than inits.
1530 unsigned minElements = 0;
1531 if (E->isArray() && E->hasInitializer()) {
1532 const InitListExpr *ILE = dyn_cast<InitListExpr>(E->getInitializer());
1533 if (ILE && ILE->isStringLiteralInit())
1535 cast<ConstantArrayType>(ILE->getType()->getAsArrayTypeUnsafe())
1536 ->getSize().getZExtValue();
1538 minElements = ILE->getNumInits();
1541 llvm::Value *numElements = nullptr;
1542 llvm::Value *allocSizeWithoutCookie = nullptr;
1543 llvm::Value *allocSize =
1544 EmitCXXNewAllocSize(*this, E, minElements, numElements,
1545 allocSizeWithoutCookie);
1546 CharUnits allocAlign = getContext().getTypeAlignInChars(allocType);
1548 // Emit the allocation call. If the allocator is a global placement
1549 // operator, just "inline" it directly.
1550 Address allocation = Address::invalid();
1551 CallArgList allocatorArgs;
1552 if (allocator->isReservedGlobalPlacementOperator()) {
1553 assert(E->getNumPlacementArgs() == 1);
1554 const Expr *arg = *E->placement_arguments().begin();
1556 LValueBaseInfo BaseInfo;
1557 allocation = EmitPointerWithAlignment(arg, &BaseInfo);
1559 // The pointer expression will, in many cases, be an opaque void*.
1560 // In these cases, discard the computed alignment and use the
1561 // formal alignment of the allocated type.
1562 if (BaseInfo.getAlignmentSource() != AlignmentSource::Decl)
1563 allocation = Address(allocation.getPointer(), allocAlign);
1565 // Set up allocatorArgs for the call to operator delete if it's not
1566 // the reserved global operator.
1567 if (E->getOperatorDelete() &&
1568 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1569 allocatorArgs.add(RValue::get(allocSize), getContext().getSizeType());
1570 allocatorArgs.add(RValue::get(allocation.getPointer()), arg->getType());
1574 const FunctionProtoType *allocatorType =
1575 allocator->getType()->castAs<FunctionProtoType>();
1576 unsigned ParamsToSkip = 0;
1578 // The allocation size is the first argument.
1579 QualType sizeType = getContext().getSizeType();
1580 allocatorArgs.add(RValue::get(allocSize), sizeType);
1583 if (allocSize != allocSizeWithoutCookie) {
1584 CharUnits cookieAlign = getSizeAlign(); // FIXME: Ask the ABI.
1585 allocAlign = std::max(allocAlign, cookieAlign);
1588 // The allocation alignment may be passed as the second argument.
1589 if (E->passAlignment()) {
1590 QualType AlignValT = sizeType;
1591 if (allocatorType->getNumParams() > 1) {
1592 AlignValT = allocatorType->getParamType(1);
1593 assert(getContext().hasSameUnqualifiedType(
1594 AlignValT->castAs<EnumType>()->getDecl()->getIntegerType(),
1596 "wrong type for alignment parameter");
1599 // Corner case, passing alignment to 'operator new(size_t, ...)'.
1600 assert(allocator->isVariadic() && "can't pass alignment to allocator");
1603 RValue::get(llvm::ConstantInt::get(SizeTy, allocAlign.getQuantity())),
1607 // FIXME: Why do we not pass a CalleeDecl here?
1608 EmitCallArgs(allocatorArgs, allocatorType, E->placement_arguments(),
1609 /*AC*/AbstractCallee(), /*ParamsToSkip*/ParamsToSkip);
1612 EmitNewDeleteCall(*this, allocator, allocatorType, allocatorArgs);
1614 // If this was a call to a global replaceable allocation function that does
1615 // not take an alignment argument, the allocator is known to produce
1616 // storage that's suitably aligned for any object that fits, up to a known
1617 // threshold. Otherwise assume it's suitably aligned for the allocated type.
1618 CharUnits allocationAlign = allocAlign;
1619 if (!E->passAlignment() &&
1620 allocator->isReplaceableGlobalAllocationFunction()) {
1621 unsigned AllocatorAlign = llvm::PowerOf2Floor(std::min<uint64_t>(
1622 Target.getNewAlign(), getContext().getTypeSize(allocType)));
1623 allocationAlign = std::max(
1624 allocationAlign, getContext().toCharUnitsFromBits(AllocatorAlign));
1627 allocation = Address(RV.getScalarVal(), allocationAlign);
1630 // Emit a null check on the allocation result if the allocation
1631 // function is allowed to return null (because it has a non-throwing
1632 // exception spec or is the reserved placement new) and we have an
1633 // interesting initializer.
1634 bool nullCheck = E->shouldNullCheckAllocation(getContext()) &&
1635 (!allocType.isPODType(getContext()) || E->hasInitializer());
1637 llvm::BasicBlock *nullCheckBB = nullptr;
1638 llvm::BasicBlock *contBB = nullptr;
1640 // The null-check means that the initializer is conditionally
1642 ConditionalEvaluation conditional(*this);
1645 conditional.begin(*this);
1647 nullCheckBB = Builder.GetInsertBlock();
1648 llvm::BasicBlock *notNullBB = createBasicBlock("new.notnull");
1649 contBB = createBasicBlock("new.cont");
1651 llvm::Value *isNull =
1652 Builder.CreateIsNull(allocation.getPointer(), "new.isnull");
1653 Builder.CreateCondBr(isNull, contBB, notNullBB);
1654 EmitBlock(notNullBB);
1657 // If there's an operator delete, enter a cleanup to call it if an
1658 // exception is thrown.
1659 EHScopeStack::stable_iterator operatorDeleteCleanup;
1660 llvm::Instruction *cleanupDominator = nullptr;
1661 if (E->getOperatorDelete() &&
1662 !E->getOperatorDelete()->isReservedGlobalPlacementOperator()) {
1663 EnterNewDeleteCleanup(*this, E, allocation, allocSize, allocAlign,
1665 operatorDeleteCleanup = EHStack.stable_begin();
1666 cleanupDominator = Builder.CreateUnreachable();
1669 assert((allocSize == allocSizeWithoutCookie) ==
1670 CalculateCookiePadding(*this, E).isZero());
1671 if (allocSize != allocSizeWithoutCookie) {
1672 assert(E->isArray());
1673 allocation = CGM.getCXXABI().InitializeArrayCookie(*this, allocation,
1678 llvm::Type *elementTy = ConvertTypeForMem(allocType);
1679 Address result = Builder.CreateElementBitCast(allocation, elementTy);
1681 // Passing pointer through invariant.group.barrier to avoid propagation of
1682 // vptrs information which may be included in previous type.
1683 // To not break LTO with different optimizations levels, we do it regardless
1684 // of optimization level.
1685 if (CGM.getCodeGenOpts().StrictVTablePointers &&
1686 allocator->isReservedGlobalPlacementOperator())
1687 result = Address(Builder.CreateInvariantGroupBarrier(result.getPointer()),
1688 result.getAlignment());
1690 EmitNewInitializer(*this, E, allocType, elementTy, result, numElements,
1691 allocSizeWithoutCookie);
1693 // NewPtr is a pointer to the base element type. If we're
1694 // allocating an array of arrays, we'll need to cast back to the
1695 // array pointer type.
1696 llvm::Type *resultType = ConvertTypeForMem(E->getType());
1697 if (result.getType() != resultType)
1698 result = Builder.CreateBitCast(result, resultType);
1701 // Deactivate the 'operator delete' cleanup if we finished
1703 if (operatorDeleteCleanup.isValid()) {
1704 DeactivateCleanupBlock(operatorDeleteCleanup, cleanupDominator);
1705 cleanupDominator->eraseFromParent();
1708 llvm::Value *resultPtr = result.getPointer();
1710 conditional.end(*this);
1712 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
1715 llvm::PHINode *PHI = Builder.CreatePHI(resultPtr->getType(), 2);
1716 PHI->addIncoming(resultPtr, notNullBB);
1717 PHI->addIncoming(llvm::Constant::getNullValue(resultPtr->getType()),
1726 void CodeGenFunction::EmitDeleteCall(const FunctionDecl *DeleteFD,
1727 llvm::Value *Ptr, QualType DeleteTy,
1728 llvm::Value *NumElements,
1729 CharUnits CookieSize) {
1730 assert((!NumElements && CookieSize.isZero()) ||
1731 DeleteFD->getOverloadedOperator() == OO_Array_Delete);
1733 const FunctionProtoType *DeleteFTy =
1734 DeleteFD->getType()->getAs<FunctionProtoType>();
1736 CallArgList DeleteArgs;
1738 auto Params = getUsualDeleteParams(DeleteFD);
1739 auto ParamTypeIt = DeleteFTy->param_type_begin();
1741 // Pass the pointer itself.
1742 QualType ArgTy = *ParamTypeIt++;
1743 llvm::Value *DeletePtr = Builder.CreateBitCast(Ptr, ConvertType(ArgTy));
1744 DeleteArgs.add(RValue::get(DeletePtr), ArgTy);
1746 // Pass the std::destroying_delete tag if present.
1747 if (Params.DestroyingDelete) {
1748 QualType DDTag = *ParamTypeIt++;
1749 // Just pass an 'undef'. We expect the tag type to be an empty struct.
1750 auto *V = llvm::UndefValue::get(getTypes().ConvertType(DDTag));
1751 DeleteArgs.add(RValue::get(V), DDTag);
1754 // Pass the size if the delete function has a size_t parameter.
1756 QualType SizeType = *ParamTypeIt++;
1757 CharUnits DeleteTypeSize = getContext().getTypeSizeInChars(DeleteTy);
1758 llvm::Value *Size = llvm::ConstantInt::get(ConvertType(SizeType),
1759 DeleteTypeSize.getQuantity());
1761 // For array new, multiply by the number of elements.
1763 Size = Builder.CreateMul(Size, NumElements);
1765 // If there is a cookie, add the cookie size.
1766 if (!CookieSize.isZero())
1767 Size = Builder.CreateAdd(
1768 Size, llvm::ConstantInt::get(SizeTy, CookieSize.getQuantity()));
1770 DeleteArgs.add(RValue::get(Size), SizeType);
1773 // Pass the alignment if the delete function has an align_val_t parameter.
1774 if (Params.Alignment) {
1775 QualType AlignValType = *ParamTypeIt++;
1776 CharUnits DeleteTypeAlign = getContext().toCharUnitsFromBits(
1777 getContext().getTypeAlignIfKnown(DeleteTy));
1778 llvm::Value *Align = llvm::ConstantInt::get(ConvertType(AlignValType),
1779 DeleteTypeAlign.getQuantity());
1780 DeleteArgs.add(RValue::get(Align), AlignValType);
1783 assert(ParamTypeIt == DeleteFTy->param_type_end() &&
1784 "unknown parameter to usual delete function");
1786 // Emit the call to delete.
1787 EmitNewDeleteCall(*this, DeleteFD, DeleteFTy, DeleteArgs);
1791 /// Calls the given 'operator delete' on a single object.
1792 struct CallObjectDelete final : EHScopeStack::Cleanup {
1794 const FunctionDecl *OperatorDelete;
1795 QualType ElementType;
1797 CallObjectDelete(llvm::Value *Ptr,
1798 const FunctionDecl *OperatorDelete,
1799 QualType ElementType)
1800 : Ptr(Ptr), OperatorDelete(OperatorDelete), ElementType(ElementType) {}
1802 void Emit(CodeGenFunction &CGF, Flags flags) override {
1803 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType);
1809 CodeGenFunction::pushCallObjectDeleteCleanup(const FunctionDecl *OperatorDelete,
1810 llvm::Value *CompletePtr,
1811 QualType ElementType) {
1812 EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup, CompletePtr,
1813 OperatorDelete, ElementType);
1816 /// Emit the code for deleting a single object with a destroying operator
1817 /// delete. If the element type has a non-virtual destructor, Ptr has already
1818 /// been converted to the type of the parameter of 'operator delete'. Otherwise
1819 /// Ptr points to an object of the static type.
1820 static void EmitDestroyingObjectDelete(CodeGenFunction &CGF,
1821 const CXXDeleteExpr *DE, Address Ptr,
1822 QualType ElementType) {
1823 auto *Dtor = ElementType->getAsCXXRecordDecl()->getDestructor();
1824 if (Dtor && Dtor->isVirtual())
1825 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1828 CGF.EmitDeleteCall(DE->getOperatorDelete(), Ptr.getPointer(), ElementType);
1831 /// Emit the code for deleting a single object.
1832 static void EmitObjectDelete(CodeGenFunction &CGF,
1833 const CXXDeleteExpr *DE,
1835 QualType ElementType) {
1836 // C++11 [expr.delete]p3:
1837 // If the static type of the object to be deleted is different from its
1838 // dynamic type, the static type shall be a base class of the dynamic type
1839 // of the object to be deleted and the static type shall have a virtual
1840 // destructor or the behavior is undefined.
1841 CGF.EmitTypeCheck(CodeGenFunction::TCK_MemberCall,
1842 DE->getExprLoc(), Ptr.getPointer(),
1845 const FunctionDecl *OperatorDelete = DE->getOperatorDelete();
1846 assert(!OperatorDelete->isDestroyingOperatorDelete());
1848 // Find the destructor for the type, if applicable. If the
1849 // destructor is virtual, we'll just emit the vcall and return.
1850 const CXXDestructorDecl *Dtor = nullptr;
1851 if (const RecordType *RT = ElementType->getAs<RecordType>()) {
1852 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
1853 if (RD->hasDefinition() && !RD->hasTrivialDestructor()) {
1854 Dtor = RD->getDestructor();
1856 if (Dtor->isVirtual()) {
1857 CGF.CGM.getCXXABI().emitVirtualObjectDelete(CGF, DE, Ptr, ElementType,
1864 // Make sure that we call delete even if the dtor throws.
1865 // This doesn't have to a conditional cleanup because we're going
1866 // to pop it off in a second.
1867 CGF.EHStack.pushCleanup<CallObjectDelete>(NormalAndEHCleanup,
1869 OperatorDelete, ElementType);
1872 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1873 /*ForVirtualBase=*/false,
1874 /*Delegating=*/false,
1876 else if (auto Lifetime = ElementType.getObjCLifetime()) {
1878 case Qualifiers::OCL_None:
1879 case Qualifiers::OCL_ExplicitNone:
1880 case Qualifiers::OCL_Autoreleasing:
1883 case Qualifiers::OCL_Strong:
1884 CGF.EmitARCDestroyStrong(Ptr, ARCPreciseLifetime);
1887 case Qualifiers::OCL_Weak:
1888 CGF.EmitARCDestroyWeak(Ptr);
1893 CGF.PopCleanupBlock();
1897 /// Calls the given 'operator delete' on an array of objects.
1898 struct CallArrayDelete final : EHScopeStack::Cleanup {
1900 const FunctionDecl *OperatorDelete;
1901 llvm::Value *NumElements;
1902 QualType ElementType;
1903 CharUnits CookieSize;
1905 CallArrayDelete(llvm::Value *Ptr,
1906 const FunctionDecl *OperatorDelete,
1907 llvm::Value *NumElements,
1908 QualType ElementType,
1909 CharUnits CookieSize)
1910 : Ptr(Ptr), OperatorDelete(OperatorDelete), NumElements(NumElements),
1911 ElementType(ElementType), CookieSize(CookieSize) {}
1913 void Emit(CodeGenFunction &CGF, Flags flags) override {
1914 CGF.EmitDeleteCall(OperatorDelete, Ptr, ElementType, NumElements,
1920 /// Emit the code for deleting an array of objects.
1921 static void EmitArrayDelete(CodeGenFunction &CGF,
1922 const CXXDeleteExpr *E,
1924 QualType elementType) {
1925 llvm::Value *numElements = nullptr;
1926 llvm::Value *allocatedPtr = nullptr;
1927 CharUnits cookieSize;
1928 CGF.CGM.getCXXABI().ReadArrayCookie(CGF, deletedPtr, E, elementType,
1929 numElements, allocatedPtr, cookieSize);
1931 assert(allocatedPtr && "ReadArrayCookie didn't set allocated pointer");
1933 // Make sure that we call delete even if one of the dtors throws.
1934 const FunctionDecl *operatorDelete = E->getOperatorDelete();
1935 CGF.EHStack.pushCleanup<CallArrayDelete>(NormalAndEHCleanup,
1936 allocatedPtr, operatorDelete,
1937 numElements, elementType,
1940 // Destroy the elements.
1941 if (QualType::DestructionKind dtorKind = elementType.isDestructedType()) {
1942 assert(numElements && "no element count for a type with a destructor!");
1944 CharUnits elementSize = CGF.getContext().getTypeSizeInChars(elementType);
1945 CharUnits elementAlign =
1946 deletedPtr.getAlignment().alignmentOfArrayElement(elementSize);
1948 llvm::Value *arrayBegin = deletedPtr.getPointer();
1949 llvm::Value *arrayEnd =
1950 CGF.Builder.CreateInBoundsGEP(arrayBegin, numElements, "delete.end");
1952 // Note that it is legal to allocate a zero-length array, and we
1953 // can never fold the check away because the length should always
1954 // come from a cookie.
1955 CGF.emitArrayDestroy(arrayBegin, arrayEnd, elementType, elementAlign,
1956 CGF.getDestroyer(dtorKind),
1957 /*checkZeroLength*/ true,
1958 CGF.needsEHCleanup(dtorKind));
1961 // Pop the cleanup block.
1962 CGF.PopCleanupBlock();
1965 void CodeGenFunction::EmitCXXDeleteExpr(const CXXDeleteExpr *E) {
1966 const Expr *Arg = E->getArgument();
1967 Address Ptr = EmitPointerWithAlignment(Arg);
1969 // Null check the pointer.
1970 llvm::BasicBlock *DeleteNotNull = createBasicBlock("delete.notnull");
1971 llvm::BasicBlock *DeleteEnd = createBasicBlock("delete.end");
1973 llvm::Value *IsNull = Builder.CreateIsNull(Ptr.getPointer(), "isnull");
1975 Builder.CreateCondBr(IsNull, DeleteEnd, DeleteNotNull);
1976 EmitBlock(DeleteNotNull);
1978 QualType DeleteTy = E->getDestroyedType();
1980 // A destroying operator delete overrides the entire operation of the
1981 // delete expression.
1982 if (E->getOperatorDelete()->isDestroyingOperatorDelete()) {
1983 EmitDestroyingObjectDelete(*this, E, Ptr, DeleteTy);
1984 EmitBlock(DeleteEnd);
1988 // We might be deleting a pointer to array. If so, GEP down to the
1989 // first non-array element.
1990 // (this assumes that A(*)[3][7] is converted to [3 x [7 x %A]]*)
1991 if (DeleteTy->isConstantArrayType()) {
1992 llvm::Value *Zero = Builder.getInt32(0);
1993 SmallVector<llvm::Value*,8> GEP;
1995 GEP.push_back(Zero); // point at the outermost array
1997 // For each layer of array type we're pointing at:
1998 while (const ConstantArrayType *Arr
1999 = getContext().getAsConstantArrayType(DeleteTy)) {
2000 // 1. Unpeel the array type.
2001 DeleteTy = Arr->getElementType();
2003 // 2. GEP to the first element of the array.
2004 GEP.push_back(Zero);
2007 Ptr = Address(Builder.CreateInBoundsGEP(Ptr.getPointer(), GEP, "del.first"),
2008 Ptr.getAlignment());
2011 assert(ConvertTypeForMem(DeleteTy) == Ptr.getElementType());
2013 if (E->isArrayForm()) {
2014 EmitArrayDelete(*this, E, Ptr, DeleteTy);
2016 EmitObjectDelete(*this, E, Ptr, DeleteTy);
2019 EmitBlock(DeleteEnd);
2022 static bool isGLValueFromPointerDeref(const Expr *E) {
2023 E = E->IgnoreParens();
2025 if (const auto *CE = dyn_cast<CastExpr>(E)) {
2026 if (!CE->getSubExpr()->isGLValue())
2028 return isGLValueFromPointerDeref(CE->getSubExpr());
2031 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
2032 return isGLValueFromPointerDeref(OVE->getSourceExpr());
2034 if (const auto *BO = dyn_cast<BinaryOperator>(E))
2035 if (BO->getOpcode() == BO_Comma)
2036 return isGLValueFromPointerDeref(BO->getRHS());
2038 if (const auto *ACO = dyn_cast<AbstractConditionalOperator>(E))
2039 return isGLValueFromPointerDeref(ACO->getTrueExpr()) ||
2040 isGLValueFromPointerDeref(ACO->getFalseExpr());
2042 // C++11 [expr.sub]p1:
2043 // The expression E1[E2] is identical (by definition) to *((E1)+(E2))
2044 if (isa<ArraySubscriptExpr>(E))
2047 if (const auto *UO = dyn_cast<UnaryOperator>(E))
2048 if (UO->getOpcode() == UO_Deref)
2054 static llvm::Value *EmitTypeidFromVTable(CodeGenFunction &CGF, const Expr *E,
2055 llvm::Type *StdTypeInfoPtrTy) {
2056 // Get the vtable pointer.
2057 Address ThisPtr = CGF.EmitLValue(E).getAddress();
2059 QualType SrcRecordTy = E->getType();
2061 // C++ [class.cdtor]p4:
2062 // If the operand of typeid refers to the object under construction or
2063 // destruction and the static type of the operand is neither the constructor
2064 // or destructor’s class nor one of its bases, the behavior is undefined.
2065 CGF.EmitTypeCheck(CodeGenFunction::TCK_DynamicOperation, E->getExprLoc(),
2066 ThisPtr.getPointer(), SrcRecordTy);
2068 // C++ [expr.typeid]p2:
2069 // If the glvalue expression is obtained by applying the unary * operator to
2070 // a pointer and the pointer is a null pointer value, the typeid expression
2071 // throws the std::bad_typeid exception.
2073 // However, this paragraph's intent is not clear. We choose a very generous
2074 // interpretation which implores us to consider comma operators, conditional
2075 // operators, parentheses and other such constructs.
2076 if (CGF.CGM.getCXXABI().shouldTypeidBeNullChecked(
2077 isGLValueFromPointerDeref(E), SrcRecordTy)) {
2078 llvm::BasicBlock *BadTypeidBlock =
2079 CGF.createBasicBlock("typeid.bad_typeid");
2080 llvm::BasicBlock *EndBlock = CGF.createBasicBlock("typeid.end");
2082 llvm::Value *IsNull = CGF.Builder.CreateIsNull(ThisPtr.getPointer());
2083 CGF.Builder.CreateCondBr(IsNull, BadTypeidBlock, EndBlock);
2085 CGF.EmitBlock(BadTypeidBlock);
2086 CGF.CGM.getCXXABI().EmitBadTypeidCall(CGF);
2087 CGF.EmitBlock(EndBlock);
2090 return CGF.CGM.getCXXABI().EmitTypeid(CGF, SrcRecordTy, ThisPtr,
2094 llvm::Value *CodeGenFunction::EmitCXXTypeidExpr(const CXXTypeidExpr *E) {
2095 llvm::Type *StdTypeInfoPtrTy =
2096 ConvertType(E->getType())->getPointerTo();
2098 if (E->isTypeOperand()) {
2099 llvm::Constant *TypeInfo =
2100 CGM.GetAddrOfRTTIDescriptor(E->getTypeOperand(getContext()));
2101 return Builder.CreateBitCast(TypeInfo, StdTypeInfoPtrTy);
2104 // C++ [expr.typeid]p2:
2105 // When typeid is applied to a glvalue expression whose type is a
2106 // polymorphic class type, the result refers to a std::type_info object
2107 // representing the type of the most derived object (that is, the dynamic
2108 // type) to which the glvalue refers.
2109 if (E->isPotentiallyEvaluated())
2110 return EmitTypeidFromVTable(*this, E->getExprOperand(),
2113 QualType OperandTy = E->getExprOperand()->getType();
2114 return Builder.CreateBitCast(CGM.GetAddrOfRTTIDescriptor(OperandTy),
2118 static llvm::Value *EmitDynamicCastToNull(CodeGenFunction &CGF,
2120 llvm::Type *DestLTy = CGF.ConvertType(DestTy);
2121 if (DestTy->isPointerType())
2122 return llvm::Constant::getNullValue(DestLTy);
2124 /// C++ [expr.dynamic.cast]p9:
2125 /// A failed cast to reference type throws std::bad_cast
2126 if (!CGF.CGM.getCXXABI().EmitBadCastCall(CGF))
2129 CGF.EmitBlock(CGF.createBasicBlock("dynamic_cast.end"));
2130 return llvm::UndefValue::get(DestLTy);
2133 llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
2134 const CXXDynamicCastExpr *DCE) {
2135 CGM.EmitExplicitCastExprType(DCE, this);
2136 QualType DestTy = DCE->getTypeAsWritten();
2138 QualType SrcTy = DCE->getSubExpr()->getType();
2140 // C++ [expr.dynamic.cast]p7:
2141 // If T is "pointer to cv void," then the result is a pointer to the most
2142 // derived object pointed to by v.
2143 const PointerType *DestPTy = DestTy->getAs<PointerType>();
2145 bool isDynamicCastToVoid;
2146 QualType SrcRecordTy;
2147 QualType DestRecordTy;
2149 isDynamicCastToVoid = DestPTy->getPointeeType()->isVoidType();
2150 SrcRecordTy = SrcTy->castAs<PointerType>()->getPointeeType();
2151 DestRecordTy = DestPTy->getPointeeType();
2153 isDynamicCastToVoid = false;
2154 SrcRecordTy = SrcTy;
2155 DestRecordTy = DestTy->castAs<ReferenceType>()->getPointeeType();
2158 // C++ [class.cdtor]p5:
2159 // If the operand of the dynamic_cast refers to the object under
2160 // construction or destruction and the static type of the operand is not a
2161 // pointer to or object of the constructor or destructor’s own class or one
2162 // of its bases, the dynamic_cast results in undefined behavior.
2163 EmitTypeCheck(TCK_DynamicOperation, DCE->getExprLoc(), ThisAddr.getPointer(),
2166 if (DCE->isAlwaysNull())
2167 if (llvm::Value *T = EmitDynamicCastToNull(*this, DestTy))
2170 assert(SrcRecordTy->isRecordType() && "source type must be a record type!");
2172 // C++ [expr.dynamic.cast]p4:
2173 // If the value of v is a null pointer value in the pointer case, the result
2174 // is the null pointer value of type T.
2175 bool ShouldNullCheckSrcValue =
2176 CGM.getCXXABI().shouldDynamicCastCallBeNullChecked(SrcTy->isPointerType(),
2179 llvm::BasicBlock *CastNull = nullptr;
2180 llvm::BasicBlock *CastNotNull = nullptr;
2181 llvm::BasicBlock *CastEnd = createBasicBlock("dynamic_cast.end");
2183 if (ShouldNullCheckSrcValue) {
2184 CastNull = createBasicBlock("dynamic_cast.null");
2185 CastNotNull = createBasicBlock("dynamic_cast.notnull");
2187 llvm::Value *IsNull = Builder.CreateIsNull(ThisAddr.getPointer());
2188 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
2189 EmitBlock(CastNotNull);
2193 if (isDynamicCastToVoid) {
2194 Value = CGM.getCXXABI().EmitDynamicCastToVoid(*this, ThisAddr, SrcRecordTy,
2197 assert(DestRecordTy->isRecordType() &&
2198 "destination type must be a record type!");
2199 Value = CGM.getCXXABI().EmitDynamicCastCall(*this, ThisAddr, SrcRecordTy,
2200 DestTy, DestRecordTy, CastEnd);
2201 CastNotNull = Builder.GetInsertBlock();
2204 if (ShouldNullCheckSrcValue) {
2205 EmitBranch(CastEnd);
2207 EmitBlock(CastNull);
2208 EmitBranch(CastEnd);
2213 if (ShouldNullCheckSrcValue) {
2214 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
2215 PHI->addIncoming(Value, CastNotNull);
2216 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull);
2224 void CodeGenFunction::EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Slot) {
2225 RunCleanupsScope Scope(*this);
2226 LValue SlotLV = MakeAddrLValue(Slot.getAddress(), E->getType());
2228 CXXRecordDecl::field_iterator CurField = E->getLambdaClass()->field_begin();
2229 for (LambdaExpr::const_capture_init_iterator i = E->capture_init_begin(),
2230 e = E->capture_init_end();
2231 i != e; ++i, ++CurField) {
2232 // Emit initialization
2233 LValue LV = EmitLValueForFieldInitialization(SlotLV, *CurField);
2234 if (CurField->hasCapturedVLAType()) {
2235 auto VAT = CurField->getCapturedVLAType();
2236 EmitStoreThroughLValue(RValue::get(VLASizeMap[VAT->getSizeExpr()]), LV);
2238 EmitInitializerForField(*CurField, LV, *i);