blob: 2ececb03651ad3b47f15225bb3e2769aeadad6f8 [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
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000293 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurFuncDecl)->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 McCallb8b2c9d2013-01-25 22:30:49 +0000713 CGM.getContext().getTargetInfo().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) {
862 assert(F->getFieldIndex() == LastAddedFieldIndex + 1 &&
863 "Cannot aggregate non-contiguous fields.");
864 LastAddedFieldIndex = F->getFieldIndex();
865
866 // The 'first' and 'last' fields are chosen by offset, rather than field
867 // index. This allows the code to support bitfields, as well as regular
868 // fields.
869 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
870 if (FOffset < FirstFieldOffset) {
871 FirstField = F;
872 FirstFieldOffset = FOffset;
873 } else if (FOffset > LastFieldOffset) {
874 LastField = F;
875 LastFieldOffset = FOffset;
876 }
877 }
878
879 const VarDecl *SrcRec;
880 const ASTRecordLayout &RecLayout;
881 FieldDecl *FirstField;
882 FieldDecl *LastField;
883 uint64_t FirstFieldOffset, LastFieldOffset;
884 unsigned LastAddedFieldIndex;
885 };
886
887 class ConstructorMemcpyizer : public FieldMemcpyizer {
888 private:
889
890 /// Get source argument for copy constructor. Returns null if not a copy
891 /// constructor.
892 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
893 FunctionArgList &Args) {
894 if (CD->isCopyOrMoveConstructor() && CD->isImplicitlyDefined())
895 return Args[Args.size() - 1];
896 return 0;
897 }
898
899 // Returns true if a CXXCtorInitializer represents a member initialization
900 // that can be rolled into a memcpy.
901 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
902 if (!MemcpyableCtor)
903 return false;
904 FieldDecl *Field = MemberInit->getMember();
905 assert(Field != 0 && "No field for member init.");
906 QualType FieldType = Field->getType();
907 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
908
909 // Bail out on non-POD, not-trivially-constructable members.
910 if (!(CE && CE->getConstructor()->isTrivial()) &&
911 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
912 FieldType->isReferenceType()))
913 return false;
914
915 // Bail out on volatile fields.
916 if (!isMemcpyableField(Field))
917 return false;
918
919 // Otherwise we're good.
920 return true;
921 }
922
923 public:
924 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
925 FunctionArgList &Args)
926 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
927 ConstructorDecl(CD),
928 MemcpyableCtor(CD->isImplicitlyDefined() &&
929 CD->isCopyOrMoveConstructor() &&
930 CGF.getLangOpts().getGC() == LangOptions::NonGC),
931 Args(Args) { }
932
933 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
934 if (isMemberInitMemcpyable(MemberInit)) {
935 AggregatedInits.push_back(MemberInit);
936 addMemcpyableField(MemberInit->getMember());
937 } else {
938 emitAggregatedInits();
939 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
940 ConstructorDecl, Args);
941 }
942 }
943
944 void emitAggregatedInits() {
945 if (AggregatedInits.size() <= 1) {
946 // This memcpy is too small to be worthwhile. Fall back on default
947 // codegen.
948 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
949 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
950 AggregatedInits[i], ConstructorDecl, Args);
951 }
952 reset();
953 return;
954 }
955
956 pushEHDestructors();
957 emitMemcpy();
958 AggregatedInits.clear();
959 }
960
961 void pushEHDestructors() {
962 llvm::Value *ThisPtr = CGF.LoadCXXThis();
963 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
964 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
965
966 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
967 QualType FieldType = AggregatedInits[i]->getMember()->getType();
968 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
969 if (CGF.needsEHCleanup(dtorKind))
970 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
971 }
972 }
973
974 void finish() {
975 emitAggregatedInits();
976 }
977
978 private:
979 const CXXConstructorDecl *ConstructorDecl;
980 bool MemcpyableCtor;
981 FunctionArgList &Args;
982 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
983 };
984
985 class AssignmentMemcpyizer : public FieldMemcpyizer {
986 private:
987
988 // Returns the memcpyable field copied by the given statement, if one
989 // exists. Otherwise r
990 FieldDecl* getMemcpyableField(Stmt *S) {
991 if (!AssignmentsMemcpyable)
992 return 0;
993 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
994 // Recognise trivial assignments.
995 if (BO->getOpcode() != BO_Assign)
996 return 0;
997 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
998 if (!ME)
999 return 0;
1000 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1001 if (!Field || !isMemcpyableField(Field))
1002 return 0;
1003 Stmt *RHS = BO->getRHS();
1004 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1005 RHS = EC->getSubExpr();
1006 if (!RHS)
1007 return 0;
1008 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1009 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1010 return 0;
1011 return Field;
1012 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1013 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1014 if (!(MD && (MD->isCopyAssignmentOperator() ||
1015 MD->isMoveAssignmentOperator()) &&
1016 MD->isTrivial()))
1017 return 0;
1018 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1019 if (!IOA)
1020 return 0;
1021 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1022 if (!Field || !isMemcpyableField(Field))
1023 return 0;
1024 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1025 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1026 return 0;
1027 return Field;
1028 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1029 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1030 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1031 return 0;
1032 Expr *DstPtr = CE->getArg(0);
1033 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1034 DstPtr = DC->getSubExpr();
1035 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1036 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1037 return 0;
1038 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1039 if (!ME)
1040 return 0;
1041 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1042 if (!Field || !isMemcpyableField(Field))
1043 return 0;
1044 Expr *SrcPtr = CE->getArg(1);
1045 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1046 SrcPtr = SC->getSubExpr();
1047 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1048 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1049 return 0;
1050 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1051 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1052 return 0;
1053 return Field;
1054 }
1055
1056 return 0;
1057 }
1058
1059 bool AssignmentsMemcpyable;
1060 SmallVector<Stmt*, 16> AggregatedStmts;
1061
1062 public:
1063
1064 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1065 FunctionArgList &Args)
1066 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1067 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1068 assert(Args.size() == 2);
1069 }
1070
1071 void emitAssignment(Stmt *S) {
1072 FieldDecl *F = getMemcpyableField(S);
1073 if (F) {
1074 addMemcpyableField(F);
1075 AggregatedStmts.push_back(S);
1076 } else {
1077 emitAggregatedStmts();
1078 CGF.EmitStmt(S);
1079 }
1080 }
1081
1082 void emitAggregatedStmts() {
1083 if (AggregatedStmts.size() <= 1) {
1084 for (unsigned i = 0; i < AggregatedStmts.size(); ++i)
1085 CGF.EmitStmt(AggregatedStmts[i]);
1086 reset();
1087 }
1088
1089 emitMemcpy();
1090 AggregatedStmts.clear();
1091 }
1092
1093 void finish() {
1094 emitAggregatedStmts();
1095 }
1096 };
1097
1098}
1099
Anders Carlsson607d0372009-12-24 22:46:43 +00001100/// EmitCtorPrologue - This routine generates necessary code to initialize
1101/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001102void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001103 CXXCtorType CtorType,
1104 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001105 if (CD->isDelegatingConstructor())
1106 return EmitDelegatingCXXConstructorCall(CD, Args);
1107
Anders Carlsson607d0372009-12-24 22:46:43 +00001108 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001109
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001110 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1111 E = CD->init_end();
1112
1113 llvm::BasicBlock *BaseCtorContinueBB = 0;
1114 if (ClassDecl->getNumVBases() &&
1115 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1116 // The ABIs that don't have constructor variants need to put a branch
1117 // before the virtual base initialization code.
1118 BaseCtorContinueBB = CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this);
1119 assert(BaseCtorContinueBB);
1120 }
1121
1122 // Virtual base initializers first.
1123 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1124 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1125 }
1126
1127 if (BaseCtorContinueBB) {
1128 // Complete object handler should continue to the remaining initializers.
1129 Builder.CreateBr(BaseCtorContinueBB);
1130 EmitBlock(BaseCtorContinueBB);
1131 }
1132
1133 // Then, non-virtual base initializers.
1134 for (; B != E && (*B)->isBaseInitializer(); B++) {
1135 assert(!(*B)->isBaseVirtual());
1136 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001137 }
1138
Anders Carlsson603d6d12010-03-28 21:07:49 +00001139 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001140
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001141 // And finally, initialize class members.
Lang Hames56c00c42013-02-17 07:22:09 +00001142 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001143 for (; B != E; B++) {
1144 CXXCtorInitializer *Member = (*B);
1145 assert(!Member->isBaseInitializer());
1146 assert(Member->isAnyMemberInitializer() &&
1147 "Delegating initializer on non-delegating constructor");
1148 CM.addMemberInitializer(Member);
1149 }
Lang Hames56c00c42013-02-17 07:22:09 +00001150 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001151}
1152
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001153static bool
1154FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1155
1156static bool
1157HasTrivialDestructorBody(ASTContext &Context,
1158 const CXXRecordDecl *BaseClassDecl,
1159 const CXXRecordDecl *MostDerivedClassDecl)
1160{
1161 // If the destructor is trivial we don't have to check anything else.
1162 if (BaseClassDecl->hasTrivialDestructor())
1163 return true;
1164
1165 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1166 return false;
1167
1168 // Check fields.
1169 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1170 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001171 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001172
1173 if (!FieldHasTrivialDestructorBody(Context, Field))
1174 return false;
1175 }
1176
1177 // Check non-virtual bases.
1178 for (CXXRecordDecl::base_class_const_iterator I =
1179 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1180 I != E; ++I) {
1181 if (I->isVirtual())
1182 continue;
1183
1184 const CXXRecordDecl *NonVirtualBase =
1185 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1186 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1187 MostDerivedClassDecl))
1188 return false;
1189 }
1190
1191 if (BaseClassDecl == MostDerivedClassDecl) {
1192 // Check virtual bases.
1193 for (CXXRecordDecl::base_class_const_iterator I =
1194 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1195 I != E; ++I) {
1196 const CXXRecordDecl *VirtualBase =
1197 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1198 if (!HasTrivialDestructorBody(Context, VirtualBase,
1199 MostDerivedClassDecl))
1200 return false;
1201 }
1202 }
1203
1204 return true;
1205}
1206
1207static bool
1208FieldHasTrivialDestructorBody(ASTContext &Context,
1209 const FieldDecl *Field)
1210{
1211 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1212
1213 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1214 if (!RT)
1215 return true;
1216
1217 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1218 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1219}
1220
Anders Carlssonffb945f2011-05-14 23:26:09 +00001221/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1222/// any vtable pointers before calling this destructor.
1223static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001224 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001225 if (!Dtor->hasTrivialBody())
1226 return false;
1227
1228 // Check the fields.
1229 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1230 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1231 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001232 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001233
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001234 if (!FieldHasTrivialDestructorBody(Context, Field))
1235 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001236 }
1237
1238 return true;
1239}
1240
John McCall9fc6a772010-02-19 09:25:03 +00001241/// EmitDestructorBody - Emits the body of the current destructor.
1242void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1243 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1244 CXXDtorType DtorType = CurGD.getDtorType();
1245
John McCall50da2ca2010-07-21 05:30:47 +00001246 // The call to operator delete in a deleting destructor happens
1247 // outside of the function-try-block, which means it's always
1248 // possible to delegate the destructor body to the complete
1249 // destructor. Do so.
1250 if (DtorType == Dtor_Deleting) {
1251 EnterDtorCleanups(Dtor, Dtor_Deleting);
1252 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001253 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001254 PopCleanupBlock();
1255 return;
1256 }
1257
John McCall9fc6a772010-02-19 09:25:03 +00001258 Stmt *Body = Dtor->getBody();
1259
1260 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001261 // anything else.
1262 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001263 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001264 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001265
John McCall50da2ca2010-07-21 05:30:47 +00001266 // Enter the epilogue cleanups.
1267 RunCleanupsScope DtorEpilogue(*this);
1268
John McCall9fc6a772010-02-19 09:25:03 +00001269 // If this is the complete variant, just invoke the base variant;
1270 // the epilogue will destruct the virtual bases. But we can't do
1271 // this optimization if the body is a function-try-block, because
1272 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +00001273 switch (DtorType) {
1274 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1275
1276 case Dtor_Complete:
1277 // Enter the cleanup scopes for virtual bases.
1278 EnterDtorCleanups(Dtor, Dtor_Complete);
1279
John McCallb8b2c9d2013-01-25 22:30:49 +00001280 if (!isTryBody &&
1281 CGM.getContext().getTargetInfo().getCXXABI().hasDestructorVariants()) {
John McCall50da2ca2010-07-21 05:30:47 +00001282 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001283 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001284 break;
1285 }
1286 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001287
John McCall50da2ca2010-07-21 05:30:47 +00001288 case Dtor_Base:
1289 // Enter the cleanup scopes for fields and non-virtual bases.
1290 EnterDtorCleanups(Dtor, Dtor_Base);
1291
1292 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001293 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1294 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001295
1296 if (isTryBody)
1297 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1298 else if (Body)
1299 EmitStmt(Body);
1300 else {
1301 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1302 // nothing to do besides what's in the epilogue
1303 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001304 // -fapple-kext must inline any call to this dtor into
1305 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001306 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001307 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001308 break;
John McCall9fc6a772010-02-19 09:25:03 +00001309 }
1310
John McCall50da2ca2010-07-21 05:30:47 +00001311 // Jump out through the epilogue cleanups.
1312 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001313
1314 // Exit the try if applicable.
1315 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001316 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001317}
1318
Lang Hames56c00c42013-02-17 07:22:09 +00001319void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1320 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1321 const Stmt *RootS = AssignOp->getBody();
1322 assert(isa<CompoundStmt>(RootS) &&
1323 "Body of an implicit assignment operator should be compound stmt.");
1324 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1325
1326 LexicalScope Scope(*this, RootCS->getSourceRange());
1327
1328 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1329 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1330 E = RootCS->body_end();
1331 I != E; ++I) {
1332 AM.emitAssignment(*I);
1333 }
1334 AM.finish();
1335}
1336
John McCall50da2ca2010-07-21 05:30:47 +00001337namespace {
1338 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001339 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001340 CallDtorDelete() {}
1341
John McCallad346f42011-07-12 20:27:29 +00001342 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001343 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1344 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1345 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1346 CGF.getContext().getTagDeclType(ClassDecl));
1347 }
1348 };
1349
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001350 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1351 llvm::Value *ShouldDeleteCondition;
1352 public:
1353 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1354 : ShouldDeleteCondition(ShouldDeleteCondition) {
1355 assert(ShouldDeleteCondition != NULL);
1356 }
1357
1358 void Emit(CodeGenFunction &CGF, Flags flags) {
1359 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1360 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1361 llvm::Value *ShouldCallDelete
1362 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1363 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1364
1365 CGF.EmitBlock(callDeleteBB);
1366 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1367 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1368 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1369 CGF.getContext().getTagDeclType(ClassDecl));
1370 CGF.Builder.CreateBr(continueBB);
1371
1372 CGF.EmitBlock(continueBB);
1373 }
1374 };
1375
John McCall9928c482011-07-12 16:41:08 +00001376 class DestroyField : public EHScopeStack::Cleanup {
1377 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001378 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001379 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001380
John McCall9928c482011-07-12 16:41:08 +00001381 public:
1382 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1383 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001384 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001385 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001386
John McCallad346f42011-07-12 20:27:29 +00001387 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001388 // Find the address of the field.
1389 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001390 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1391 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1392 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001393 assert(LV.isSimple());
1394
1395 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001396 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001397 }
1398 };
1399}
1400
Anders Carlsson607d0372009-12-24 22:46:43 +00001401/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1402/// destructor. This is to call destructors on members and base classes
1403/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001404void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1405 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001406 assert(!DD->isTrivial() &&
1407 "Should not emit dtor epilogue for trivial dtor!");
1408
John McCall50da2ca2010-07-21 05:30:47 +00001409 // The deleting-destructor phase just needs to call the appropriate
1410 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001411 if (DtorType == Dtor_Deleting) {
1412 assert(DD->getOperatorDelete() &&
1413 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001414 if (CXXStructorImplicitParamValue) {
1415 // If there is an implicit param to the deleting dtor, it's a boolean
1416 // telling whether we should call delete at the end of the dtor.
1417 EHStack.pushCleanup<CallDtorDeleteConditional>(
1418 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1419 } else {
1420 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1421 }
John McCall3b477332010-02-18 19:59:28 +00001422 return;
1423 }
1424
John McCall50da2ca2010-07-21 05:30:47 +00001425 const CXXRecordDecl *ClassDecl = DD->getParent();
1426
Richard Smith416f63e2011-09-18 12:11:43 +00001427 // Unions have no bases and do not call field destructors.
1428 if (ClassDecl->isUnion())
1429 return;
1430
John McCall50da2ca2010-07-21 05:30:47 +00001431 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001432 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001433
1434 // We push them in the forward order so that they'll be popped in
1435 // the reverse order.
1436 for (CXXRecordDecl::base_class_const_iterator I =
1437 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001438 I != E; ++I) {
1439 const CXXBaseSpecifier &Base = *I;
1440 CXXRecordDecl *BaseClassDecl
1441 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1442
1443 // Ignore trivial destructors.
1444 if (BaseClassDecl->hasTrivialDestructor())
1445 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001446
John McCall1f0fca52010-07-21 07:22:38 +00001447 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1448 BaseClassDecl,
1449 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001450 }
John McCall50da2ca2010-07-21 05:30:47 +00001451
John McCall3b477332010-02-18 19:59:28 +00001452 return;
1453 }
1454
1455 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001456
1457 // Destroy non-virtual bases.
1458 for (CXXRecordDecl::base_class_const_iterator I =
1459 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1460 const CXXBaseSpecifier &Base = *I;
1461
1462 // Ignore virtual bases.
1463 if (Base.isVirtual())
1464 continue;
1465
1466 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1467
1468 // Ignore trivial destructors.
1469 if (BaseClassDecl->hasTrivialDestructor())
1470 continue;
John McCall3b477332010-02-18 19:59:28 +00001471
John McCall1f0fca52010-07-21 07:22:38 +00001472 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1473 BaseClassDecl,
1474 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001475 }
1476
1477 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001478 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001479 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1480 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001481 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001482 QualType type = field->getType();
1483 QualType::DestructionKind dtorKind = type.isDestructedType();
1484 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001485
Richard Smith9a561d52012-02-26 09:11:52 +00001486 // Anonymous union members do not have their destructors called.
1487 const RecordType *RT = type->getAsUnionType();
1488 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1489
John McCall9928c482011-07-12 16:41:08 +00001490 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1491 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1492 getDestroyer(dtorKind),
1493 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001494 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001495}
1496
John McCallc3c07662011-07-13 06:10:41 +00001497/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1498/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001499///
John McCallc3c07662011-07-13 06:10:41 +00001500/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001501/// \param arrayType the type of the array to initialize
1502/// \param arrayBegin an arrayType*
1503/// \param zeroInitialize true if each element should be
1504/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001505void
John McCallc3c07662011-07-13 06:10:41 +00001506CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1507 const ConstantArrayType *arrayType,
1508 llvm::Value *arrayBegin,
1509 CallExpr::const_arg_iterator argBegin,
1510 CallExpr::const_arg_iterator argEnd,
1511 bool zeroInitialize) {
1512 QualType elementType;
1513 llvm::Value *numElements =
1514 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001515
John McCallc3c07662011-07-13 06:10:41 +00001516 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1517 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001518}
1519
John McCallc3c07662011-07-13 06:10:41 +00001520/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1521/// constructor for each of several members of an array.
1522///
1523/// \param ctor the constructor to call for each element
1524/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001525/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001526/// \param arrayBegin a T*, where T is the type constructed by ctor
1527/// \param zeroInitialize true if each element should be
1528/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001529void
John McCallc3c07662011-07-13 06:10:41 +00001530CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1531 llvm::Value *numElements,
1532 llvm::Value *arrayBegin,
1533 CallExpr::const_arg_iterator argBegin,
1534 CallExpr::const_arg_iterator argEnd,
1535 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001536
1537 // It's legal for numElements to be zero. This can happen both
1538 // dynamically, because x can be zero in 'new A[x]', and statically,
1539 // because of GCC extensions that permit zero-length arrays. There
1540 // are probably legitimate places where we could assume that this
1541 // doesn't happen, but it's not clear that it's worth it.
1542 llvm::BranchInst *zeroCheckBranch = 0;
1543
1544 // Optimize for a constant count.
1545 llvm::ConstantInt *constantCount
1546 = dyn_cast<llvm::ConstantInt>(numElements);
1547 if (constantCount) {
1548 // Just skip out if the constant count is zero.
1549 if (constantCount->isZero()) return;
1550
1551 // Otherwise, emit the check.
1552 } else {
1553 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1554 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1555 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1556 EmitBlock(loopBB);
1557 }
1558
John McCallc3c07662011-07-13 06:10:41 +00001559 // Find the end of the array.
1560 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1561 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001562
John McCallc3c07662011-07-13 06:10:41 +00001563 // Enter the loop, setting up a phi for the current location to initialize.
1564 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1565 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1566 EmitBlock(loopBB);
1567 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1568 "arrayctor.cur");
1569 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001570
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001571 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001572
1573 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001574
Douglas Gregor59174c02010-07-21 01:10:17 +00001575 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001576 if (zeroInitialize)
1577 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001578
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001579 // C++ [class.temporary]p4:
1580 // There are two contexts in which temporaries are destroyed at a different
1581 // point than the end of the full-expression. The first context is when a
1582 // default constructor is called to initialize an element of an array.
1583 // If the constructor has one or more default arguments, the destruction of
1584 // every temporary created in a default argument expression is sequenced
1585 // before the construction of the next array element, if any.
1586
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001587 {
John McCallf1549f62010-07-06 01:34:17 +00001588 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001589
John McCallc3c07662011-07-13 06:10:41 +00001590 // Evaluate the constructor and its arguments in a regular
1591 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001592 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001593 !ctor->getParent()->hasTrivialDestructor()) {
1594 Destroyer *destroyer = destroyCXXObject;
1595 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1596 }
1597
1598 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001599 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001600 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001601
John McCallc3c07662011-07-13 06:10:41 +00001602 // Go to the next element.
1603 llvm::Value *next =
1604 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1605 "arrayctor.next");
1606 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001607
John McCallc3c07662011-07-13 06:10:41 +00001608 // Check whether that's the end of the loop.
1609 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1610 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1611 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001612
John McCalldd376ca2011-07-13 07:37:11 +00001613 // Patch the earlier check to skip over the loop.
1614 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1615
John McCallc3c07662011-07-13 06:10:41 +00001616 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001617}
1618
John McCallbdc4d802011-07-09 01:37:26 +00001619void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1620 llvm::Value *addr,
1621 QualType type) {
1622 const RecordType *rtype = type->castAs<RecordType>();
1623 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1624 const CXXDestructorDecl *dtor = record->getDestructor();
1625 assert(!dtor->isTrivial());
1626 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001627 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001628}
1629
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001630void
1631CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001632 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001633 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001634 llvm::Value *This,
1635 CallExpr::const_arg_iterator ArgBeg,
1636 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001637
1638 CGDebugInfo *DI = getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +00001639 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +00001640 CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::LimitedDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001641 // If debug info for this class has not been emitted then this is the
1642 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001643 const CXXRecordDecl *Parent = D->getParent();
1644 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1645 Parent->getLocation());
1646 }
1647
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001648 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001649 if (D->isTrivial()) {
1650 if (ArgBeg == ArgEnd) {
1651 // Trivial default constructor, no codegen required.
1652 assert(D->isDefaultConstructor() &&
1653 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001654 return;
1655 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001656
1657 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001658 assert(D->isCopyOrMoveConstructor() &&
1659 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001660
John McCall8b6bbeb2010-02-06 00:25:16 +00001661 const Expr *E = (*ArgBeg);
1662 QualType Ty = E->getType();
1663 llvm::Value *Src = EmitLValue(E).getAddress();
1664 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001665 return;
1666 }
1667
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001668 // Non-trivial constructors are handled in an ABI-specific manner.
Manman Ren2710ed82013-03-16 00:11:09 +00001669 llvm::Value *Callee = CGM.getCXXABI().EmitConstructorCall(*this, D, Type,
1670 ForVirtualBase, Delegating, This, ArgBeg, ArgEnd);
1671 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1672 CGM.getCXXABI().HasThisReturn(GlobalDecl(D, Type)))
1673 CalleeWithThisReturn = Callee;
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001674}
1675
John McCallc0bf4622010-02-23 00:48:20 +00001676void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001677CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1678 llvm::Value *This, llvm::Value *Src,
1679 CallExpr::const_arg_iterator ArgBeg,
1680 CallExpr::const_arg_iterator ArgEnd) {
1681 if (D->isTrivial()) {
1682 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001683 assert(D->isCopyOrMoveConstructor() &&
1684 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001685 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1686 return;
1687 }
1688 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1689 clang::Ctor_Complete);
1690 assert(D->isInstance() &&
1691 "Trying to emit a member call expr on a static method!");
1692
1693 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1694
1695 CallArgList Args;
1696
1697 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001698 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001699
1700
1701 // Push the src ptr.
1702 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001703 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001704 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001705 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001706
1707 // Skip over first argument (Src).
1708 ++ArgBeg;
1709 CallExpr::const_arg_iterator Arg = ArgBeg;
1710 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1711 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1712 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001713 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001714 }
1715 // Either we've emitted all the call args, or we have a call to a
1716 // variadic function.
1717 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1718 "Extra arguments in non-variadic function!");
1719 // If we still have any arguments, emit them using the type of the argument.
1720 for (; Arg != ArgEnd; ++Arg) {
1721 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001722 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001723 }
1724
John McCall0f3d0972012-07-07 06:41:13 +00001725 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1726 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001727}
1728
1729void
John McCallc0bf4622010-02-23 00:48:20 +00001730CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1731 CXXCtorType CtorType,
1732 const FunctionArgList &Args) {
1733 CallArgList DelegateArgs;
1734
1735 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1736 assert(I != E && "no parameters to constructor");
1737
1738 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001739 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001740 ++I;
1741
1742 // vtt
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001743 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001744 /*ForVirtualBase=*/false,
1745 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001746 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001747 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001748
Anders Carlssonaf440352010-03-23 04:11:45 +00001749 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001750 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001751 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001752 ++I;
1753 }
1754 }
1755
1756 // Explicit arguments.
1757 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001758 const VarDecl *param = *I;
1759 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001760 }
1761
Manman Ren2710ed82013-03-16 00:11:09 +00001762 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCallde5d3c72012-02-17 03:33:10 +00001763 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren2710ed82013-03-16 00:11:09 +00001764 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
1765 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1766 CGM.getCXXABI().HasThisReturn(GlobalDecl(Ctor, CtorType)))
1767 CalleeWithThisReturn = Callee;
John McCallc0bf4622010-02-23 00:48:20 +00001768}
1769
Sean Huntb76af9c2011-05-03 23:05:34 +00001770namespace {
1771 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1772 const CXXDestructorDecl *Dtor;
1773 llvm::Value *Addr;
1774 CXXDtorType Type;
1775
1776 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1777 CXXDtorType Type)
1778 : Dtor(D), Addr(Addr), Type(Type) {}
1779
John McCallad346f42011-07-12 20:27:29 +00001780 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001781 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001782 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001783 }
1784 };
1785}
1786
Sean Hunt059ce0d2011-05-01 07:04:31 +00001787void
1788CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1789 const FunctionArgList &Args) {
1790 assert(Ctor->isDelegatingConstructor());
1791
1792 llvm::Value *ThisPtr = LoadCXXThis();
1793
Eli Friedmanf3940782011-12-03 00:54:26 +00001794 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001795 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001796 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001797 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001798 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001799 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001800 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001801
1802 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001803
Sean Huntb76af9c2011-05-03 23:05:34 +00001804 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001805 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001806 CXXDtorType Type =
1807 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1808
1809 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1810 ClassDecl->getDestructor(),
1811 ThisPtr, Type);
1812 }
1813}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001814
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001815void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1816 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001817 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001818 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001819 llvm::Value *This) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001820 llvm::Value *VTT = GetVTTParameter(GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001821 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001822 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001823 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001824 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1825 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001826
1827 if (!Callee)
1828 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001829
Richard Smith4def70d2012-10-09 19:52:38 +00001830 // FIXME: Provide a source location here.
1831 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001832 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1833 0, 0);
Manman Ren2710ed82013-03-16 00:11:09 +00001834 if (CGM.getCXXABI().HasThisReturn(CurGD) &&
1835 CGM.getCXXABI().HasThisReturn(GlobalDecl(DD, Type)))
1836 CalleeWithThisReturn = Callee;
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001837}
1838
John McCall291ae942010-07-21 01:41:18 +00001839namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001840 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001841 const CXXDestructorDecl *Dtor;
1842 llvm::Value *Addr;
1843
1844 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1845 : Dtor(D), Addr(Addr) {}
1846
John McCallad346f42011-07-12 20:27:29 +00001847 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001848 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001849 /*ForVirtualBase=*/false,
1850 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001851 }
1852 };
1853}
1854
John McCall81407d42010-07-21 06:29:51 +00001855void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1856 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001857 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001858}
1859
John McCallf1549f62010-07-06 01:34:17 +00001860void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1861 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1862 if (!ClassDecl) return;
1863 if (ClassDecl->hasTrivialDestructor()) return;
1864
1865 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001866 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001867 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001868}
1869
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001870llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001871CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1872 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001873 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001874 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001875 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001876 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001877
1878 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001879 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1880 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001881 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001882 ConvertType(getContext().getPointerDiffType());
1883
1884 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1885 PtrDiffTy->getPointerTo());
1886
1887 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1888
1889 return VBaseOffset;
1890}
1891
Anders Carlssond103f9f2010-03-28 19:40:00 +00001892void
1893CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001894 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001895 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001896 llvm::Constant *VTable,
1897 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001898 const CXXRecordDecl *RD = Base.getBase();
1899
Anders Carlssond103f9f2010-03-28 19:40:00 +00001900 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001901 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001902
Anders Carlssonc83f1062010-03-29 01:08:49 +00001903 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001904 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001905 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001906 // Get the secondary vpointer index.
1907 uint64_t VirtualPointerIndex =
1908 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1909
1910 /// Load the VTT.
1911 llvm::Value *VTT = LoadCXXVTT();
1912 if (VirtualPointerIndex)
1913 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1914
1915 // And load the address point from the VTT.
1916 VTableAddressPoint = Builder.CreateLoad(VTT);
1917 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001918 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001919 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001920 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001921 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001922 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001923
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001924 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001925 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001926 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001927
1928 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1929 // We need to use the virtual base offset offset because the virtual base
1930 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001931 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1932 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001933 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001934 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001935 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001936 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001937 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001938
1939 // Apply the offsets.
1940 llvm::Value *VTableField = LoadCXXThis();
1941
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001942 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001943 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1944 NonVirtualOffset,
1945 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001946
Anders Carlssond103f9f2010-03-28 19:40:00 +00001947 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001948 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001949 VTableAddressPoint->getType()->getPointerTo();
1950 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001951 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1952 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001953}
1954
Anders Carlsson603d6d12010-03-28 21:07:49 +00001955void
1956CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001957 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001958 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001959 bool BaseIsNonVirtualPrimaryBase,
1960 llvm::Constant *VTable,
1961 const CXXRecordDecl *VTableClass,
1962 VisitedVirtualBasesSetTy& VBases) {
1963 // If this base is a non-virtual primary base the address point has already
1964 // been set.
1965 if (!BaseIsNonVirtualPrimaryBase) {
1966 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001967 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1968 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001969 }
1970
1971 const CXXRecordDecl *RD = Base.getBase();
1972
1973 // Traverse bases.
1974 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1975 E = RD->bases_end(); I != E; ++I) {
1976 CXXRecordDecl *BaseDecl
1977 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1978
1979 // Ignore classes without a vtable.
1980 if (!BaseDecl->isDynamicClass())
1981 continue;
1982
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001983 CharUnits BaseOffset;
1984 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001985 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001986
1987 if (I->isVirtual()) {
1988 // Check if we've visited this virtual base before.
1989 if (!VBases.insert(BaseDecl))
1990 continue;
1991
1992 const ASTRecordLayout &Layout =
1993 getContext().getASTRecordLayout(VTableClass);
1994
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001995 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1996 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001997 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001998 } else {
1999 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2000
Ken Dyck4230d522011-03-24 01:21:01 +00002001 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00002002 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002003 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00002004 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00002005 }
2006
Ken Dyck4230d522011-03-24 01:21:01 +00002007 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00002008 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00002009 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00002010 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00002011 VTable, VTableClass, VBases);
2012 }
2013}
2014
2015void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2016 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00002017 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002018 return;
2019
Anders Carlsson07036902010-03-26 04:39:42 +00002020 // Get the VTable.
2021 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00002022
Anders Carlsson603d6d12010-03-28 21:07:49 +00002023 // Initialize the vtable pointers for this class and all of its bases.
2024 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00002025 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2026 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002027 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00002028 /*BaseIsNonVirtualPrimaryBase=*/false,
2029 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002030}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002031
2032llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002033 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002034 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002035 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2036 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2037 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002038}
Anders Carlssona2447e02011-05-08 20:32:23 +00002039
2040static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
2041 const Expr *E = Base;
2042
2043 while (true) {
2044 E = E->IgnoreParens();
2045 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2046 if (CE->getCastKind() == CK_DerivedToBase ||
2047 CE->getCastKind() == CK_UncheckedDerivedToBase ||
2048 CE->getCastKind() == CK_NoOp) {
2049 E = CE->getSubExpr();
2050 continue;
2051 }
2052 }
2053
2054 break;
2055 }
2056
2057 QualType DerivedType = E->getType();
2058 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
2059 DerivedType = PTy->getPointeeType();
2060
2061 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
2062}
2063
2064// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2065// quite what we want.
2066static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2067 while (true) {
2068 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2069 E = PE->getSubExpr();
2070 continue;
2071 }
2072
2073 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2074 if (CE->getCastKind() == CK_NoOp) {
2075 E = CE->getSubExpr();
2076 continue;
2077 }
2078 }
2079 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2080 if (UO->getOpcode() == UO_Extension) {
2081 E = UO->getSubExpr();
2082 continue;
2083 }
2084 }
2085 return E;
2086 }
2087}
2088
2089/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
2090/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00002091static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
2092 const CXXMethodDecl *MD) {
2093 // If the most derived class is marked final, we know that no subclass can
2094 // override this member function and so we can devirtualize it. For example:
2095 //
2096 // struct A { virtual void f(); }
2097 // struct B final : A { };
2098 //
2099 // void f(B *b) {
2100 // b->f();
2101 // }
2102 //
2103 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
2104 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2105 return true;
2106
2107 // If the member function is marked 'final', we know that it can't be
2108 // overridden and can therefore devirtualize it.
2109 if (MD->hasAttr<FinalAttr>())
2110 return true;
2111
2112 // Similarly, if the class itself is marked 'final' it can't be overridden
2113 // and we can therefore devirtualize the member function call.
2114 if (MD->getParent()->hasAttr<FinalAttr>())
2115 return true;
2116
2117 Base = skipNoOpCastsAndParens(Base);
2118 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2119 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2120 // This is a record decl. We know the type and can devirtualize it.
2121 return VD->getType()->isRecordType();
2122 }
2123
2124 return false;
2125 }
2126
2127 // We can always devirtualize calls on temporary object expressions.
2128 if (isa<CXXConstructExpr>(Base))
2129 return true;
2130
2131 // And calls on bound temporaries.
2132 if (isa<CXXBindTemporaryExpr>(Base))
2133 return true;
2134
2135 // Check if this is a call expr that returns a record type.
2136 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2137 return CE->getCallReturnType()->isRecordType();
2138
2139 // We can't devirtualize the call.
2140 return false;
2141}
2142
2143static bool UseVirtualCall(ASTContext &Context,
2144 const CXXOperatorCallExpr *CE,
2145 const CXXMethodDecl *MD) {
2146 if (!MD->isVirtual())
2147 return false;
2148
2149 // When building with -fapple-kext, all calls must go through the vtable since
2150 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00002151 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00002152 return true;
2153
2154 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
2155}
2156
2157llvm::Value *
2158CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2159 const CXXMethodDecl *MD,
2160 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002161 llvm::FunctionType *fnType =
2162 CGM.getTypes().GetFunctionType(
2163 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002164
2165 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00002166 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002167
John McCallde5d3c72012-02-17 03:33:10 +00002168 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002169}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002170
John McCall0f3d0972012-07-07 06:41:13 +00002171void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2172 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002173 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002174 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002175 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002176 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002177 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002178
Eli Friedman21f6ed92012-02-16 03:47:28 +00002179 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002180 const CGFunctionInfo &calleeFnInfo =
2181 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2182 llvm::Value *callee =
2183 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2184 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002185
John McCall0f3d0972012-07-07 06:41:13 +00002186 // Prepare the return slot.
2187 const FunctionProtoType *FPT =
2188 callOperator->getType()->castAs<FunctionProtoType>();
2189 QualType resultType = FPT->getResultType();
2190 ReturnValueSlot returnSlot;
2191 if (!resultType->isVoidType() &&
2192 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002193 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002194 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2195
2196 // We don't need to separately arrange the call arguments because
2197 // the call can't be variadic anyway --- it's impossible to forward
2198 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002199
2200 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002201 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2202 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002203
John McCall0f3d0972012-07-07 06:41:13 +00002204 // If necessary, copy the returned value into the slot.
2205 if (!resultType->isVoidType() && returnSlot.isNull())
2206 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002207 else
2208 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002209}
2210
Eli Friedman64bee652012-02-25 02:48:22 +00002211void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2212 const BlockDecl *BD = BlockInfo->getBlockDecl();
2213 const VarDecl *variable = BD->capture_begin()->getVariable();
2214 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2215
2216 // Start building arguments for forwarding call
2217 CallArgList CallArgs;
2218
2219 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2220 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2221 CallArgs.add(RValue::get(ThisPtr), ThisType);
2222
2223 // Add the rest of the parameters.
2224 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2225 E = BD->param_end(); I != E; ++I) {
2226 ParmVarDecl *param = *I;
2227 EmitDelegateCallArg(CallArgs, param);
2228 }
2229
2230 EmitForwardingCallToLambda(Lambda, CallArgs);
2231}
2232
2233void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
2234 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
2235 // FIXME: Making this work correctly is nasty because it requires either
2236 // cloning the body of the call operator or making the call operator forward.
2237 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
2238 return;
2239 }
2240
Eli Friedman64bee652012-02-25 02:48:22 +00002241 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002242}
2243
2244void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2245 const CXXRecordDecl *Lambda = MD->getParent();
2246
2247 // Start building arguments for forwarding call
2248 CallArgList CallArgs;
2249
2250 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2251 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2252 CallArgs.add(RValue::get(ThisPtr), ThisType);
2253
2254 // Add the rest of the parameters.
2255 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2256 E = MD->param_end(); I != E; ++I) {
2257 ParmVarDecl *param = *I;
2258 EmitDelegateCallArg(CallArgs, param);
2259 }
2260
2261 EmitForwardingCallToLambda(Lambda, CallArgs);
2262}
2263
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002264void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2265 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002266 // FIXME: Making this work correctly is nasty because it requires either
2267 // cloning the body of the call operator or making the call operator forward.
2268 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002269 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002270 }
2271
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002272 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002273}