blob: e4180a0d72da7452359f2e0894a8e38412442edf [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman64bee652012-02-25 02:48:22 +000014#include "CGBlocks.h"
Devang Pateld67ef0e2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Lang Hames56c00c42013-02-17 07:22:09 +000016#include "CGRecordLayout.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000017#include "CodeGenFunction.h"
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +000018#include "CGCXXABI.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000020#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000021#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000022#include "clang/AST/StmtCXX.h"
Lang Hames56c00c42013-02-17 07:22:09 +000023#include "clang/Basic/TargetBuiltins.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000024#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000025
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000026using namespace clang;
27using namespace CodeGen;
28
Ken Dyck55c02582011-03-22 00:53:26 +000029static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000030ComputeNonVirtualBaseClassOffset(ASTContext &Context,
31 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000032 CastExpr::path_const_iterator Start,
33 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000034 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000035
36 const CXXRecordDecl *RD = DerivedClass;
37
John McCallf871d0c2010-08-07 06:22:56 +000038 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000039 const CXXBaseSpecifier *Base = *I;
40 assert(!Base->isVirtual() && "Should not see virtual bases here!");
41
42 // Get the layout.
43 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
44
45 const CXXRecordDecl *BaseDecl =
46 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
47
48 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000049 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000050
51 RD = BaseDecl;
52 }
53
Ken Dyck55c02582011-03-22 00:53:26 +000054 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000055}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000056
Anders Carlsson84080ec2009-09-29 03:13:20 +000057llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000058CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000059 CastExpr::path_const_iterator PathBegin,
60 CastExpr::path_const_iterator PathEnd) {
61 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000062
Ken Dyck55c02582011-03-22 00:53:26 +000063 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000064 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
65 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000066 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000067 return 0;
68
Chris Lattner2acc6e32011-07-18 04:24:23 +000069 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000070 Types.ConvertType(getContext().getPointerDiffType());
71
Ken Dyck55c02582011-03-22 00:53:26 +000072 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000073}
74
Anders Carlsson8561a862010-04-24 23:01:49 +000075/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000076/// This should only be used for (1) non-virtual bases or (2) virtual bases
77/// when the type is known to be complete (e.g. in complete destructors).
78///
79/// The object pointed to by 'This' is assumed to be non-null.
80llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000081CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
82 const CXXRecordDecl *Derived,
83 const CXXRecordDecl *Base,
84 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000085 // 'this' must be a pointer (in some address space) to Derived.
86 assert(This->getType()->isPointerTy() &&
87 cast<llvm::PointerType>(This->getType())->getElementType()
88 == ConvertType(Derived));
89
90 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000091 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000092 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000093 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000094 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000095 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000096 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000097
98 // Shift and cast down to the base type.
99 // TODO: for complete types, this should be possible with a GEP.
100 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +0000101 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +0000102 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000103 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000104 }
105 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
106
107 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000108}
John McCallbff225e2010-02-16 04:15:37 +0000109
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000110static llvm::Value *
John McCall7916c992012-08-01 05:04:58 +0000111ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
112 CharUnits nonVirtualOffset,
113 llvm::Value *virtualOffset) {
114 // Assert that we have something to do.
115 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
116
117 // Compute the offset from the static and dynamic components.
118 llvm::Value *baseOffset;
119 if (!nonVirtualOffset.isZero()) {
120 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
121 nonVirtualOffset.getQuantity());
122 if (virtualOffset) {
123 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
124 }
125 } else {
126 baseOffset = virtualOffset;
127 }
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000128
129 // Apply the base offset.
John McCall7916c992012-08-01 05:04:58 +0000130 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
131 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
132 return ptr;
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000133}
134
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000135llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000136CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000137 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000138 CastExpr::path_const_iterator PathBegin,
139 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000140 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000141 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000142
John McCallf871d0c2010-08-07 06:22:56 +0000143 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000144 const CXXRecordDecl *VBase = 0;
145
John McCall7916c992012-08-01 05:04:58 +0000146 // Sema has done some convenient canonicalization here: if the
147 // access path involved any virtual steps, the conversion path will
148 // *start* with a step down to the correct virtual base subobject,
149 // and hence will not require any further steps.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000150 if ((*Start)->isVirtual()) {
151 VBase =
152 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
153 ++Start;
154 }
John McCall7916c992012-08-01 05:04:58 +0000155
156 // Compute the static offset of the ultimate destination within its
157 // allocating subobject (the virtual base, if there is one, or else
158 // the "complete" object that we see).
Ken Dyck55c02582011-03-22 00:53:26 +0000159 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000160 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000161 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000162
John McCall7916c992012-08-01 05:04:58 +0000163 // If there's a virtual step, we can sometimes "devirtualize" it.
164 // For now, that's limited to when the derived type is final.
165 // TODO: "devirtualize" this for accesses to known-complete objects.
166 if (VBase && Derived->hasAttr<FinalAttr>()) {
167 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
168 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
169 NonVirtualOffset += vBaseOffset;
170 VBase = 0; // we no longer have a virtual step
171 }
172
Anders Carlsson34a2d382010-04-24 21:06:20 +0000173 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000174 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000175 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall7916c992012-08-01 05:04:58 +0000176
177 // If the static offset is zero and we don't have a virtual step,
178 // just do a bitcast; null checks are unnecessary.
Ken Dyck55c02582011-03-22 00:53:26 +0000179 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000180 return Builder.CreateBitCast(Value, BasePtrTy);
181 }
John McCall7916c992012-08-01 05:04:58 +0000182
183 llvm::BasicBlock *origBB = 0;
184 llvm::BasicBlock *endBB = 0;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000185
John McCall7916c992012-08-01 05:04:58 +0000186 // Skip over the offset (and the vtable load) if we're supposed to
187 // null-check the pointer.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000188 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000189 origBB = Builder.GetInsertBlock();
190 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
191 endBB = createBasicBlock("cast.end");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000192
John McCall7916c992012-08-01 05:04:58 +0000193 llvm::Value *isNull = Builder.CreateIsNull(Value);
194 Builder.CreateCondBr(isNull, endBB, notNullBB);
195 EmitBlock(notNullBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000196 }
197
John McCall7916c992012-08-01 05:04:58 +0000198 // Compute the virtual offset.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000199 llvm::Value *VirtualOffset = 0;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000200 if (VBase) {
John McCall7916c992012-08-01 05:04:58 +0000201 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000202 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000203
John McCall7916c992012-08-01 05:04:58 +0000204 // Apply both offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000205 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000206 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000207 VirtualOffset);
208
John McCall7916c992012-08-01 05:04:58 +0000209 // Cast to the destination type.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000210 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall7916c992012-08-01 05:04:58 +0000211
212 // Build a phi if we needed a null check.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000213 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000214 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
215 Builder.CreateBr(endBB);
216 EmitBlock(endBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000217
John McCall7916c992012-08-01 05:04:58 +0000218 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
219 PHI->addIncoming(Value, notNullBB);
220 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000221 Value = PHI;
222 }
223
224 return Value;
225}
226
227llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000228CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000229 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000230 CastExpr::path_const_iterator PathBegin,
231 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000232 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000233 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000234
Anders Carlssona3697c92009-11-23 17:57:54 +0000235 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000236 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000237 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smithc7648302013-02-13 21:18:23 +0000238
Anders Carlssona552ea72010-01-31 01:43:37 +0000239 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000240 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000241
242 if (!NonVirtualOffset) {
243 // No offset, we can just cast back.
244 return Builder.CreateBitCast(Value, DerivedPtrTy);
245 }
246
Anders Carlssona3697c92009-11-23 17:57:54 +0000247 llvm::BasicBlock *CastNull = 0;
248 llvm::BasicBlock *CastNotNull = 0;
249 llvm::BasicBlock *CastEnd = 0;
250
251 if (NullCheckValue) {
252 CastNull = createBasicBlock("cast.null");
253 CastNotNull = createBasicBlock("cast.notnull");
254 CastEnd = createBasicBlock("cast.end");
255
Anders Carlssonb9241242011-04-11 00:30:07 +0000256 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000257 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
258 EmitBlock(CastNotNull);
259 }
260
Anders Carlssona552ea72010-01-31 01:43:37 +0000261 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000262 Value = Builder.CreateBitCast(Value, Int8PtrTy);
263 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
264 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000265
266 // Just cast.
267 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000268
269 if (NullCheckValue) {
270 Builder.CreateBr(CastEnd);
271 EmitBlock(CastNull);
272 Builder.CreateBr(CastEnd);
273 EmitBlock(CastEnd);
274
Jay Foadbbf3bac2011-03-30 11:28:58 +0000275 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000276 PHI->addIncoming(Value, CastNotNull);
277 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
278 CastNull);
279 Value = PHI;
280 }
281
282 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000283}
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000284
285llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
286 bool ForVirtualBase,
287 bool Delegating) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000288 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000289 // This constructor/destructor does not need a VTT parameter.
290 return 0;
291 }
292
John McCallf5ebf9b2013-05-03 07:33:41 +0000293 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssonc997d422010-01-02 01:01:18 +0000294 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000295
Anders Carlssonc997d422010-01-02 01:01:18 +0000296 llvm::Value *VTT;
297
John McCall3b477332010-02-18 19:59:28 +0000298 uint64_t SubVTTIndex;
299
Douglas Gregor378e1e72013-01-31 05:50:40 +0000300 if (Delegating) {
301 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000302 return LoadCXXVTT();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000303 } else if (RD == Base) {
304 // If the record matches the base, this is the complete ctor/dtor
305 // variant calling the base variant in a class with virtual bases.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000306 assert(!CodeGenVTables::needsVTTParameter(CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000307 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000308 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000309 SubVTTIndex = 0;
310 } else {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000311 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000312 CharUnits BaseOffset = ForVirtualBase ?
313 Layout.getVBaseClassOffset(Base) :
314 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000315
316 SubVTTIndex =
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000317 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000318 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
319 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000320
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000321 if (CodeGenVTables::needsVTTParameter(CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000322 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000323 VTT = LoadCXXVTT();
324 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000325 } else {
326 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000327 VTT = CGM.getVTables().GetAddrOfVTT(RD);
328 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000329 }
330
331 return VTT;
332}
333
John McCall182ab512010-07-21 01:23:41 +0000334namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000335 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000336 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000337 const CXXRecordDecl *BaseClass;
338 bool BaseIsVirtual;
339 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
340 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000341
John McCallad346f42011-07-12 20:27:29 +0000342 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000343 const CXXRecordDecl *DerivedClass =
344 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
345
346 const CXXDestructorDecl *D = BaseClass->getDestructor();
347 llvm::Value *Addr =
348 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
349 DerivedClass, BaseClass,
350 BaseIsVirtual);
Douglas Gregor378e1e72013-01-31 05:50:40 +0000351 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
352 /*Delegating=*/false, Addr);
John McCall182ab512010-07-21 01:23:41 +0000353 }
354 };
John McCall7e1dff72010-09-17 02:31:44 +0000355
356 /// A visitor which checks whether an initializer uses 'this' in a
357 /// way which requires the vtable to be properly set.
358 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
359 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
360
361 bool UsesThis;
362
363 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
364
365 // Black-list all explicit and implicit references to 'this'.
366 //
367 // Do we need to worry about external references to 'this' derived
368 // from arbitrary code? If so, then anything which runs arbitrary
369 // external code might potentially access the vtable.
370 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
371 };
372}
373
374static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
375 DynamicThisUseChecker Checker(C);
376 Checker.Visit(const_cast<Expr*>(Init));
377 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000378}
379
Anders Carlsson607d0372009-12-24 22:46:43 +0000380static void EmitBaseInitializer(CodeGenFunction &CGF,
381 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000382 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000383 CXXCtorType CtorType) {
384 assert(BaseInit->isBaseInitializer() &&
385 "Must have base initializer!");
386
387 llvm::Value *ThisPtr = CGF.LoadCXXThis();
388
389 const Type *BaseType = BaseInit->getBaseClass();
390 CXXRecordDecl *BaseClassDecl =
391 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
392
Anders Carlsson80638c52010-04-12 00:51:03 +0000393 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000394
395 // The base constructor doesn't construct virtual bases.
396 if (CtorType == Ctor_Base && isBaseVirtual)
397 return;
398
John McCall7e1dff72010-09-17 02:31:44 +0000399 // If the initializer for the base (other than the constructor
400 // itself) accesses 'this' in any way, we need to initialize the
401 // vtables.
402 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
403 CGF.InitializeVTablePointers(ClassDecl);
404
John McCallbff225e2010-02-16 04:15:37 +0000405 // We can pretend to be a complete class because it only matters for
406 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000407 llvm::Value *V =
408 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000409 BaseClassDecl,
410 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000411 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000412 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000413 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000414 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000415 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000416 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000417
418 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000419
David Blaikie4e4d0842012-03-11 07:00:24 +0000420 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000421 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000422 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
423 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000424}
425
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000426static void EmitAggMemberInitializer(CodeGenFunction &CGF,
427 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000428 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000429 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000430 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000431 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000432 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000433 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000434 LValue LV = LHS;
Sebastian Redl924db712012-02-19 15:41:54 +0000435 { // Scope for Cleanups.
436 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000437
Sebastian Redl924db712012-02-19 15:41:54 +0000438 if (ArrayIndexVar) {
439 // If we have an array index variable, load it and use it as an offset.
440 // Then, increment the value.
441 llvm::Value *Dest = LHS.getAddress();
442 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
443 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
444 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
445 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
446 CGF.Builder.CreateStore(Next, ArrayIndexVar);
447
448 // Update the LValue.
449 LV.setAddress(Dest);
450 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
451 LV.setAlignment(std::min(Align, LV.getAlignment()));
452 }
453
John McCall9d232c82013-03-07 21:37:08 +0000454 switch (CGF.getEvaluationKind(T)) {
455 case TEK_Scalar:
Sebastian Redl924db712012-02-19 15:41:54 +0000456 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
John McCall9d232c82013-03-07 21:37:08 +0000457 break;
458 case TEK_Complex:
459 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
460 break;
461 case TEK_Aggregate: {
Sebastian Redl924db712012-02-19 15:41:54 +0000462 AggValueSlot Slot =
463 AggValueSlot::forLValue(LV,
464 AggValueSlot::IsDestructed,
465 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000466 AggValueSlot::IsNotAliased);
Sebastian Redl924db712012-02-19 15:41:54 +0000467
468 CGF.EmitAggExpr(Init, Slot);
John McCall9d232c82013-03-07 21:37:08 +0000469 break;
470 }
Sebastian Redl924db712012-02-19 15:41:54 +0000471 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000472 }
John McCall558d2ab2010-09-15 10:14:12 +0000473
Sebastian Redl924db712012-02-19 15:41:54 +0000474 // Now, outside of the initializer cleanup scope, destroy the backing array
475 // for a std::initializer_list member.
Sebastian Redl972edf02012-02-19 16:03:09 +0000476 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl924db712012-02-19 15:41:54 +0000477
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000478 return;
479 }
480
481 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
482 assert(Array && "Array initialization without the array type?");
483 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000484 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000485 assert(IndexVar && "Array index variable not loaded");
486
487 // Initialize this index variable to zero.
488 llvm::Value* Zero
489 = llvm::Constant::getNullValue(
490 CGF.ConvertType(CGF.getContext().getSizeType()));
491 CGF.Builder.CreateStore(Zero, IndexVar);
492
493 // Start the loop with a block that tests the condition.
494 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
495 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
496
497 CGF.EmitBlock(CondBlock);
498
499 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
500 // Generate: if (loop-index < number-of-elements) fall to the loop body,
501 // otherwise, go to the block after the for-loop.
502 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000503 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000504 llvm::Value *NumElementsPtr =
505 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000506 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
507 "isless");
508
509 // If the condition is true, execute the body.
510 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
511
512 CGF.EmitBlock(ForBody);
513 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
514
515 {
John McCallf1549f62010-07-06 01:34:17 +0000516 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000517
518 // Inside the loop body recurse to emit the inner loop or, eventually, the
519 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000520 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
521 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000522 }
523
524 CGF.EmitBlock(ContinueBlock);
525
526 // Emit the increment of the loop counter.
527 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
528 Counter = CGF.Builder.CreateLoad(IndexVar);
529 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
530 CGF.Builder.CreateStore(NextVal, IndexVar);
531
532 // Finally, branch back up to the condition for the next iteration.
533 CGF.EmitBranch(CondBlock);
534
535 // Emit the fall-through block.
536 CGF.EmitBlock(AfterFor, true);
537}
John McCall182ab512010-07-21 01:23:41 +0000538
Anders Carlsson607d0372009-12-24 22:46:43 +0000539static void EmitMemberInitializer(CodeGenFunction &CGF,
540 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000541 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000542 const CXXConstructorDecl *Constructor,
543 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000544 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000545 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000546 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000547
548 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000549 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000550 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000551
552 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000553 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000554 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000555
Francois Pichet00eb3f92010-12-04 09:14:42 +0000556 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000557 // If we are initializing an anonymous union field, drill down to
558 // the field.
559 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
560 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
561 IEnd = IndirectField->chain_end();
562 for ( ; I != IEnd; ++I)
563 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000564 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000565 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000566 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000567 }
568
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000569 // Special case: if we are in a copy or move constructor, and we are copying
570 // an array of PODs or classes with trivial copy constructors, ignore the
571 // AST and perform the copy we know is equivalent.
572 // FIXME: This is hacky at best... if we had a bit more explicit information
573 // in the AST, we could generalize it more easily.
574 const ConstantArrayType *Array
575 = CGF.getContext().getAsConstantArrayType(FieldType);
576 if (Array && Constructor->isImplicitlyDefined() &&
577 Constructor->isCopyOrMoveConstructor()) {
578 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000579 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000580 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000581 (CE && CE->getConstructor()->isTrivial())) {
582 // Find the source pointer. We know it's the last argument because
583 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000584 unsigned SrcArgIndex = Args.size() - 1;
585 llvm::Value *SrcPtr
586 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000587 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
588 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000589
590 // Copy the aggregate.
591 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000592 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000593 return;
594 }
595 }
596
597 ArrayRef<VarDecl *> ArrayIndexes;
598 if (MemberInit->getNumArrayIndices())
599 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000600 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000601}
602
Eli Friedmanb74ed082012-02-14 02:31:03 +0000603void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
604 LValue LHS, Expr *Init,
605 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000606 QualType FieldType = Field->getType();
John McCall9d232c82013-03-07 21:37:08 +0000607 switch (getEvaluationKind(FieldType)) {
608 case TEK_Scalar:
John McCallf85e1932011-06-15 23:02:42 +0000609 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000610 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000611 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000612 RValue RHS = RValue::get(EmitScalarExpr(Init));
613 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000614 }
John McCall9d232c82013-03-07 21:37:08 +0000615 break;
616 case TEK_Complex:
617 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
618 break;
619 case TEK_Aggregate: {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000620 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000621 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000622 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000623
624 // The LHS is a pointer to the first object we'll be constructing, as
625 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000626 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
627 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000628 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000629 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
630 BasePtr);
631 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000632
633 // Create an array index that will be used to walk over all of the
634 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000635 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000636 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000637 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000638
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000639
640 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000641 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000642 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000643 }
644
Eli Friedmanb74ed082012-02-14 02:31:03 +0000645 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000646 ArrayIndexes, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000647 }
John McCall9d232c82013-03-07 21:37:08 +0000648 }
John McCall074cae02013-02-01 05:11:40 +0000649
650 // Ensure that we destroy this object if an exception is thrown
651 // later in the constructor.
652 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
653 if (needsEHCleanup(dtorKind))
654 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlsson607d0372009-12-24 22:46:43 +0000655}
656
John McCallc0bf4622010-02-23 00:48:20 +0000657/// Checks whether the given constructor is a valid subject for the
658/// complete-to-base constructor delegation optimization, i.e.
659/// emitting the complete constructor as a simple call to the base
660/// constructor.
661static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
662
663 // Currently we disable the optimization for classes with virtual
664 // bases because (1) the addresses of parameter variables need to be
665 // consistent across all initializers but (2) the delegate function
666 // call necessarily creates a second copy of the parameter variable.
667 //
668 // The limiting example (purely theoretical AFAIK):
669 // struct A { A(int &c) { c++; } };
670 // struct B : virtual A {
671 // B(int count) : A(count) { printf("%d\n", count); }
672 // };
673 // ...although even this example could in principle be emitted as a
674 // delegation since the address of the parameter doesn't escape.
675 if (Ctor->getParent()->getNumVBases()) {
676 // TODO: white-list trivial vbase initializers. This case wouldn't
677 // be subject to the restrictions below.
678
679 // TODO: white-list cases where:
680 // - there are no non-reference parameters to the constructor
681 // - the initializers don't access any non-reference parameters
682 // - the initializers don't take the address of non-reference
683 // parameters
684 // - etc.
685 // If we ever add any of the above cases, remember that:
686 // - function-try-blocks will always blacklist this optimization
687 // - we need to perform the constructor prologue and cleanup in
688 // EmitConstructorBody.
689
690 return false;
691 }
692
693 // We also disable the optimization for variadic functions because
694 // it's impossible to "re-pass" varargs.
695 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
696 return false;
697
Sean Hunt059ce0d2011-05-01 07:04:31 +0000698 // FIXME: Decide if we can do a delegation of a delegating constructor.
699 if (Ctor->isDelegatingConstructor())
700 return false;
701
John McCallc0bf4622010-02-23 00:48:20 +0000702 return true;
703}
704
John McCall9fc6a772010-02-19 09:25:03 +0000705/// EmitConstructorBody - Emits the body of the current constructor.
706void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
707 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
708 CXXCtorType CtorType = CurGD.getCtorType();
709
John McCallc0bf4622010-02-23 00:48:20 +0000710 // Before we go any further, try the complete->base constructor
711 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000712 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCall64aa4b32013-04-16 22:48:15 +0000713 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000714 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000715 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000716 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
717 return;
718 }
719
John McCall9fc6a772010-02-19 09:25:03 +0000720 Stmt *Body = Ctor->getBody();
721
John McCallc0bf4622010-02-23 00:48:20 +0000722 // Enter the function-try-block before the constructor prologue if
723 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000724 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000725 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000726 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000727
John McCallf1549f62010-07-06 01:34:17 +0000728 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000729
John McCall56ea3772012-03-30 04:25:03 +0000730 // TODO: in restricted cases, we can emit the vbase initializers of
731 // a complete ctor and then delegate to the base ctor.
732
John McCallc0bf4622010-02-23 00:48:20 +0000733 // Emit the constructor prologue, i.e. the base and member
734 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000735 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000736
737 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000738 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000739 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
740 else if (Body)
741 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000742
743 // Emit any cleanup blocks associated with the member or base
744 // initializers, which includes (along the exceptional path) the
745 // destructors for those members and bases that were fully
746 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000747 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000748
John McCallc0bf4622010-02-23 00:48:20 +0000749 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000750 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000751}
752
Lang Hames56c00c42013-02-17 07:22:09 +0000753namespace {
754 class FieldMemcpyizer {
755 public:
756 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
757 const VarDecl *SrcRec)
758 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
759 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
760 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
761 LastAddedFieldIndex(0) { }
762
763 static bool isMemcpyableField(FieldDecl *F) {
764 Qualifiers Qual = F->getType().getQualifiers();
765 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
766 return false;
767 return true;
768 }
769
770 void addMemcpyableField(FieldDecl *F) {
771 if (FirstField == 0)
772 addInitialField(F);
773 else
774 addNextField(F);
775 }
776
777 CharUnits getMemcpySize() const {
778 unsigned LastFieldSize =
779 LastField->isBitField() ?
780 LastField->getBitWidthValue(CGF.getContext()) :
781 CGF.getContext().getTypeSize(LastField->getType());
782 uint64_t MemcpySizeBits =
783 LastFieldOffset + LastFieldSize - FirstFieldOffset +
784 CGF.getContext().getCharWidth() - 1;
785 CharUnits MemcpySize =
786 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
787 return MemcpySize;
788 }
789
790 void emitMemcpy() {
791 // Give the subclass a chance to bail out if it feels the memcpy isn't
792 // worth it (e.g. Hasn't aggregated enough data).
793 if (FirstField == 0) {
794 return;
795 }
796
Lang Hames5e8577e2013-02-27 04:14:49 +0000797 CharUnits Alignment;
Lang Hames56c00c42013-02-17 07:22:09 +0000798
799 if (FirstField->isBitField()) {
800 const CGRecordLayout &RL =
801 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
802 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000803 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
804 } else {
Lang Hames23742cd2013-03-05 20:27:24 +0000805 Alignment = CGF.getContext().getDeclAlign(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000806 }
Lang Hames56c00c42013-02-17 07:22:09 +0000807
Lang Hames5e8577e2013-02-27 04:14:49 +0000808 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
809 Alignment) == 0 && "Bad field alignment.");
810
Lang Hames56c00c42013-02-17 07:22:09 +0000811 CharUnits MemcpySize = getMemcpySize();
812 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
813 llvm::Value *ThisPtr = CGF.LoadCXXThis();
814 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
815 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
816 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
817 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
818 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
819
820 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
821 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
822 MemcpySize, Alignment);
823 reset();
824 }
825
826 void reset() {
827 FirstField = 0;
828 }
829
830 protected:
831 CodeGenFunction &CGF;
832 const CXXRecordDecl *ClassDecl;
833
834 private:
835
836 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
837 CharUnits Size, CharUnits Alignment) {
838 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
839 llvm::Type *DBP =
840 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
841 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
842
843 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
844 llvm::Type *SBP =
845 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
846 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
847
848 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
849 Alignment.getQuantity());
850 }
851
852 void addInitialField(FieldDecl *F) {
853 FirstField = F;
854 LastField = F;
855 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
856 LastFieldOffset = FirstFieldOffset;
857 LastAddedFieldIndex = F->getFieldIndex();
858 return;
859 }
860
861 void addNextField(FieldDecl *F) {
John McCall402cd222013-05-07 05:20:46 +0000862 // For the most part, the following invariant will hold:
863 // F->getFieldIndex() == LastAddedFieldIndex + 1
864 // The one exception is that Sema won't add a copy-initializer for an
865 // unnamed bitfield, which will show up here as a gap in the sequence.
866 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
867 "Cannot aggregate fields out of order.");
Lang Hames56c00c42013-02-17 07:22:09 +0000868 LastAddedFieldIndex = F->getFieldIndex();
869
870 // The 'first' and 'last' fields are chosen by offset, rather than field
871 // index. This allows the code to support bitfields, as well as regular
872 // fields.
873 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
874 if (FOffset < FirstFieldOffset) {
875 FirstField = F;
876 FirstFieldOffset = FOffset;
877 } else if (FOffset > LastFieldOffset) {
878 LastField = F;
879 LastFieldOffset = FOffset;
880 }
881 }
882
883 const VarDecl *SrcRec;
884 const ASTRecordLayout &RecLayout;
885 FieldDecl *FirstField;
886 FieldDecl *LastField;
887 uint64_t FirstFieldOffset, LastFieldOffset;
888 unsigned LastAddedFieldIndex;
889 };
890
891 class ConstructorMemcpyizer : public FieldMemcpyizer {
892 private:
893
894 /// Get source argument for copy constructor. Returns null if not a copy
895 /// constructor.
896 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
897 FunctionArgList &Args) {
898 if (CD->isCopyOrMoveConstructor() && CD->isImplicitlyDefined())
899 return Args[Args.size() - 1];
900 return 0;
901 }
902
903 // Returns true if a CXXCtorInitializer represents a member initialization
904 // that can be rolled into a memcpy.
905 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
906 if (!MemcpyableCtor)
907 return false;
908 FieldDecl *Field = MemberInit->getMember();
909 assert(Field != 0 && "No field for member init.");
910 QualType FieldType = Field->getType();
911 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
912
913 // Bail out on non-POD, not-trivially-constructable members.
914 if (!(CE && CE->getConstructor()->isTrivial()) &&
915 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
916 FieldType->isReferenceType()))
917 return false;
918
919 // Bail out on volatile fields.
920 if (!isMemcpyableField(Field))
921 return false;
922
923 // Otherwise we're good.
924 return true;
925 }
926
927 public:
928 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
929 FunctionArgList &Args)
930 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
931 ConstructorDecl(CD),
932 MemcpyableCtor(CD->isImplicitlyDefined() &&
933 CD->isCopyOrMoveConstructor() &&
934 CGF.getLangOpts().getGC() == LangOptions::NonGC),
935 Args(Args) { }
936
937 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
938 if (isMemberInitMemcpyable(MemberInit)) {
939 AggregatedInits.push_back(MemberInit);
940 addMemcpyableField(MemberInit->getMember());
941 } else {
942 emitAggregatedInits();
943 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
944 ConstructorDecl, Args);
945 }
946 }
947
948 void emitAggregatedInits() {
949 if (AggregatedInits.size() <= 1) {
950 // This memcpy is too small to be worthwhile. Fall back on default
951 // codegen.
952 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
953 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
954 AggregatedInits[i], ConstructorDecl, Args);
955 }
956 reset();
957 return;
958 }
959
960 pushEHDestructors();
961 emitMemcpy();
962 AggregatedInits.clear();
963 }
964
965 void pushEHDestructors() {
966 llvm::Value *ThisPtr = CGF.LoadCXXThis();
967 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
968 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
969
970 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
971 QualType FieldType = AggregatedInits[i]->getMember()->getType();
972 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
973 if (CGF.needsEHCleanup(dtorKind))
974 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
975 }
976 }
977
978 void finish() {
979 emitAggregatedInits();
980 }
981
982 private:
983 const CXXConstructorDecl *ConstructorDecl;
984 bool MemcpyableCtor;
985 FunctionArgList &Args;
986 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
987 };
988
989 class AssignmentMemcpyizer : public FieldMemcpyizer {
990 private:
991
992 // Returns the memcpyable field copied by the given statement, if one
993 // exists. Otherwise r
994 FieldDecl* getMemcpyableField(Stmt *S) {
995 if (!AssignmentsMemcpyable)
996 return 0;
997 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
998 // Recognise trivial assignments.
999 if (BO->getOpcode() != BO_Assign)
1000 return 0;
1001 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1002 if (!ME)
1003 return 0;
1004 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1005 if (!Field || !isMemcpyableField(Field))
1006 return 0;
1007 Stmt *RHS = BO->getRHS();
1008 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1009 RHS = EC->getSubExpr();
1010 if (!RHS)
1011 return 0;
1012 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1013 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1014 return 0;
1015 return Field;
1016 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1017 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1018 if (!(MD && (MD->isCopyAssignmentOperator() ||
1019 MD->isMoveAssignmentOperator()) &&
1020 MD->isTrivial()))
1021 return 0;
1022 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1023 if (!IOA)
1024 return 0;
1025 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1026 if (!Field || !isMemcpyableField(Field))
1027 return 0;
1028 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1029 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1030 return 0;
1031 return Field;
1032 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1033 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1034 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1035 return 0;
1036 Expr *DstPtr = CE->getArg(0);
1037 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1038 DstPtr = DC->getSubExpr();
1039 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1040 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1041 return 0;
1042 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1043 if (!ME)
1044 return 0;
1045 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1046 if (!Field || !isMemcpyableField(Field))
1047 return 0;
1048 Expr *SrcPtr = CE->getArg(1);
1049 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1050 SrcPtr = SC->getSubExpr();
1051 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1052 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1053 return 0;
1054 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1055 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1056 return 0;
1057 return Field;
1058 }
1059
1060 return 0;
1061 }
1062
1063 bool AssignmentsMemcpyable;
1064 SmallVector<Stmt*, 16> AggregatedStmts;
1065
1066 public:
1067
1068 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1069 FunctionArgList &Args)
1070 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1071 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1072 assert(Args.size() == 2);
1073 }
1074
1075 void emitAssignment(Stmt *S) {
1076 FieldDecl *F = getMemcpyableField(S);
1077 if (F) {
1078 addMemcpyableField(F);
1079 AggregatedStmts.push_back(S);
1080 } else {
1081 emitAggregatedStmts();
1082 CGF.EmitStmt(S);
1083 }
1084 }
1085
1086 void emitAggregatedStmts() {
1087 if (AggregatedStmts.size() <= 1) {
1088 for (unsigned i = 0; i < AggregatedStmts.size(); ++i)
1089 CGF.EmitStmt(AggregatedStmts[i]);
1090 reset();
1091 }
1092
1093 emitMemcpy();
1094 AggregatedStmts.clear();
1095 }
1096
1097 void finish() {
1098 emitAggregatedStmts();
1099 }
1100 };
1101
1102}
1103
Anders Carlsson607d0372009-12-24 22:46:43 +00001104/// EmitCtorPrologue - This routine generates necessary code to initialize
1105/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001106void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001107 CXXCtorType CtorType,
1108 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001109 if (CD->isDelegatingConstructor())
1110 return EmitDelegatingCXXConstructorCall(CD, Args);
1111
Anders Carlsson607d0372009-12-24 22:46:43 +00001112 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001113
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001114 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1115 E = CD->init_end();
1116
1117 llvm::BasicBlock *BaseCtorContinueBB = 0;
1118 if (ClassDecl->getNumVBases() &&
1119 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1120 // The ABIs that don't have constructor variants need to put a branch
1121 // before the virtual base initialization code.
1122 BaseCtorContinueBB = CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this);
1123 assert(BaseCtorContinueBB);
1124 }
1125
1126 // Virtual base initializers first.
1127 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1128 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1129 }
1130
1131 if (BaseCtorContinueBB) {
1132 // Complete object handler should continue to the remaining initializers.
1133 Builder.CreateBr(BaseCtorContinueBB);
1134 EmitBlock(BaseCtorContinueBB);
1135 }
1136
1137 // Then, non-virtual base initializers.
1138 for (; B != E && (*B)->isBaseInitializer(); B++) {
1139 assert(!(*B)->isBaseVirtual());
1140 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001141 }
1142
Anders Carlsson603d6d12010-03-28 21:07:49 +00001143 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001144
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001145 // And finally, initialize class members.
Richard Smithc3bf52c2013-04-20 22:23:05 +00001146 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hames56c00c42013-02-17 07:22:09 +00001147 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001148 for (; B != E; B++) {
1149 CXXCtorInitializer *Member = (*B);
1150 assert(!Member->isBaseInitializer());
1151 assert(Member->isAnyMemberInitializer() &&
1152 "Delegating initializer on non-delegating constructor");
1153 CM.addMemberInitializer(Member);
1154 }
Lang Hames56c00c42013-02-17 07:22:09 +00001155 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001156}
1157
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001158static bool
1159FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1160
1161static bool
1162HasTrivialDestructorBody(ASTContext &Context,
1163 const CXXRecordDecl *BaseClassDecl,
1164 const CXXRecordDecl *MostDerivedClassDecl)
1165{
1166 // If the destructor is trivial we don't have to check anything else.
1167 if (BaseClassDecl->hasTrivialDestructor())
1168 return true;
1169
1170 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1171 return false;
1172
1173 // Check fields.
1174 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1175 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001176 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001177
1178 if (!FieldHasTrivialDestructorBody(Context, Field))
1179 return false;
1180 }
1181
1182 // Check non-virtual bases.
1183 for (CXXRecordDecl::base_class_const_iterator I =
1184 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1185 I != E; ++I) {
1186 if (I->isVirtual())
1187 continue;
1188
1189 const CXXRecordDecl *NonVirtualBase =
1190 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1191 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1192 MostDerivedClassDecl))
1193 return false;
1194 }
1195
1196 if (BaseClassDecl == MostDerivedClassDecl) {
1197 // Check virtual bases.
1198 for (CXXRecordDecl::base_class_const_iterator I =
1199 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1200 I != E; ++I) {
1201 const CXXRecordDecl *VirtualBase =
1202 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1203 if (!HasTrivialDestructorBody(Context, VirtualBase,
1204 MostDerivedClassDecl))
1205 return false;
1206 }
1207 }
1208
1209 return true;
1210}
1211
1212static bool
1213FieldHasTrivialDestructorBody(ASTContext &Context,
1214 const FieldDecl *Field)
1215{
1216 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1217
1218 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1219 if (!RT)
1220 return true;
1221
1222 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1223 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1224}
1225
Anders Carlssonffb945f2011-05-14 23:26:09 +00001226/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1227/// any vtable pointers before calling this destructor.
1228static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001229 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001230 if (!Dtor->hasTrivialBody())
1231 return false;
1232
1233 // Check the fields.
1234 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1235 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1236 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001237 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001238
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001239 if (!FieldHasTrivialDestructorBody(Context, Field))
1240 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001241 }
1242
1243 return true;
1244}
1245
John McCall9fc6a772010-02-19 09:25:03 +00001246/// EmitDestructorBody - Emits the body of the current destructor.
1247void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1248 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1249 CXXDtorType DtorType = CurGD.getDtorType();
1250
John McCall50da2ca2010-07-21 05:30:47 +00001251 // The call to operator delete in a deleting destructor happens
1252 // outside of the function-try-block, which means it's always
1253 // possible to delegate the destructor body to the complete
1254 // destructor. Do so.
1255 if (DtorType == Dtor_Deleting) {
1256 EnterDtorCleanups(Dtor, Dtor_Deleting);
1257 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001258 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001259 PopCleanupBlock();
1260 return;
1261 }
1262
John McCall9fc6a772010-02-19 09:25:03 +00001263 Stmt *Body = Dtor->getBody();
1264
1265 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001266 // anything else.
1267 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001268 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001269 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001270
John McCall50da2ca2010-07-21 05:30:47 +00001271 // Enter the epilogue cleanups.
1272 RunCleanupsScope DtorEpilogue(*this);
1273
John McCall9fc6a772010-02-19 09:25:03 +00001274 // If this is the complete variant, just invoke the base variant;
1275 // the epilogue will destruct the virtual bases. But we can't do
1276 // this optimization if the body is a function-try-block, because
1277 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +00001278 switch (DtorType) {
1279 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1280
1281 case Dtor_Complete:
1282 // Enter the cleanup scopes for virtual bases.
1283 EnterDtorCleanups(Dtor, Dtor_Complete);
1284
John McCallb8b2c9d2013-01-25 22:30:49 +00001285 if (!isTryBody &&
John McCall64aa4b32013-04-16 22:48:15 +00001286 CGM.getTarget().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +00001287 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001288 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001289 break;
1290 }
1291 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001292
John McCall50da2ca2010-07-21 05:30:47 +00001293 case Dtor_Base:
1294 // Enter the cleanup scopes for fields and non-virtual bases.
1295 EnterDtorCleanups(Dtor, Dtor_Base);
1296
1297 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001298 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1299 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001300
1301 if (isTryBody)
1302 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1303 else if (Body)
1304 EmitStmt(Body);
1305 else {
1306 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1307 // nothing to do besides what's in the epilogue
1308 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001309 // -fapple-kext must inline any call to this dtor into
1310 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001311 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001312 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001313 break;
John McCall9fc6a772010-02-19 09:25:03 +00001314 }
1315
John McCall50da2ca2010-07-21 05:30:47 +00001316 // Jump out through the epilogue cleanups.
1317 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001318
1319 // Exit the try if applicable.
1320 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001321 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001322}
1323
Lang Hames56c00c42013-02-17 07:22:09 +00001324void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1325 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1326 const Stmt *RootS = AssignOp->getBody();
1327 assert(isa<CompoundStmt>(RootS) &&
1328 "Body of an implicit assignment operator should be compound stmt.");
1329 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1330
1331 LexicalScope Scope(*this, RootCS->getSourceRange());
1332
1333 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1334 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1335 E = RootCS->body_end();
1336 I != E; ++I) {
1337 AM.emitAssignment(*I);
1338 }
1339 AM.finish();
1340}
1341
John McCall50da2ca2010-07-21 05:30:47 +00001342namespace {
1343 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001344 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001345 CallDtorDelete() {}
1346
John McCallad346f42011-07-12 20:27:29 +00001347 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001348 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1349 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1350 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1351 CGF.getContext().getTagDeclType(ClassDecl));
1352 }
1353 };
1354
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001355 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1356 llvm::Value *ShouldDeleteCondition;
1357 public:
1358 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1359 : ShouldDeleteCondition(ShouldDeleteCondition) {
1360 assert(ShouldDeleteCondition != NULL);
1361 }
1362
1363 void Emit(CodeGenFunction &CGF, Flags flags) {
1364 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1365 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1366 llvm::Value *ShouldCallDelete
1367 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1368 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1369
1370 CGF.EmitBlock(callDeleteBB);
1371 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1372 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1373 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1374 CGF.getContext().getTagDeclType(ClassDecl));
1375 CGF.Builder.CreateBr(continueBB);
1376
1377 CGF.EmitBlock(continueBB);
1378 }
1379 };
1380
John McCall9928c482011-07-12 16:41:08 +00001381 class DestroyField : public EHScopeStack::Cleanup {
1382 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001383 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001384 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001385
John McCall9928c482011-07-12 16:41:08 +00001386 public:
1387 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1388 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001389 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001390 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001391
John McCallad346f42011-07-12 20:27:29 +00001392 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001393 // Find the address of the field.
1394 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001395 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1396 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1397 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001398 assert(LV.isSimple());
1399
1400 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001401 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001402 }
1403 };
1404}
1405
Anders Carlsson607d0372009-12-24 22:46:43 +00001406/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1407/// destructor. This is to call destructors on members and base classes
1408/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001409void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1410 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001411 assert(!DD->isTrivial() &&
1412 "Should not emit dtor epilogue for trivial dtor!");
1413
John McCall50da2ca2010-07-21 05:30:47 +00001414 // The deleting-destructor phase just needs to call the appropriate
1415 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001416 if (DtorType == Dtor_Deleting) {
1417 assert(DD->getOperatorDelete() &&
1418 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001419 if (CXXStructorImplicitParamValue) {
1420 // If there is an implicit param to the deleting dtor, it's a boolean
1421 // telling whether we should call delete at the end of the dtor.
1422 EHStack.pushCleanup<CallDtorDeleteConditional>(
1423 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1424 } else {
1425 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1426 }
John McCall3b477332010-02-18 19:59:28 +00001427 return;
1428 }
1429
John McCall50da2ca2010-07-21 05:30:47 +00001430 const CXXRecordDecl *ClassDecl = DD->getParent();
1431
Richard Smith416f63e2011-09-18 12:11:43 +00001432 // Unions have no bases and do not call field destructors.
1433 if (ClassDecl->isUnion())
1434 return;
1435
John McCall50da2ca2010-07-21 05:30:47 +00001436 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001437 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001438
1439 // We push them in the forward order so that they'll be popped in
1440 // the reverse order.
1441 for (CXXRecordDecl::base_class_const_iterator I =
1442 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001443 I != E; ++I) {
1444 const CXXBaseSpecifier &Base = *I;
1445 CXXRecordDecl *BaseClassDecl
1446 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1447
1448 // Ignore trivial destructors.
1449 if (BaseClassDecl->hasTrivialDestructor())
1450 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001451
John McCall1f0fca52010-07-21 07:22:38 +00001452 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1453 BaseClassDecl,
1454 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001455 }
John McCall50da2ca2010-07-21 05:30:47 +00001456
John McCall3b477332010-02-18 19:59:28 +00001457 return;
1458 }
1459
1460 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001461
1462 // Destroy non-virtual bases.
1463 for (CXXRecordDecl::base_class_const_iterator I =
1464 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1465 const CXXBaseSpecifier &Base = *I;
1466
1467 // Ignore virtual bases.
1468 if (Base.isVirtual())
1469 continue;
1470
1471 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1472
1473 // Ignore trivial destructors.
1474 if (BaseClassDecl->hasTrivialDestructor())
1475 continue;
John McCall3b477332010-02-18 19:59:28 +00001476
John McCall1f0fca52010-07-21 07:22:38 +00001477 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1478 BaseClassDecl,
1479 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001480 }
1481
1482 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001483 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001484 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1485 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001486 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001487 QualType type = field->getType();
1488 QualType::DestructionKind dtorKind = type.isDestructedType();
1489 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001490
Richard Smith9a561d52012-02-26 09:11:52 +00001491 // Anonymous union members do not have their destructors called.
1492 const RecordType *RT = type->getAsUnionType();
1493 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1494
John McCall9928c482011-07-12 16:41:08 +00001495 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1496 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1497 getDestroyer(dtorKind),
1498 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001499 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001500}
1501
John McCallc3c07662011-07-13 06:10:41 +00001502/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1503/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001504///
John McCallc3c07662011-07-13 06:10:41 +00001505/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001506/// \param arrayType the type of the array to initialize
1507/// \param arrayBegin an arrayType*
1508/// \param zeroInitialize true if each element should be
1509/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001510void
John McCallc3c07662011-07-13 06:10:41 +00001511CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1512 const ConstantArrayType *arrayType,
1513 llvm::Value *arrayBegin,
1514 CallExpr::const_arg_iterator argBegin,
1515 CallExpr::const_arg_iterator argEnd,
1516 bool zeroInitialize) {
1517 QualType elementType;
1518 llvm::Value *numElements =
1519 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001520
John McCallc3c07662011-07-13 06:10:41 +00001521 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1522 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001523}
1524
John McCallc3c07662011-07-13 06:10:41 +00001525/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1526/// constructor for each of several members of an array.
1527///
1528/// \param ctor the constructor to call for each element
1529/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001530/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001531/// \param arrayBegin a T*, where T is the type constructed by ctor
1532/// \param zeroInitialize true if each element should be
1533/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001534void
John McCallc3c07662011-07-13 06:10:41 +00001535CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1536 llvm::Value *numElements,
1537 llvm::Value *arrayBegin,
1538 CallExpr::const_arg_iterator argBegin,
1539 CallExpr::const_arg_iterator argEnd,
1540 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001541
1542 // It's legal for numElements to be zero. This can happen both
1543 // dynamically, because x can be zero in 'new A[x]', and statically,
1544 // because of GCC extensions that permit zero-length arrays. There
1545 // are probably legitimate places where we could assume that this
1546 // doesn't happen, but it's not clear that it's worth it.
1547 llvm::BranchInst *zeroCheckBranch = 0;
1548
1549 // Optimize for a constant count.
1550 llvm::ConstantInt *constantCount
1551 = dyn_cast<llvm::ConstantInt>(numElements);
1552 if (constantCount) {
1553 // Just skip out if the constant count is zero.
1554 if (constantCount->isZero()) return;
1555
1556 // Otherwise, emit the check.
1557 } else {
1558 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1559 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1560 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1561 EmitBlock(loopBB);
1562 }
1563
John McCallc3c07662011-07-13 06:10:41 +00001564 // Find the end of the array.
1565 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1566 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001567
John McCallc3c07662011-07-13 06:10:41 +00001568 // Enter the loop, setting up a phi for the current location to initialize.
1569 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1570 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1571 EmitBlock(loopBB);
1572 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1573 "arrayctor.cur");
1574 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001575
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001576 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001577
1578 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001579
Douglas Gregor59174c02010-07-21 01:10:17 +00001580 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001581 if (zeroInitialize)
1582 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001583
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001584 // C++ [class.temporary]p4:
1585 // There are two contexts in which temporaries are destroyed at a different
1586 // point than the end of the full-expression. The first context is when a
1587 // default constructor is called to initialize an element of an array.
1588 // If the constructor has one or more default arguments, the destruction of
1589 // every temporary created in a default argument expression is sequenced
1590 // before the construction of the next array element, if any.
1591
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001592 {
John McCallf1549f62010-07-06 01:34:17 +00001593 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001594
John McCallc3c07662011-07-13 06:10:41 +00001595 // Evaluate the constructor and its arguments in a regular
1596 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001597 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001598 !ctor->getParent()->hasTrivialDestructor()) {
1599 Destroyer *destroyer = destroyCXXObject;
1600 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1601 }
1602
1603 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001604 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001605 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001606
John McCallc3c07662011-07-13 06:10:41 +00001607 // Go to the next element.
1608 llvm::Value *next =
1609 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1610 "arrayctor.next");
1611 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001612
John McCallc3c07662011-07-13 06:10:41 +00001613 // Check whether that's the end of the loop.
1614 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1615 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1616 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001617
John McCalldd376ca2011-07-13 07:37:11 +00001618 // Patch the earlier check to skip over the loop.
1619 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1620
John McCallc3c07662011-07-13 06:10:41 +00001621 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001622}
1623
John McCallbdc4d802011-07-09 01:37:26 +00001624void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1625 llvm::Value *addr,
1626 QualType type) {
1627 const RecordType *rtype = type->castAs<RecordType>();
1628 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1629 const CXXDestructorDecl *dtor = record->getDestructor();
1630 assert(!dtor->isTrivial());
1631 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001632 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001633}
1634
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001635void
1636CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001637 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001638 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001639 llvm::Value *This,
1640 CallExpr::const_arg_iterator ArgBeg,
1641 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001642
1643 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001644 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001645 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001646 // If debug info for this class has not been emitted then this is the
1647 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001648 const CXXRecordDecl *Parent = D->getParent();
1649 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1650 Parent->getLocation());
1651 }
1652
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001653 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001654 if (D->isTrivial()) {
1655 if (ArgBeg == ArgEnd) {
1656 // Trivial default constructor, no codegen required.
1657 assert(D->isDefaultConstructor() &&
1658 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001659 return;
1660 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001661
1662 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001663 assert(D->isCopyOrMoveConstructor() &&
1664 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001665
John McCall8b6bbeb2010-02-06 00:25:16 +00001666 const Expr *E = (*ArgBeg);
1667 QualType Ty = E->getType();
1668 llvm::Value *Src = EmitLValue(E).getAddress();
1669 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001670 return;
1671 }
1672
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001673 // Non-trivial constructors are handled in an ABI-specific manner.
Manman Ren63fd4082013-03-20 16:59:38 +00001674 llvm::Value *Callee = CGM.getCXXABI().EmitConstructorCall(*this, D, Type,
1675 ForVirtualBase, Delegating, This, ArgBeg, ArgEnd);
1676 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1677 CGM.getCXXABI().HasThisReturn(GlobalDecl(D, Type)))
1678 CalleeWithThisReturn = Callee;
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001679}
1680
John McCallc0bf4622010-02-23 00:48:20 +00001681void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001682CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1683 llvm::Value *This, llvm::Value *Src,
1684 CallExpr::const_arg_iterator ArgBeg,
1685 CallExpr::const_arg_iterator ArgEnd) {
1686 if (D->isTrivial()) {
1687 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001688 assert(D->isCopyOrMoveConstructor() &&
1689 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001690 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1691 return;
1692 }
1693 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1694 clang::Ctor_Complete);
1695 assert(D->isInstance() &&
1696 "Trying to emit a member call expr on a static method!");
1697
1698 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1699
1700 CallArgList Args;
1701
1702 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001703 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001704
1705
1706 // Push the src ptr.
1707 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001708 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001709 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001710 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001711
1712 // Skip over first argument (Src).
1713 ++ArgBeg;
1714 CallExpr::const_arg_iterator Arg = ArgBeg;
1715 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1716 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1717 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001718 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001719 }
1720 // Either we've emitted all the call args, or we have a call to a
1721 // variadic function.
1722 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1723 "Extra arguments in non-variadic function!");
1724 // If we still have any arguments, emit them using the type of the argument.
1725 for (; Arg != ArgEnd; ++Arg) {
1726 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001727 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001728 }
1729
John McCall0f3d0972012-07-07 06:41:13 +00001730 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1731 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001732}
1733
1734void
John McCallc0bf4622010-02-23 00:48:20 +00001735CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1736 CXXCtorType CtorType,
1737 const FunctionArgList &Args) {
1738 CallArgList DelegateArgs;
1739
1740 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1741 assert(I != E && "no parameters to constructor");
1742
1743 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001744 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001745 ++I;
1746
1747 // vtt
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001748 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001749 /*ForVirtualBase=*/false,
1750 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001751 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001752 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001753
Anders Carlssonaf440352010-03-23 04:11:45 +00001754 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001755 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001756 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001757 ++I;
1758 }
1759 }
1760
1761 // Explicit arguments.
1762 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001763 const VarDecl *param = *I;
1764 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001765 }
1766
Manman Ren63fd4082013-03-20 16:59:38 +00001767 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCallde5d3c72012-02-17 03:33:10 +00001768 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren63fd4082013-03-20 16:59:38 +00001769 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1770 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1771 CGM.getCXXABI().HasThisReturn(GlobalDecl(Ctor, CtorType)))
1772 CalleeWithThisReturn = Callee;
John McCallc0bf4622010-02-23 00:48:20 +00001773}
1774
Sean Huntb76af9c2011-05-03 23:05:34 +00001775namespace {
1776 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1777 const CXXDestructorDecl *Dtor;
1778 llvm::Value *Addr;
1779 CXXDtorType Type;
1780
1781 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1782 CXXDtorType Type)
1783 : Dtor(D), Addr(Addr), Type(Type) {}
1784
John McCallad346f42011-07-12 20:27:29 +00001785 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001786 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001787 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001788 }
1789 };
1790}
1791
Sean Hunt059ce0d2011-05-01 07:04:31 +00001792void
1793CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1794 const FunctionArgList &Args) {
1795 assert(Ctor->isDelegatingConstructor());
1796
1797 llvm::Value *ThisPtr = LoadCXXThis();
1798
Eli Friedmanf3940782011-12-03 00:54:26 +00001799 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001800 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001801 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001802 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001803 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001804 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001805 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001806
1807 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001808
Sean Huntb76af9c2011-05-03 23:05:34 +00001809 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001810 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001811 CXXDtorType Type =
1812 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1813
1814 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1815 ClassDecl->getDestructor(),
1816 ThisPtr, Type);
1817 }
1818}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001819
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001820void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1821 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001822 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001823 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001824 llvm::Value *This) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001825 llvm::Value *VTT = GetVTTParameter(GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001826 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001827 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001828 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001829 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1830 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001831
1832 if (!Callee)
1833 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001834
Richard Smith4def70d2012-10-09 19:52:38 +00001835 // FIXME: Provide a source location here.
1836 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001837 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1838 0, 0);
Manman Ren63fd4082013-03-20 16:59:38 +00001839 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1840 CGM.getCXXABI().HasThisReturn(GlobalDecl(DD, Type)))
1841 CalleeWithThisReturn = Callee;
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001842}
1843
John McCall291ae942010-07-21 01:41:18 +00001844namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001845 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001846 const CXXDestructorDecl *Dtor;
1847 llvm::Value *Addr;
1848
1849 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1850 : Dtor(D), Addr(Addr) {}
1851
John McCallad346f42011-07-12 20:27:29 +00001852 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001853 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001854 /*ForVirtualBase=*/false,
1855 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001856 }
1857 };
1858}
1859
John McCall81407d42010-07-21 06:29:51 +00001860void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1861 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001862 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001863}
1864
John McCallf1549f62010-07-06 01:34:17 +00001865void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1866 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1867 if (!ClassDecl) return;
1868 if (ClassDecl->hasTrivialDestructor()) return;
1869
1870 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001871 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001872 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001873}
1874
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001875llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001876CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1877 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001878 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001879 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001880 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001881 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001882
1883 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001884 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1885 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001886 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001887 ConvertType(getContext().getPointerDiffType());
1888
1889 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1890 PtrDiffTy->getPointerTo());
1891
1892 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1893
1894 return VBaseOffset;
1895}
1896
Anders Carlssond103f9f2010-03-28 19:40:00 +00001897void
1898CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001899 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001900 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001901 llvm::Constant *VTable,
1902 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001903 const CXXRecordDecl *RD = Base.getBase();
1904
Anders Carlssond103f9f2010-03-28 19:40:00 +00001905 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001906 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001907
Anders Carlssonc83f1062010-03-29 01:08:49 +00001908 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001909 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001910 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001911 // Get the secondary vpointer index.
1912 uint64_t VirtualPointerIndex =
1913 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1914
1915 /// Load the VTT.
1916 llvm::Value *VTT = LoadCXXVTT();
1917 if (VirtualPointerIndex)
1918 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1919
1920 // And load the address point from the VTT.
1921 VTableAddressPoint = Builder.CreateLoad(VTT);
1922 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001923 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001924 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001925 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001926 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001927 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001928
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001929 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001930 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001931 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001932
1933 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1934 // We need to use the virtual base offset offset because the virtual base
1935 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001936 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1937 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001938 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001939 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001940 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001941 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001942 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001943
1944 // Apply the offsets.
1945 llvm::Value *VTableField = LoadCXXThis();
1946
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001947 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001948 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1949 NonVirtualOffset,
1950 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001951
Anders Carlssond103f9f2010-03-28 19:40:00 +00001952 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001953 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001954 VTableAddressPoint->getType()->getPointerTo();
1955 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001956 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1957 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001958}
1959
Anders Carlsson603d6d12010-03-28 21:07:49 +00001960void
1961CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001962 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001963 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001964 bool BaseIsNonVirtualPrimaryBase,
1965 llvm::Constant *VTable,
1966 const CXXRecordDecl *VTableClass,
1967 VisitedVirtualBasesSetTy& VBases) {
1968 // If this base is a non-virtual primary base the address point has already
1969 // been set.
1970 if (!BaseIsNonVirtualPrimaryBase) {
1971 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001972 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1973 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001974 }
1975
1976 const CXXRecordDecl *RD = Base.getBase();
1977
1978 // Traverse bases.
1979 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1980 E = RD->bases_end(); I != E; ++I) {
1981 CXXRecordDecl *BaseDecl
1982 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1983
1984 // Ignore classes without a vtable.
1985 if (!BaseDecl->isDynamicClass())
1986 continue;
1987
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001988 CharUnits BaseOffset;
1989 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001990 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001991
1992 if (I->isVirtual()) {
1993 // Check if we've visited this virtual base before.
1994 if (!VBases.insert(BaseDecl))
1995 continue;
1996
1997 const ASTRecordLayout &Layout =
1998 getContext().getASTRecordLayout(VTableClass);
1999
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002000 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2001 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00002002 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00002003 } else {
2004 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2005
Ken Dyck4230d522011-03-24 01:21:01 +00002006 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00002007 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002008 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00002009 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00002010 }
2011
Ken Dyck4230d522011-03-24 01:21:01 +00002012 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00002013 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00002014 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00002015 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00002016 VTable, VTableClass, VBases);
2017 }
2018}
2019
2020void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2021 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00002022 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002023 return;
2024
Anders Carlsson07036902010-03-26 04:39:42 +00002025 // Get the VTable.
2026 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00002027
Anders Carlsson603d6d12010-03-28 21:07:49 +00002028 // Initialize the vtable pointers for this class and all of its bases.
2029 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00002030 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2031 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002032 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00002033 /*BaseIsNonVirtualPrimaryBase=*/false,
2034 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002035}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002036
2037llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002038 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002039 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002040 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2041 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2042 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002043}
Anders Carlssona2447e02011-05-08 20:32:23 +00002044
2045static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
2046 const Expr *E = Base;
2047
2048 while (true) {
2049 E = E->IgnoreParens();
2050 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2051 if (CE->getCastKind() == CK_DerivedToBase ||
2052 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2053 CE->getCastKind() == CK_NoOp) {
2054 E = CE->getSubExpr();
2055 continue;
2056 }
2057 }
2058
2059 break;
2060 }
2061
2062 QualType DerivedType = E->getType();
2063 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
2064 DerivedType = PTy->getPointeeType();
2065
2066 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
2067}
2068
2069// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2070// quite what we want.
2071static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2072 while (true) {
2073 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2074 E = PE->getSubExpr();
2075 continue;
2076 }
2077
2078 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2079 if (CE->getCastKind() == CK_NoOp) {
2080 E = CE->getSubExpr();
2081 continue;
2082 }
2083 }
2084 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2085 if (UO->getOpcode() == UO_Extension) {
2086 E = UO->getSubExpr();
2087 continue;
2088 }
2089 }
2090 return E;
2091 }
2092}
2093
2094/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
2095/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00002096static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
2097 const CXXMethodDecl *MD) {
2098 // If the most derived class is marked final, we know that no subclass can
2099 // override this member function and so we can devirtualize it. For example:
2100 //
2101 // struct A { virtual void f(); }
2102 // struct B final : A { };
2103 //
2104 // void f(B *b) {
2105 // b->f();
2106 // }
2107 //
2108 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
2109 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2110 return true;
2111
2112 // If the member function is marked 'final', we know that it can't be
2113 // overridden and can therefore devirtualize it.
2114 if (MD->hasAttr<FinalAttr>())
2115 return true;
2116
2117 // Similarly, if the class itself is marked 'final' it can't be overridden
2118 // and we can therefore devirtualize the member function call.
2119 if (MD->getParent()->hasAttr<FinalAttr>())
2120 return true;
2121
2122 Base = skipNoOpCastsAndParens(Base);
2123 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2124 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2125 // This is a record decl. We know the type and can devirtualize it.
2126 return VD->getType()->isRecordType();
2127 }
2128
2129 return false;
2130 }
2131
2132 // We can always devirtualize calls on temporary object expressions.
2133 if (isa<CXXConstructExpr>(Base))
2134 return true;
2135
2136 // And calls on bound temporaries.
2137 if (isa<CXXBindTemporaryExpr>(Base))
2138 return true;
2139
2140 // Check if this is a call expr that returns a record type.
2141 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2142 return CE->getCallReturnType()->isRecordType();
2143
2144 // We can't devirtualize the call.
2145 return false;
2146}
2147
2148static bool UseVirtualCall(ASTContext &Context,
2149 const CXXOperatorCallExpr *CE,
2150 const CXXMethodDecl *MD) {
2151 if (!MD->isVirtual())
2152 return false;
2153
2154 // When building with -fapple-kext, all calls must go through the vtable since
2155 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00002156 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00002157 return true;
2158
2159 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
2160}
2161
2162llvm::Value *
2163CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2164 const CXXMethodDecl *MD,
2165 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002166 llvm::FunctionType *fnType =
2167 CGM.getTypes().GetFunctionType(
2168 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002169
2170 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00002171 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002172
John McCallde5d3c72012-02-17 03:33:10 +00002173 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002174}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002175
John McCall0f3d0972012-07-07 06:41:13 +00002176void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2177 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002178 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002179 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002180 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002181 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002182 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002183
Eli Friedman21f6ed92012-02-16 03:47:28 +00002184 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002185 const CGFunctionInfo &calleeFnInfo =
2186 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2187 llvm::Value *callee =
2188 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2189 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002190
John McCall0f3d0972012-07-07 06:41:13 +00002191 // Prepare the return slot.
2192 const FunctionProtoType *FPT =
2193 callOperator->getType()->castAs<FunctionProtoType>();
2194 QualType resultType = FPT->getResultType();
2195 ReturnValueSlot returnSlot;
2196 if (!resultType->isVoidType() &&
2197 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002198 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002199 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2200
2201 // We don't need to separately arrange the call arguments because
2202 // the call can't be variadic anyway --- it's impossible to forward
2203 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002204
2205 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002206 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2207 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002208
John McCall0f3d0972012-07-07 06:41:13 +00002209 // If necessary, copy the returned value into the slot.
2210 if (!resultType->isVoidType() && returnSlot.isNull())
2211 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002212 else
2213 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002214}
2215
Eli Friedman64bee652012-02-25 02:48:22 +00002216void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2217 const BlockDecl *BD = BlockInfo->getBlockDecl();
2218 const VarDecl *variable = BD->capture_begin()->getVariable();
2219 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2220
2221 // Start building arguments for forwarding call
2222 CallArgList CallArgs;
2223
2224 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2225 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2226 CallArgs.add(RValue::get(ThisPtr), ThisType);
2227
2228 // Add the rest of the parameters.
2229 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2230 E = BD->param_end(); I != E; ++I) {
2231 ParmVarDecl *param = *I;
2232 EmitDelegateCallArg(CallArgs, param);
2233 }
2234
2235 EmitForwardingCallToLambda(Lambda, CallArgs);
2236}
2237
2238void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCallf5ebf9b2013-05-03 07:33:41 +00002239 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman64bee652012-02-25 02:48:22 +00002240 // FIXME: Making this work correctly is nasty because it requires either
2241 // cloning the body of the call operator or making the call operator forward.
John McCallf5ebf9b2013-05-03 07:33:41 +00002242 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002243 return;
2244 }
2245
Eli Friedman64bee652012-02-25 02:48:22 +00002246 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002247}
2248
2249void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2250 const CXXRecordDecl *Lambda = MD->getParent();
2251
2252 // Start building arguments for forwarding call
2253 CallArgList CallArgs;
2254
2255 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2256 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2257 CallArgs.add(RValue::get(ThisPtr), ThisType);
2258
2259 // Add the rest of the parameters.
2260 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2261 E = MD->param_end(); I != E; ++I) {
2262 ParmVarDecl *param = *I;
2263 EmitDelegateCallArg(CallArgs, param);
2264 }
2265
2266 EmitForwardingCallToLambda(Lambda, CallArgs);
2267}
2268
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002269void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2270 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002271 // FIXME: Making this work correctly is nasty because it requires either
2272 // cloning the body of the call operator or making the call operator forward.
2273 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002274 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002275 }
2276
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002277 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002278}