1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
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 C++ code generation of classes
12 //===----------------------------------------------------------------------===//
16 #include "CGDebugInfo.h"
17 #include "CGRecordLayout.h"
18 #include "CodeGenFunction.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/EvaluatedExprVisitor.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtCXX.h"
24 #include "clang/Basic/TargetBuiltins.h"
25 #include "clang/CodeGen/CGFunctionInfo.h"
26 #include "clang/Frontend/CodeGenOptions.h"
28 using namespace clang;
29 using namespace CodeGen;
32 ComputeNonVirtualBaseClassOffset(ASTContext &Context,
33 const CXXRecordDecl *DerivedClass,
34 CastExpr::path_const_iterator Start,
35 CastExpr::path_const_iterator End) {
36 CharUnits Offset = CharUnits::Zero();
38 const CXXRecordDecl *RD = DerivedClass;
40 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
41 const CXXBaseSpecifier *Base = *I;
42 assert(!Base->isVirtual() && "Should not see virtual bases here!");
45 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
47 const CXXRecordDecl *BaseDecl =
48 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
51 Offset += Layout.getBaseClassOffset(BaseDecl);
60 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
61 CastExpr::path_const_iterator PathBegin,
62 CastExpr::path_const_iterator PathEnd) {
63 assert(PathBegin != PathEnd && "Base path should not be empty!");
66 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
71 llvm::Type *PtrDiffTy =
72 Types.ConvertType(getContext().getPointerDiffType());
74 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
77 /// Gets the address of a direct base class within a complete object.
78 /// This should only be used for (1) non-virtual bases or (2) virtual bases
79 /// when the type is known to be complete (e.g. in complete destructors).
81 /// The object pointed to by 'This' is assumed to be non-null.
83 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
84 const CXXRecordDecl *Derived,
85 const CXXRecordDecl *Base,
87 // 'this' must be a pointer (in some address space) to Derived.
88 assert(This->getType()->isPointerTy() &&
89 cast<llvm::PointerType>(This->getType())->getElementType()
90 == ConvertType(Derived));
92 // Compute the offset of the virtual base.
94 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
96 Offset = Layout.getVBaseClassOffset(Base);
98 Offset = Layout.getBaseClassOffset(Base);
100 // Shift and cast down to the base type.
101 // TODO: for complete types, this should be possible with a GEP.
102 llvm::Value *V = This;
103 if (Offset.isPositive()) {
104 V = Builder.CreateBitCast(V, Int8PtrTy);
105 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
107 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
113 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
114 CharUnits nonVirtualOffset,
115 llvm::Value *virtualOffset) {
116 // Assert that we have something to do.
117 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
119 // Compute the offset from the static and dynamic components.
120 llvm::Value *baseOffset;
121 if (!nonVirtualOffset.isZero()) {
122 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
123 nonVirtualOffset.getQuantity());
125 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
128 baseOffset = virtualOffset;
131 // Apply the base offset.
132 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
133 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
137 llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
138 llvm::Value *Value, const CXXRecordDecl *Derived,
139 CastExpr::path_const_iterator PathBegin,
140 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
141 SourceLocation Loc) {
142 assert(PathBegin != PathEnd && "Base path should not be empty!");
144 CastExpr::path_const_iterator Start = PathBegin;
145 const CXXRecordDecl *VBase = nullptr;
147 // Sema has done some convenient canonicalization here: if the
148 // access path involved any virtual steps, the conversion path will
149 // *start* with a step down to the correct virtual base subobject,
150 // and hence will not require any further steps.
151 if ((*Start)->isVirtual()) {
153 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
157 // Compute the static offset of the ultimate destination within its
158 // allocating subobject (the virtual base, if there is one, or else
159 // the "complete" object that we see).
160 CharUnits NonVirtualOffset =
161 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
164 // If there's a virtual step, we can sometimes "devirtualize" it.
165 // For now, that's limited to when the derived type is final.
166 // TODO: "devirtualize" this for accesses to known-complete objects.
167 if (VBase && Derived->hasAttr<FinalAttr>()) {
168 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
169 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
170 NonVirtualOffset += vBaseOffset;
171 VBase = nullptr; // we no longer have a virtual step
174 // Get the base pointer type.
175 llvm::Type *BasePtrTy =
176 ConvertType((PathEnd[-1])->getType())->getPointerTo();
178 QualType DerivedTy = getContext().getRecordType(Derived);
179 CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
181 // If the static offset is zero and we don't have a virtual step,
182 // just do a bitcast; null checks are unnecessary.
183 if (NonVirtualOffset.isZero() && !VBase) {
184 if (sanitizePerformTypeCheck()) {
185 EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
188 return Builder.CreateBitCast(Value, BasePtrTy);
191 llvm::BasicBlock *origBB = nullptr;
192 llvm::BasicBlock *endBB = nullptr;
194 // Skip over the offset (and the vtable load) if we're supposed to
195 // null-check the pointer.
196 if (NullCheckValue) {
197 origBB = Builder.GetInsertBlock();
198 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
199 endBB = createBasicBlock("cast.end");
201 llvm::Value *isNull = Builder.CreateIsNull(Value);
202 Builder.CreateCondBr(isNull, endBB, notNullBB);
203 EmitBlock(notNullBB);
206 if (sanitizePerformTypeCheck()) {
207 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
208 DerivedTy, DerivedAlign, true);
211 // Compute the virtual offset.
212 llvm::Value *VirtualOffset = nullptr;
215 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
218 // Apply both offsets.
219 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
223 // Cast to the destination type.
224 Value = Builder.CreateBitCast(Value, BasePtrTy);
226 // Build a phi if we needed a null check.
227 if (NullCheckValue) {
228 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
229 Builder.CreateBr(endBB);
232 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
233 PHI->addIncoming(Value, notNullBB);
234 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
242 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
243 const CXXRecordDecl *Derived,
244 CastExpr::path_const_iterator PathBegin,
245 CastExpr::path_const_iterator PathEnd,
246 bool NullCheckValue) {
247 assert(PathBegin != PathEnd && "Base path should not be empty!");
250 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
251 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
253 llvm::Value *NonVirtualOffset =
254 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
256 if (!NonVirtualOffset) {
257 // No offset, we can just cast back.
258 return Builder.CreateBitCast(Value, DerivedPtrTy);
261 llvm::BasicBlock *CastNull = nullptr;
262 llvm::BasicBlock *CastNotNull = nullptr;
263 llvm::BasicBlock *CastEnd = nullptr;
265 if (NullCheckValue) {
266 CastNull = createBasicBlock("cast.null");
267 CastNotNull = createBasicBlock("cast.notnull");
268 CastEnd = createBasicBlock("cast.end");
270 llvm::Value *IsNull = Builder.CreateIsNull(Value);
271 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
272 EmitBlock(CastNotNull);
276 Value = Builder.CreateBitCast(Value, Int8PtrTy);
277 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
281 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
283 if (NullCheckValue) {
284 Builder.CreateBr(CastEnd);
286 Builder.CreateBr(CastEnd);
289 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
290 PHI->addIncoming(Value, CastNotNull);
291 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
299 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
302 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
303 // This constructor/destructor does not need a VTT parameter.
307 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
308 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
312 uint64_t SubVTTIndex;
315 // If this is a delegating constructor call, just load the VTT.
317 } else if (RD == Base) {
318 // If the record matches the base, this is the complete ctor/dtor
319 // variant calling the base variant in a class with virtual bases.
320 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
321 "doing no-op VTT offset in base dtor/ctor?");
322 assert(!ForVirtualBase && "Can't have same class as virtual base!");
325 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
326 CharUnits BaseOffset = ForVirtualBase ?
327 Layout.getVBaseClassOffset(Base) :
328 Layout.getBaseClassOffset(Base);
331 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
332 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
335 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
336 // A VTT parameter was passed to the constructor, use it.
338 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
340 // We're the complete constructor, so get the VTT by name.
341 VTT = CGM.getVTables().GetAddrOfVTT(RD);
342 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
349 /// Call the destructor for a direct base class.
350 struct CallBaseDtor : EHScopeStack::Cleanup {
351 const CXXRecordDecl *BaseClass;
353 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
354 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
356 void Emit(CodeGenFunction &CGF, Flags flags) override {
357 const CXXRecordDecl *DerivedClass =
358 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
360 const CXXDestructorDecl *D = BaseClass->getDestructor();
362 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
363 DerivedClass, BaseClass,
365 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
366 /*Delegating=*/false, Addr);
370 /// A visitor which checks whether an initializer uses 'this' in a
371 /// way which requires the vtable to be properly set.
372 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
373 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
377 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
379 // Black-list all explicit and implicit references to 'this'.
381 // Do we need to worry about external references to 'this' derived
382 // from arbitrary code? If so, then anything which runs arbitrary
383 // external code might potentially access the vtable.
384 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
388 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
389 DynamicThisUseChecker Checker(C);
390 Checker.Visit(const_cast<Expr*>(Init));
391 return Checker.UsesThis;
394 static void EmitBaseInitializer(CodeGenFunction &CGF,
395 const CXXRecordDecl *ClassDecl,
396 CXXCtorInitializer *BaseInit,
397 CXXCtorType CtorType) {
398 assert(BaseInit->isBaseInitializer() &&
399 "Must have base initializer!");
401 llvm::Value *ThisPtr = CGF.LoadCXXThis();
403 const Type *BaseType = BaseInit->getBaseClass();
404 CXXRecordDecl *BaseClassDecl =
405 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
407 bool isBaseVirtual = BaseInit->isBaseVirtual();
409 // The base constructor doesn't construct virtual bases.
410 if (CtorType == Ctor_Base && isBaseVirtual)
413 // If the initializer for the base (other than the constructor
414 // itself) accesses 'this' in any way, we need to initialize the
416 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
417 CGF.InitializeVTablePointers(ClassDecl);
419 // We can pretend to be a complete class because it only matters for
420 // virtual bases, and we only do virtual bases for complete ctors.
422 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
425 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
426 AggValueSlot AggSlot =
427 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
428 AggValueSlot::IsDestructed,
429 AggValueSlot::DoesNotNeedGCBarriers,
430 AggValueSlot::IsNotAliased);
432 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
434 if (CGF.CGM.getLangOpts().Exceptions &&
435 !BaseClassDecl->hasTrivialDestructor())
436 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
440 static void EmitAggMemberInitializer(CodeGenFunction &CGF,
443 llvm::Value *ArrayIndexVar,
445 ArrayRef<VarDecl *> ArrayIndexes,
447 if (Index == ArrayIndexes.size()) {
451 // If we have an array index variable, load it and use it as an offset.
452 // Then, increment the value.
453 llvm::Value *Dest = LHS.getAddress();
454 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
455 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
456 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
457 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
458 CGF.Builder.CreateStore(Next, ArrayIndexVar);
460 // Update the LValue.
462 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
463 LV.setAlignment(std::min(Align, LV.getAlignment()));
466 switch (CGF.getEvaluationKind(T)) {
468 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
471 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
473 case TEK_Aggregate: {
475 AggValueSlot::forLValue(LV,
476 AggValueSlot::IsDestructed,
477 AggValueSlot::DoesNotNeedGCBarriers,
478 AggValueSlot::IsNotAliased);
480 CGF.EmitAggExpr(Init, Slot);
488 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
489 assert(Array && "Array initialization without the array type?");
490 llvm::Value *IndexVar
491 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
492 assert(IndexVar && "Array index variable not loaded");
494 // Initialize this index variable to zero.
496 = llvm::Constant::getNullValue(
497 CGF.ConvertType(CGF.getContext().getSizeType()));
498 CGF.Builder.CreateStore(Zero, IndexVar);
500 // Start the loop with a block that tests the condition.
501 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
502 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
504 CGF.EmitBlock(CondBlock);
506 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
507 // Generate: if (loop-index < number-of-elements) fall to the loop body,
508 // otherwise, go to the block after the for-loop.
509 uint64_t NumElements = Array->getSize().getZExtValue();
510 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
511 llvm::Value *NumElementsPtr =
512 llvm::ConstantInt::get(Counter->getType(), NumElements);
513 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
516 // If the condition is true, execute the body.
517 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
519 CGF.EmitBlock(ForBody);
520 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
522 // Inside the loop body recurse to emit the inner loop or, eventually, the
524 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
525 Array->getElementType(), ArrayIndexes, Index + 1);
527 CGF.EmitBlock(ContinueBlock);
529 // Emit the increment of the loop counter.
530 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
531 Counter = CGF.Builder.CreateLoad(IndexVar);
532 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
533 CGF.Builder.CreateStore(NextVal, IndexVar);
535 // Finally, branch back up to the condition for the next iteration.
536 CGF.EmitBranch(CondBlock);
538 // Emit the fall-through block.
539 CGF.EmitBlock(AfterFor, true);
542 static void EmitMemberInitializer(CodeGenFunction &CGF,
543 const CXXRecordDecl *ClassDecl,
544 CXXCtorInitializer *MemberInit,
545 const CXXConstructorDecl *Constructor,
546 FunctionArgList &Args) {
547 ApplyDebugLocation Loc(CGF, MemberInit->getMemberLocation());
548 assert(MemberInit->isAnyMemberInitializer() &&
549 "Must have member initializer!");
550 assert(MemberInit->getInit() && "Must have initializer!");
552 // non-static data member initializers.
553 FieldDecl *Field = MemberInit->getAnyMember();
554 QualType FieldType = Field->getType();
556 llvm::Value *ThisPtr = CGF.LoadCXXThis();
557 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
558 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
560 if (MemberInit->isIndirectMemberInitializer()) {
561 // If we are initializing an anonymous union field, drill down to
563 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
564 for (const auto *I : IndirectField->chain())
565 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
566 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
568 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
571 // Special case: if we are in a copy or move constructor, and we are copying
572 // an array of PODs or classes with trivial copy constructors, ignore the
573 // AST and perform the copy we know is equivalent.
574 // FIXME: This is hacky at best... if we had a bit more explicit information
575 // in the AST, we could generalize it more easily.
576 const ConstantArrayType *Array
577 = CGF.getContext().getAsConstantArrayType(FieldType);
578 if (Array && Constructor->isDefaulted() &&
579 Constructor->isCopyOrMoveConstructor()) {
580 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
581 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
582 if (BaseElementTy.isPODType(CGF.getContext()) ||
583 (CE && CE->getConstructor()->isTrivial())) {
584 unsigned SrcArgIndex =
585 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
587 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
588 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
589 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
591 // Copy the aggregate.
592 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
593 LHS.isVolatileQualified());
598 ArrayRef<VarDecl *> ArrayIndexes;
599 if (MemberInit->getNumArrayIndices())
600 ArrayIndexes = MemberInit->getArrayIndexes();
601 ApplyDebugLocation DL(CGF, MemberInit->getMemberLocation());
602 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
605 void CodeGenFunction::EmitInitializerForField(
606 FieldDecl *Field, LValue LHS, Expr *Init,
607 ArrayRef<VarDecl *> ArrayIndexes) {
608 QualType FieldType = Field->getType();
609 switch (getEvaluationKind(FieldType)) {
611 if (LHS.isSimple()) {
612 EmitExprAsInit(Init, Field, LHS, false);
614 RValue RHS = RValue::get(EmitScalarExpr(Init));
615 EmitStoreThroughLValue(RHS, LHS);
619 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
621 case TEK_Aggregate: {
622 llvm::Value *ArrayIndexVar = nullptr;
623 if (ArrayIndexes.size()) {
624 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
626 // The LHS is a pointer to the first object we'll be constructing, as
628 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
629 llvm::Type *BasePtr = ConvertType(BaseElementTy);
630 BasePtr = llvm::PointerType::getUnqual(BasePtr);
631 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
633 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
635 // Create an array index that will be used to walk over all of the
636 // objects we're constructing.
637 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
638 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
639 Builder.CreateStore(Zero, ArrayIndexVar);
642 // Emit the block variables for the array indices, if any.
643 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
644 EmitAutoVarDecl(*ArrayIndexes[I]);
647 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
652 // Ensure that we destroy this object if an exception is thrown
653 // later in the constructor.
654 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
655 if (needsEHCleanup(dtorKind))
656 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
659 /// Checks whether the given constructor is a valid subject for the
660 /// complete-to-base constructor delegation optimization, i.e.
661 /// emitting the complete constructor as a simple call to the base
663 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
665 // Currently we disable the optimization for classes with virtual
666 // bases because (1) the addresses of parameter variables need to be
667 // consistent across all initializers but (2) the delegate function
668 // call necessarily creates a second copy of the parameter variable.
670 // The limiting example (purely theoretical AFAIK):
671 // struct A { A(int &c) { c++; } };
672 // struct B : virtual A {
673 // B(int count) : A(count) { printf("%d\n", count); }
675 // ...although even this example could in principle be emitted as a
676 // delegation since the address of the parameter doesn't escape.
677 if (Ctor->getParent()->getNumVBases()) {
678 // TODO: white-list trivial vbase initializers. This case wouldn't
679 // be subject to the restrictions below.
681 // TODO: white-list cases where:
682 // - there are no non-reference parameters to the constructor
683 // - the initializers don't access any non-reference parameters
684 // - the initializers don't take the address of non-reference
687 // If we ever add any of the above cases, remember that:
688 // - function-try-blocks will always blacklist this optimization
689 // - we need to perform the constructor prologue and cleanup in
690 // EmitConstructorBody.
695 // We also disable the optimization for variadic functions because
696 // it's impossible to "re-pass" varargs.
697 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
700 // FIXME: Decide if we can do a delegation of a delegating constructor.
701 if (Ctor->isDelegatingConstructor())
707 // Emit code in ctor (Prologue==true) or dtor (Prologue==false)
708 // to poison the extra field paddings inserted under
709 // -fsanitize-address-field-padding=1|2.
710 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
711 ASTContext &Context = getContext();
712 const CXXRecordDecl *ClassDecl =
713 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
714 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
715 if (!ClassDecl->mayInsertExtraPadding()) return;
717 struct SizeAndOffset {
722 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
723 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
725 // Populate sizes and offsets of fields.
726 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
727 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
729 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
731 size_t NumFields = 0;
732 for (const auto *Field : ClassDecl->fields()) {
733 const FieldDecl *D = Field;
734 std::pair<CharUnits, CharUnits> FieldInfo =
735 Context.getTypeInfoInChars(D->getType());
736 CharUnits FieldSize = FieldInfo.first;
737 assert(NumFields < SSV.size());
738 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
741 assert(NumFields == SSV.size());
742 if (SSV.size() <= 1) return;
744 // We will insert calls to __asan_* run-time functions.
745 // LLVM AddressSanitizer pass may decide to inline them later.
746 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
747 llvm::FunctionType *FTy =
748 llvm::FunctionType::get(CGM.VoidTy, Args, false);
749 llvm::Constant *F = CGM.CreateRuntimeFunction(
750 FTy, Prologue ? "__asan_poison_intra_object_redzone"
751 : "__asan_unpoison_intra_object_redzone");
753 llvm::Value *ThisPtr = LoadCXXThis();
754 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
755 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
756 // For each field check if it has sufficient padding,
757 // if so (un)poison it with a call.
758 for (size_t i = 0; i < SSV.size(); i++) {
759 uint64_t AsanAlignment = 8;
760 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
761 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
762 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
763 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
764 (NextField % AsanAlignment) != 0)
767 F, Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
768 Builder.getIntN(PtrSize, PoisonSize));
772 /// EmitConstructorBody - Emits the body of the current constructor.
773 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
774 EmitAsanPrologueOrEpilogue(true);
775 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
776 CXXCtorType CtorType = CurGD.getCtorType();
778 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
779 CtorType == Ctor_Complete) &&
780 "can only generate complete ctor for this ABI");
782 // Before we go any further, try the complete->base constructor
783 // delegation optimization.
784 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
785 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
786 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
790 const FunctionDecl *Definition = 0;
791 Stmt *Body = Ctor->getBody(Definition);
792 assert(Definition == Ctor && "emitting wrong constructor body");
794 // Enter the function-try-block before the constructor prologue if
796 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
798 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
800 RegionCounter Cnt = getPGORegionCounter(Body);
801 Cnt.beginRegion(Builder);
803 RunCleanupsScope RunCleanups(*this);
805 // TODO: in restricted cases, we can emit the vbase initializers of
806 // a complete ctor and then delegate to the base ctor.
808 // Emit the constructor prologue, i.e. the base and member
810 EmitCtorPrologue(Ctor, CtorType, Args);
812 // Emit the body of the statement.
814 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
818 // Emit any cleanup blocks associated with the member or base
819 // initializers, which includes (along the exceptional path) the
820 // destructors for those members and bases that were fully
822 RunCleanups.ForceCleanup();
825 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
829 /// RAII object to indicate that codegen is copying the value representation
830 /// instead of the object representation. Useful when copying a struct or
831 /// class which has uninitialized members and we're only performing
832 /// lvalue-to-rvalue conversion on the object but not its members.
833 class CopyingValueRepresentation {
835 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
836 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
837 CGF.SanOpts.set(SanitizerKind::Bool, false);
838 CGF.SanOpts.set(SanitizerKind::Enum, false);
840 ~CopyingValueRepresentation() {
841 CGF.SanOpts = OldSanOpts;
844 CodeGenFunction &CGF;
845 SanitizerSet OldSanOpts;
850 class FieldMemcpyizer {
852 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
853 const VarDecl *SrcRec)
854 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
855 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
856 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
857 LastFieldOffset(0), LastAddedFieldIndex(0) {}
859 bool isMemcpyableField(FieldDecl *F) const {
860 // Never memcpy fields when we are adding poisoned paddings.
861 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
863 Qualifiers Qual = F->getType().getQualifiers();
864 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
869 void addMemcpyableField(FieldDecl *F) {
876 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
877 unsigned LastFieldSize =
878 LastField->isBitField() ?
879 LastField->getBitWidthValue(CGF.getContext()) :
880 CGF.getContext().getTypeSize(LastField->getType());
881 uint64_t MemcpySizeBits =
882 LastFieldOffset + LastFieldSize - FirstByteOffset +
883 CGF.getContext().getCharWidth() - 1;
884 CharUnits MemcpySize =
885 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
890 // Give the subclass a chance to bail out if it feels the memcpy isn't
891 // worth it (e.g. Hasn't aggregated enough data).
898 uint64_t FirstByteOffset;
899 if (FirstField->isBitField()) {
900 const CGRecordLayout &RL =
901 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
902 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
903 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
904 // FirstFieldOffset is not appropriate for bitfields,
905 // it won't tell us what the storage offset should be and thus might not
906 // be properly aligned.
908 // Instead calculate the storage offset using the offset of the field in
910 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
912 DL.getStructLayout(RL.getLLVMType())
913 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
915 Alignment = CGF.getContext().getDeclAlign(FirstField);
916 FirstByteOffset = FirstFieldOffset;
919 assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
920 Alignment) == 0 && "Bad field alignment.");
922 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
923 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
924 llvm::Value *ThisPtr = CGF.LoadCXXThis();
925 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
926 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
927 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
928 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
929 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
931 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
932 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
933 MemcpySize, Alignment);
938 FirstField = nullptr;
942 CodeGenFunction &CGF;
943 const CXXRecordDecl *ClassDecl;
947 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
948 CharUnits Size, CharUnits Alignment) {
949 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
951 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
952 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
954 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
956 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
957 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
959 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
960 Alignment.getQuantity());
963 void addInitialField(FieldDecl *F) {
966 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
967 LastFieldOffset = FirstFieldOffset;
968 LastAddedFieldIndex = F->getFieldIndex();
972 void addNextField(FieldDecl *F) {
973 // For the most part, the following invariant will hold:
974 // F->getFieldIndex() == LastAddedFieldIndex + 1
975 // The one exception is that Sema won't add a copy-initializer for an
976 // unnamed bitfield, which will show up here as a gap in the sequence.
977 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
978 "Cannot aggregate fields out of order.");
979 LastAddedFieldIndex = F->getFieldIndex();
981 // The 'first' and 'last' fields are chosen by offset, rather than field
982 // index. This allows the code to support bitfields, as well as regular
984 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
985 if (FOffset < FirstFieldOffset) {
987 FirstFieldOffset = FOffset;
988 } else if (FOffset > LastFieldOffset) {
990 LastFieldOffset = FOffset;
994 const VarDecl *SrcRec;
995 const ASTRecordLayout &RecLayout;
996 FieldDecl *FirstField;
997 FieldDecl *LastField;
998 uint64_t FirstFieldOffset, LastFieldOffset;
999 unsigned LastAddedFieldIndex;
1002 class ConstructorMemcpyizer : public FieldMemcpyizer {
1005 /// Get source argument for copy constructor. Returns null if not a copy
1007 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1008 const CXXConstructorDecl *CD,
1009 FunctionArgList &Args) {
1010 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
1011 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
1015 // Returns true if a CXXCtorInitializer represents a member initialization
1016 // that can be rolled into a memcpy.
1017 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1018 if (!MemcpyableCtor)
1020 FieldDecl *Field = MemberInit->getMember();
1021 assert(Field && "No field for member init.");
1022 QualType FieldType = Field->getType();
1023 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1025 // Bail out on non-POD, not-trivially-constructable members.
1026 if (!(CE && CE->getConstructor()->isTrivial()) &&
1027 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1028 FieldType->isReferenceType()))
1031 // Bail out on volatile fields.
1032 if (!isMemcpyableField(Field))
1035 // Otherwise we're good.
1040 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1041 FunctionArgList &Args)
1042 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
1043 ConstructorDecl(CD),
1044 MemcpyableCtor(CD->isDefaulted() &&
1045 CD->isCopyOrMoveConstructor() &&
1046 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1049 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1050 if (isMemberInitMemcpyable(MemberInit)) {
1051 AggregatedInits.push_back(MemberInit);
1052 addMemcpyableField(MemberInit->getMember());
1054 emitAggregatedInits();
1055 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1056 ConstructorDecl, Args);
1060 void emitAggregatedInits() {
1061 if (AggregatedInits.size() <= 1) {
1062 // This memcpy is too small to be worthwhile. Fall back on default
1064 if (!AggregatedInits.empty()) {
1065 CopyingValueRepresentation CVR(CGF);
1066 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
1067 AggregatedInits[0], ConstructorDecl, Args);
1073 pushEHDestructors();
1075 AggregatedInits.clear();
1078 void pushEHDestructors() {
1079 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1080 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1081 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1083 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1084 QualType FieldType = AggregatedInits[i]->getMember()->getType();
1085 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1086 if (CGF.needsEHCleanup(dtorKind))
1087 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1092 emitAggregatedInits();
1096 const CXXConstructorDecl *ConstructorDecl;
1097 bool MemcpyableCtor;
1098 FunctionArgList &Args;
1099 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1102 class AssignmentMemcpyizer : public FieldMemcpyizer {
1105 // Returns the memcpyable field copied by the given statement, if one
1106 // exists. Otherwise returns null.
1107 FieldDecl *getMemcpyableField(Stmt *S) {
1108 if (!AssignmentsMemcpyable)
1110 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1111 // Recognise trivial assignments.
1112 if (BO->getOpcode() != BO_Assign)
1114 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1117 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1118 if (!Field || !isMemcpyableField(Field))
1120 Stmt *RHS = BO->getRHS();
1121 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1122 RHS = EC->getSubExpr();
1125 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1126 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1129 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1130 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1131 if (!(MD && (MD->isCopyAssignmentOperator() ||
1132 MD->isMoveAssignmentOperator()) &&
1135 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1138 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1139 if (!Field || !isMemcpyableField(Field))
1141 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1142 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1145 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1146 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1147 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1149 Expr *DstPtr = CE->getArg(0);
1150 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1151 DstPtr = DC->getSubExpr();
1152 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1153 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1155 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1158 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1159 if (!Field || !isMemcpyableField(Field))
1161 Expr *SrcPtr = CE->getArg(1);
1162 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1163 SrcPtr = SC->getSubExpr();
1164 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1165 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1167 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1168 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1176 bool AssignmentsMemcpyable;
1177 SmallVector<Stmt*, 16> AggregatedStmts;
1181 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1182 FunctionArgList &Args)
1183 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1184 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1185 assert(Args.size() == 2);
1188 void emitAssignment(Stmt *S) {
1189 FieldDecl *F = getMemcpyableField(S);
1191 addMemcpyableField(F);
1192 AggregatedStmts.push_back(S);
1194 emitAggregatedStmts();
1199 void emitAggregatedStmts() {
1200 if (AggregatedStmts.size() <= 1) {
1201 if (!AggregatedStmts.empty()) {
1202 CopyingValueRepresentation CVR(CGF);
1203 CGF.EmitStmt(AggregatedStmts[0]);
1209 AggregatedStmts.clear();
1213 emitAggregatedStmts();
1219 /// EmitCtorPrologue - This routine generates necessary code to initialize
1220 /// base classes and non-static data members belonging to this constructor.
1221 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
1222 CXXCtorType CtorType,
1223 FunctionArgList &Args) {
1224 if (CD->isDelegatingConstructor())
1225 return EmitDelegatingCXXConstructorCall(CD, Args);
1227 const CXXRecordDecl *ClassDecl = CD->getParent();
1229 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1232 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
1233 if (ClassDecl->getNumVBases() &&
1234 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1235 // The ABIs that don't have constructor variants need to put a branch
1236 // before the virtual base initialization code.
1237 BaseCtorContinueBB =
1238 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
1239 assert(BaseCtorContinueBB);
1242 // Virtual base initializers first.
1243 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1244 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1247 if (BaseCtorContinueBB) {
1248 // Complete object handler should continue to the remaining initializers.
1249 Builder.CreateBr(BaseCtorContinueBB);
1250 EmitBlock(BaseCtorContinueBB);
1253 // Then, non-virtual base initializers.
1254 for (; B != E && (*B)->isBaseInitializer(); B++) {
1255 assert(!(*B)->isBaseVirtual());
1256 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1259 InitializeVTablePointers(ClassDecl);
1261 // And finally, initialize class members.
1262 FieldConstructionScope FCS(*this, CXXThisValue);
1263 ConstructorMemcpyizer CM(*this, CD, Args);
1264 for (; B != E; B++) {
1265 CXXCtorInitializer *Member = (*B);
1266 assert(!Member->isBaseInitializer());
1267 assert(Member->isAnyMemberInitializer() &&
1268 "Delegating initializer on non-delegating constructor");
1269 CM.addMemberInitializer(Member);
1275 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1278 HasTrivialDestructorBody(ASTContext &Context,
1279 const CXXRecordDecl *BaseClassDecl,
1280 const CXXRecordDecl *MostDerivedClassDecl)
1282 // If the destructor is trivial we don't have to check anything else.
1283 if (BaseClassDecl->hasTrivialDestructor())
1286 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1290 for (const auto *Field : BaseClassDecl->fields())
1291 if (!FieldHasTrivialDestructorBody(Context, Field))
1294 // Check non-virtual bases.
1295 for (const auto &I : BaseClassDecl->bases()) {
1299 const CXXRecordDecl *NonVirtualBase =
1300 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1301 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1302 MostDerivedClassDecl))
1306 if (BaseClassDecl == MostDerivedClassDecl) {
1307 // Check virtual bases.
1308 for (const auto &I : BaseClassDecl->vbases()) {
1309 const CXXRecordDecl *VirtualBase =
1310 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
1311 if (!HasTrivialDestructorBody(Context, VirtualBase,
1312 MostDerivedClassDecl))
1321 FieldHasTrivialDestructorBody(ASTContext &Context,
1322 const FieldDecl *Field)
1324 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1326 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1330 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1331 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1334 /// CanSkipVTablePointerInitialization - Check whether we need to initialize
1335 /// any vtable pointers before calling this destructor.
1336 static bool CanSkipVTablePointerInitialization(ASTContext &Context,
1337 const CXXDestructorDecl *Dtor) {
1338 if (!Dtor->hasTrivialBody())
1341 // Check the fields.
1342 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1343 for (const auto *Field : ClassDecl->fields())
1344 if (!FieldHasTrivialDestructorBody(Context, Field))
1350 /// EmitDestructorBody - Emits the body of the current destructor.
1351 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1352 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1353 CXXDtorType DtorType = CurGD.getDtorType();
1355 // The call to operator delete in a deleting destructor happens
1356 // outside of the function-try-block, which means it's always
1357 // possible to delegate the destructor body to the complete
1358 // destructor. Do so.
1359 if (DtorType == Dtor_Deleting) {
1360 EnterDtorCleanups(Dtor, Dtor_Deleting);
1361 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
1362 /*Delegating=*/false, LoadCXXThis());
1367 Stmt *Body = Dtor->getBody();
1369 // If the body is a function-try-block, enter the try before
1371 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
1373 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1374 EmitAsanPrologueOrEpilogue(false);
1376 // Enter the epilogue cleanups.
1377 RunCleanupsScope DtorEpilogue(*this);
1379 // If this is the complete variant, just invoke the base variant;
1380 // the epilogue will destruct the virtual bases. But we can't do
1381 // this optimization if the body is a function-try-block, because
1382 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1383 // always delegate because we might not have a definition in this TU.
1386 llvm_unreachable("not expecting a COMDAT");
1388 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1391 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1392 "can't emit a dtor without a body for non-Microsoft ABIs");
1394 // Enter the cleanup scopes for virtual bases.
1395 EnterDtorCleanups(Dtor, Dtor_Complete);
1398 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
1399 /*Delegating=*/false, LoadCXXThis());
1402 // Fallthrough: act like we're in the base variant.
1407 RegionCounter Cnt = getPGORegionCounter(Body);
1408 Cnt.beginRegion(Builder);
1410 // Enter the cleanup scopes for fields and non-virtual bases.
1411 EnterDtorCleanups(Dtor, Dtor_Base);
1413 // Initialize the vtable pointers before entering the body.
1414 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1415 InitializeVTablePointers(Dtor->getParent());
1418 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1422 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1423 // nothing to do besides what's in the epilogue
1425 // -fapple-kext must inline any call to this dtor into
1426 // the caller's body.
1427 if (getLangOpts().AppleKext)
1428 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
1432 // Jump out through the epilogue cleanups.
1433 DtorEpilogue.ForceCleanup();
1435 // Exit the try if applicable.
1437 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
1440 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1441 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1442 const Stmt *RootS = AssignOp->getBody();
1443 assert(isa<CompoundStmt>(RootS) &&
1444 "Body of an implicit assignment operator should be compound stmt.");
1445 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1447 LexicalScope Scope(*this, RootCS->getSourceRange());
1449 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1450 for (auto *I : RootCS->body())
1451 AM.emitAssignment(I);
1456 /// Call the operator delete associated with the current destructor.
1457 struct CallDtorDelete : EHScopeStack::Cleanup {
1460 void Emit(CodeGenFunction &CGF, Flags flags) override {
1461 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1462 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1463 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1464 CGF.getContext().getTagDeclType(ClassDecl));
1468 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1469 llvm::Value *ShouldDeleteCondition;
1471 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1472 : ShouldDeleteCondition(ShouldDeleteCondition) {
1473 assert(ShouldDeleteCondition != nullptr);
1476 void Emit(CodeGenFunction &CGF, Flags flags) override {
1477 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1478 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1479 llvm::Value *ShouldCallDelete
1480 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1481 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1483 CGF.EmitBlock(callDeleteBB);
1484 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1485 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1486 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1487 CGF.getContext().getTagDeclType(ClassDecl));
1488 CGF.Builder.CreateBr(continueBB);
1490 CGF.EmitBlock(continueBB);
1494 class DestroyField : public EHScopeStack::Cleanup {
1495 const FieldDecl *field;
1496 CodeGenFunction::Destroyer *destroyer;
1497 bool useEHCleanupForArray;
1500 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1501 bool useEHCleanupForArray)
1502 : field(field), destroyer(destroyer),
1503 useEHCleanupForArray(useEHCleanupForArray) {}
1505 void Emit(CodeGenFunction &CGF, Flags flags) override {
1506 // Find the address of the field.
1507 llvm::Value *thisValue = CGF.LoadCXXThis();
1508 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1509 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1510 LValue LV = CGF.EmitLValueForField(ThisLV, field);
1511 assert(LV.isSimple());
1513 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
1514 flags.isForNormalCleanup() && useEHCleanupForArray);
1519 /// \brief Emit all code that comes at the end of class's
1520 /// destructor. This is to call destructors on members and base classes
1521 /// in reverse order of their construction.
1522 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1523 CXXDtorType DtorType) {
1524 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1525 "Should not emit dtor epilogue for non-exported trivial dtor!");
1527 // The deleting-destructor phase just needs to call the appropriate
1528 // operator delete that Sema picked up.
1529 if (DtorType == Dtor_Deleting) {
1530 assert(DD->getOperatorDelete() &&
1531 "operator delete missing - EnterDtorCleanups");
1532 if (CXXStructorImplicitParamValue) {
1533 // If there is an implicit param to the deleting dtor, it's a boolean
1534 // telling whether we should call delete at the end of the dtor.
1535 EHStack.pushCleanup<CallDtorDeleteConditional>(
1536 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1538 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1543 const CXXRecordDecl *ClassDecl = DD->getParent();
1545 // Unions have no bases and do not call field destructors.
1546 if (ClassDecl->isUnion())
1549 // The complete-destructor phase just destructs all the virtual bases.
1550 if (DtorType == Dtor_Complete) {
1552 // We push them in the forward order so that they'll be popped in
1553 // the reverse order.
1554 for (const auto &Base : ClassDecl->vbases()) {
1555 CXXRecordDecl *BaseClassDecl
1556 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1558 // Ignore trivial destructors.
1559 if (BaseClassDecl->hasTrivialDestructor())
1562 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1564 /*BaseIsVirtual*/ true);
1570 assert(DtorType == Dtor_Base);
1572 // Destroy non-virtual bases.
1573 for (const auto &Base : ClassDecl->bases()) {
1574 // Ignore virtual bases.
1575 if (Base.isVirtual())
1578 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1580 // Ignore trivial destructors.
1581 if (BaseClassDecl->hasTrivialDestructor())
1584 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1586 /*BaseIsVirtual*/ false);
1589 // Destroy direct fields.
1590 for (const auto *Field : ClassDecl->fields()) {
1591 QualType type = Field->getType();
1592 QualType::DestructionKind dtorKind = type.isDestructedType();
1593 if (!dtorKind) continue;
1595 // Anonymous union members do not have their destructors called.
1596 const RecordType *RT = type->getAsUnionType();
1597 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1599 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1600 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
1601 getDestroyer(dtorKind),
1602 cleanupKind & EHCleanup);
1606 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1607 /// constructor for each of several members of an array.
1609 /// \param ctor the constructor to call for each element
1610 /// \param arrayType the type of the array to initialize
1611 /// \param arrayBegin an arrayType*
1612 /// \param zeroInitialize true if each element should be
1613 /// zero-initialized before it is constructed
1614 void CodeGenFunction::EmitCXXAggrConstructorCall(
1615 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1616 llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
1617 QualType elementType;
1618 llvm::Value *numElements =
1619 emitArrayLength(arrayType, elementType, arrayBegin);
1621 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
1624 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1625 /// constructor for each of several members of an array.
1627 /// \param ctor the constructor to call for each element
1628 /// \param numElements the number of elements in the array;
1630 /// \param arrayBegin a T*, where T is the type constructed by ctor
1631 /// \param zeroInitialize true if each element should be
1632 /// zero-initialized before it is constructed
1633 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1634 llvm::Value *numElements,
1635 llvm::Value *arrayBegin,
1636 const CXXConstructExpr *E,
1637 bool zeroInitialize) {
1639 // It's legal for numElements to be zero. This can happen both
1640 // dynamically, because x can be zero in 'new A[x]', and statically,
1641 // because of GCC extensions that permit zero-length arrays. There
1642 // are probably legitimate places where we could assume that this
1643 // doesn't happen, but it's not clear that it's worth it.
1644 llvm::BranchInst *zeroCheckBranch = nullptr;
1646 // Optimize for a constant count.
1647 llvm::ConstantInt *constantCount
1648 = dyn_cast<llvm::ConstantInt>(numElements);
1649 if (constantCount) {
1650 // Just skip out if the constant count is zero.
1651 if (constantCount->isZero()) return;
1653 // Otherwise, emit the check.
1655 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1656 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1657 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1661 // Find the end of the array.
1662 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1665 // Enter the loop, setting up a phi for the current location to initialize.
1666 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1667 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1669 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1671 cur->addIncoming(arrayBegin, entryBB);
1673 // Inside the loop body, emit the constructor call on the array element.
1675 QualType type = getContext().getTypeDeclType(ctor->getParent());
1677 // Zero initialize the storage, if requested.
1679 EmitNullInitialization(cur, type);
1681 // C++ [class.temporary]p4:
1682 // There are two contexts in which temporaries are destroyed at a different
1683 // point than the end of the full-expression. The first context is when a
1684 // default constructor is called to initialize an element of an array.
1685 // If the constructor has one or more default arguments, the destruction of
1686 // every temporary created in a default argument expression is sequenced
1687 // before the construction of the next array element, if any.
1690 RunCleanupsScope Scope(*this);
1692 // Evaluate the constructor and its arguments in a regular
1693 // partial-destroy cleanup.
1694 if (getLangOpts().Exceptions &&
1695 !ctor->getParent()->hasTrivialDestructor()) {
1696 Destroyer *destroyer = destroyCXXObject;
1697 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1700 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1701 /*Delegating=*/false, cur, E);
1704 // Go to the next element.
1706 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1708 cur->addIncoming(next, Builder.GetInsertBlock());
1710 // Check whether that's the end of the loop.
1711 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1712 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1713 Builder.CreateCondBr(done, contBB, loopBB);
1715 // Patch the earlier check to skip over the loop.
1716 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1721 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1724 const RecordType *rtype = type->castAs<RecordType>();
1725 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1726 const CXXDestructorDecl *dtor = record->getDestructor();
1727 assert(!dtor->isTrivial());
1728 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1729 /*Delegating=*/false, addr);
1732 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1734 bool ForVirtualBase,
1735 bool Delegating, llvm::Value *This,
1736 const CXXConstructExpr *E) {
1737 // If this is a trivial constructor, just emit what's needed.
1738 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding()) {
1739 if (E->getNumArgs() == 0) {
1740 // Trivial default constructor, no codegen required.
1741 assert(D->isDefaultConstructor() &&
1742 "trivial 0-arg ctor not a default ctor");
1746 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1747 assert(D->isCopyOrMoveConstructor() &&
1748 "trivial 1-arg ctor not a copy/move ctor");
1750 const Expr *Arg = E->getArg(0);
1751 QualType Ty = Arg->getType();
1752 llvm::Value *Src = EmitLValue(Arg).getAddress();
1753 EmitAggregateCopy(This, Src, Ty);
1757 // C++11 [class.mfct.non-static]p2:
1758 // If a non-static member function of a class X is called for an object that
1759 // is not of type X, or of a type derived from X, the behavior is undefined.
1760 // FIXME: Provide a source location here.
1761 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1762 getContext().getRecordType(D->getParent()));
1766 // Push the this ptr.
1767 Args.add(RValue::get(This), D->getThisType(getContext()));
1769 // Add the rest of the user-supplied arguments.
1770 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1771 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
1773 // Insert any ABI-specific implicit constructor arguments.
1774 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1775 *this, D, Type, ForVirtualBase, Delegating, Args);
1778 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
1779 const CGFunctionInfo &Info =
1780 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
1781 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
1785 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1786 llvm::Value *This, llvm::Value *Src,
1787 const CXXConstructExpr *E) {
1788 if (D->isTrivial() &&
1789 !D->getParent()->mayInsertExtraPadding()) {
1790 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
1791 assert(D->isCopyOrMoveConstructor() &&
1792 "trivial 1-arg ctor not a copy/move ctor");
1793 EmitAggregateCopy(This, Src, E->arg_begin()->getType());
1796 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
1797 assert(D->isInstance() &&
1798 "Trying to emit a member call expr on a static method!");
1800 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
1804 // Push the this ptr.
1805 Args.add(RValue::get(This), D->getThisType(getContext()));
1807 // Push the src ptr.
1808 QualType QT = *(FPT->param_type_begin());
1809 llvm::Type *t = CGM.getTypes().ConvertType(QT);
1810 Src = Builder.CreateBitCast(Src, t);
1811 Args.add(RValue::get(Src), QT);
1813 // Skip over first argument (Src).
1814 EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1815 /*ParamsToSkip*/ 1);
1817 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1818 Callee, ReturnValueSlot(), Args, D);
1822 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1823 CXXCtorType CtorType,
1824 const FunctionArgList &Args,
1825 SourceLocation Loc) {
1826 CallArgList DelegateArgs;
1828 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1829 assert(I != E && "no parameters to constructor");
1832 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
1836 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
1837 /*ForVirtualBase=*/false,
1838 /*Delegating=*/true)) {
1839 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1840 DelegateArgs.add(RValue::get(VTT), VoidPP);
1842 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
1843 assert(I != E && "cannot skip vtt parameter, already done with args");
1844 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
1849 // Explicit arguments.
1850 for (; I != E; ++I) {
1851 const VarDecl *param = *I;
1852 // FIXME: per-argument source location
1853 EmitDelegateCallArg(DelegateArgs, param, Loc);
1856 llvm::Value *Callee =
1857 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
1858 EmitCall(CGM.getTypes()
1859 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
1860 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1864 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1865 const CXXDestructorDecl *Dtor;
1869 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1871 : Dtor(D), Addr(Addr), Type(Type) {}
1873 void Emit(CodeGenFunction &CGF, Flags flags) override {
1874 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1875 /*Delegating=*/true, Addr);
1881 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1882 const FunctionArgList &Args) {
1883 assert(Ctor->isDelegatingConstructor());
1885 llvm::Value *ThisPtr = LoadCXXThis();
1887 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
1888 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
1889 AggValueSlot AggSlot =
1890 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
1891 AggValueSlot::IsDestructed,
1892 AggValueSlot::DoesNotNeedGCBarriers,
1893 AggValueSlot::IsNotAliased);
1895 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1897 const CXXRecordDecl *ClassDecl = Ctor->getParent();
1898 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1900 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1902 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1903 ClassDecl->getDestructor(),
1908 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1910 bool ForVirtualBase,
1912 llvm::Value *This) {
1913 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1918 struct CallLocalDtor : EHScopeStack::Cleanup {
1919 const CXXDestructorDecl *Dtor;
1922 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1923 : Dtor(D), Addr(Addr) {}
1925 void Emit(CodeGenFunction &CGF, Flags flags) override {
1926 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1927 /*ForVirtualBase=*/false,
1928 /*Delegating=*/false, Addr);
1933 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1934 llvm::Value *Addr) {
1935 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
1938 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1939 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1940 if (!ClassDecl) return;
1941 if (ClassDecl->hasTrivialDestructor()) return;
1943 const CXXDestructorDecl *D = ClassDecl->getDestructor();
1944 assert(D && D->isUsed() && "destructor not marked as used!");
1945 PushDestructorCleanup(D, Addr);
1949 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
1950 const CXXRecordDecl *NearestVBase,
1951 CharUnits OffsetFromNearestVBase,
1952 const CXXRecordDecl *VTableClass) {
1953 // Compute the address point.
1954 bool NeedsVirtualOffset;
1955 llvm::Value *VTableAddressPoint =
1956 CGM.getCXXABI().getVTableAddressPointInStructor(
1957 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1958 if (!VTableAddressPoint)
1961 // Compute where to store the address point.
1962 llvm::Value *VirtualOffset = nullptr;
1963 CharUnits NonVirtualOffset = CharUnits::Zero();
1965 if (NeedsVirtualOffset) {
1966 // We need to use the virtual base offset offset because the virtual base
1967 // might have a different offset in the most derived class.
1968 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1972 NonVirtualOffset = OffsetFromNearestVBase;
1974 // We can just use the base offset in the complete class.
1975 NonVirtualOffset = Base.getBaseOffset();
1978 // Apply the offsets.
1979 llvm::Value *VTableField = LoadCXXThis();
1981 if (!NonVirtualOffset.isZero() || VirtualOffset)
1982 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1986 // Finally, store the address point. Use the same LLVM types as the field to
1987 // support optimization.
1988 llvm::Type *VTablePtrTy =
1989 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
1992 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
1993 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
1994 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1995 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
1999 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
2000 const CXXRecordDecl *NearestVBase,
2001 CharUnits OffsetFromNearestVBase,
2002 bool BaseIsNonVirtualPrimaryBase,
2003 const CXXRecordDecl *VTableClass,
2004 VisitedVirtualBasesSetTy& VBases) {
2005 // If this base is a non-virtual primary base the address point has already
2007 if (!BaseIsNonVirtualPrimaryBase) {
2008 // Initialize the vtable pointer for this base.
2009 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
2013 const CXXRecordDecl *RD = Base.getBase();
2016 for (const auto &I : RD->bases()) {
2017 CXXRecordDecl *BaseDecl
2018 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
2020 // Ignore classes without a vtable.
2021 if (!BaseDecl->isDynamicClass())
2024 CharUnits BaseOffset;
2025 CharUnits BaseOffsetFromNearestVBase;
2026 bool BaseDeclIsNonVirtualPrimaryBase;
2028 if (I.isVirtual()) {
2029 // Check if we've visited this virtual base before.
2030 if (!VBases.insert(BaseDecl).second)
2033 const ASTRecordLayout &Layout =
2034 getContext().getASTRecordLayout(VTableClass);
2036 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2037 BaseOffsetFromNearestVBase = CharUnits::Zero();
2038 BaseDeclIsNonVirtualPrimaryBase = false;
2040 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2042 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
2043 BaseOffsetFromNearestVBase =
2044 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
2045 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
2048 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
2049 I.isVirtual() ? BaseDecl : NearestVBase,
2050 BaseOffsetFromNearestVBase,
2051 BaseDeclIsNonVirtualPrimaryBase,
2052 VTableClass, VBases);
2056 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2057 // Ignore classes without a vtable.
2058 if (!RD->isDynamicClass())
2061 // Initialize the vtable pointers for this class and all of its bases.
2062 VisitedVirtualBasesSetTy VBases;
2063 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2064 /*NearestVBase=*/nullptr,
2065 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2066 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
2068 if (RD->getNumVBases())
2069 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
2072 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
2074 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
2075 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2076 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2081 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2082 // quite what we want.
2083 static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2085 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2086 E = PE->getSubExpr();
2090 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2091 if (CE->getCastKind() == CK_NoOp) {
2092 E = CE->getSubExpr();
2096 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2097 if (UO->getOpcode() == UO_Extension) {
2098 E = UO->getSubExpr();
2107 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2108 const CXXMethodDecl *MD) {
2109 // When building with -fapple-kext, all calls must go through the vtable since
2110 // the kernel linker can do runtime patching of vtables.
2111 if (getLangOpts().AppleKext)
2114 // If the most derived class is marked final, we know that no subclass can
2115 // override this member function and so we can devirtualize it. For example:
2117 // struct A { virtual void f(); }
2118 // struct B final : A { };
2124 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
2125 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2128 // If the member function is marked 'final', we know that it can't be
2129 // overridden and can therefore devirtualize it.
2130 if (MD->hasAttr<FinalAttr>())
2133 // Similarly, if the class itself is marked 'final' it can't be overridden
2134 // and we can therefore devirtualize the member function call.
2135 if (MD->getParent()->hasAttr<FinalAttr>())
2138 Base = skipNoOpCastsAndParens(Base);
2139 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2140 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2141 // This is a record decl. We know the type and can devirtualize it.
2142 return VD->getType()->isRecordType();
2148 // We can devirtualize calls on an object accessed by a class member access
2149 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2150 // a derived class object constructed in the same location.
2151 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2152 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2153 return VD->getType()->isRecordType();
2155 // We can always devirtualize calls on temporary object expressions.
2156 if (isa<CXXConstructExpr>(Base))
2159 // And calls on bound temporaries.
2160 if (isa<CXXBindTemporaryExpr>(Base))
2163 // Check if this is a call expr that returns a record type.
2164 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2165 return CE->getCallReturnType()->isRecordType();
2167 // We can't devirtualize the call.
2171 void CodeGenFunction::EmitForwardingCallToLambda(
2172 const CXXMethodDecl *callOperator,
2173 CallArgList &callArgs) {
2174 // Get the address of the call operator.
2175 const CGFunctionInfo &calleeFnInfo =
2176 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2177 llvm::Value *callee =
2178 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2179 CGM.getTypes().GetFunctionType(calleeFnInfo));
2181 // Prepare the return slot.
2182 const FunctionProtoType *FPT =
2183 callOperator->getType()->castAs<FunctionProtoType>();
2184 QualType resultType = FPT->getReturnType();
2185 ReturnValueSlot returnSlot;
2186 if (!resultType->isVoidType() &&
2187 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
2188 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
2189 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2191 // We don't need to separately arrange the call arguments because
2192 // the call can't be variadic anyway --- it's impossible to forward
2193 // variadic arguments.
2195 // Now emit our call.
2196 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2197 callArgs, callOperator);
2199 // If necessary, copy the returned value into the slot.
2200 if (!resultType->isVoidType() && returnSlot.isNull())
2201 EmitReturnOfRValue(RV, resultType);
2203 EmitBranchThroughCleanup(ReturnBlock);
2206 void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2207 const BlockDecl *BD = BlockInfo->getBlockDecl();
2208 const VarDecl *variable = BD->capture_begin()->getVariable();
2209 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2211 // Start building arguments for forwarding call
2212 CallArgList CallArgs;
2214 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2215 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2216 CallArgs.add(RValue::get(ThisPtr), ThisType);
2218 // Add the rest of the parameters.
2219 for (auto param : BD->params())
2220 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
2222 assert(!Lambda->isGenericLambda() &&
2223 "generic lambda interconversion to block not implemented");
2224 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
2227 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2228 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
2229 // FIXME: Making this work correctly is nasty because it requires either
2230 // cloning the body of the call operator or making the call operator forward.
2231 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
2235 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
2238 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2239 const CXXRecordDecl *Lambda = MD->getParent();
2241 // Start building arguments for forwarding call
2242 CallArgList CallArgs;
2244 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2245 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2246 CallArgs.add(RValue::get(ThisPtr), ThisType);
2248 // Add the rest of the parameters.
2249 for (auto Param : MD->params())
2250 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2252 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2253 // For a generic lambda, find the corresponding call operator specialization
2254 // to which the call to the static-invoker shall be forwarded.
2255 if (Lambda->isGenericLambda()) {
2256 assert(MD->isFunctionTemplateSpecialization());
2257 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2258 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2259 void *InsertPos = nullptr;
2260 FunctionDecl *CorrespondingCallOpSpecialization =
2261 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
2262 assert(CorrespondingCallOpSpecialization);
2263 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2265 EmitForwardingCallToLambda(CallOp, CallArgs);
2268 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2269 if (MD->isVariadic()) {
2270 // FIXME: Making this work correctly is nasty because it requires either
2271 // cloning the body of the call operator or making the call operator forward.
2272 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
2276 EmitLambdaDelegatingInvokeBody(MD);