blob: 392fe85f64f2376e2ba207aa47749d2617048f7e [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) {
Reid Klecknerb0f533e2013-05-29 18:02:47 +0000201 VirtualOffset =
202 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000203 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000204
John McCall7916c992012-08-01 05:04:58 +0000205 // Apply both offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000206 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000207 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000208 VirtualOffset);
209
John McCall7916c992012-08-01 05:04:58 +0000210 // Cast to the destination type.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000211 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall7916c992012-08-01 05:04:58 +0000212
213 // Build a phi if we needed a null check.
Anders Carlsson34a2d382010-04-24 21:06:20 +0000214 if (NullCheckValue) {
John McCall7916c992012-08-01 05:04:58 +0000215 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
216 Builder.CreateBr(endBB);
217 EmitBlock(endBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000218
John McCall7916c992012-08-01 05:04:58 +0000219 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
220 PHI->addIncoming(Value, notNullBB);
221 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000222 Value = PHI;
223 }
224
225 return Value;
226}
227
228llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000229CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000230 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000231 CastExpr::path_const_iterator PathBegin,
232 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000233 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000234 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000235
Anders Carlssona3697c92009-11-23 17:57:54 +0000236 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000237 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000238 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smithc7648302013-02-13 21:18:23 +0000239
Anders Carlssona552ea72010-01-31 01:43:37 +0000240 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000241 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000242
243 if (!NonVirtualOffset) {
244 // No offset, we can just cast back.
245 return Builder.CreateBitCast(Value, DerivedPtrTy);
246 }
247
Anders Carlssona3697c92009-11-23 17:57:54 +0000248 llvm::BasicBlock *CastNull = 0;
249 llvm::BasicBlock *CastNotNull = 0;
250 llvm::BasicBlock *CastEnd = 0;
251
252 if (NullCheckValue) {
253 CastNull = createBasicBlock("cast.null");
254 CastNotNull = createBasicBlock("cast.notnull");
255 CastEnd = createBasicBlock("cast.end");
256
Anders Carlssonb9241242011-04-11 00:30:07 +0000257 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000258 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
259 EmitBlock(CastNotNull);
260 }
261
Anders Carlssona552ea72010-01-31 01:43:37 +0000262 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000263 Value = Builder.CreateBitCast(Value, Int8PtrTy);
264 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
265 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000266
267 // Just cast.
268 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000269
270 if (NullCheckValue) {
271 Builder.CreateBr(CastEnd);
272 EmitBlock(CastNull);
273 Builder.CreateBr(CastEnd);
274 EmitBlock(CastEnd);
275
Jay Foadbbf3bac2011-03-30 11:28:58 +0000276 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000277 PHI->addIncoming(Value, CastNotNull);
278 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
279 CastNull);
280 Value = PHI;
281 }
282
283 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000284}
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000285
286llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
287 bool ForVirtualBase,
288 bool Delegating) {
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000289 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000290 // This constructor/destructor does not need a VTT parameter.
291 return 0;
292 }
293
John McCallf5ebf9b2013-05-03 07:33:41 +0000294 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssonc997d422010-01-02 01:01:18 +0000295 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000296
Anders Carlssonc997d422010-01-02 01:01:18 +0000297 llvm::Value *VTT;
298
John McCall3b477332010-02-18 19:59:28 +0000299 uint64_t SubVTTIndex;
300
Douglas Gregor378e1e72013-01-31 05:50:40 +0000301 if (Delegating) {
302 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000303 return LoadCXXVTT();
Douglas Gregor378e1e72013-01-31 05:50:40 +0000304 } else if (RD == Base) {
305 // If the record matches the base, this is the complete ctor/dtor
306 // variant calling the base variant in a class with virtual bases.
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000307 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000308 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000309 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000310 SubVTTIndex = 0;
311 } else {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000312 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000313 CharUnits BaseOffset = ForVirtualBase ?
314 Layout.getVBaseClassOffset(Base) :
315 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000316
317 SubVTTIndex =
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000318 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000319 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
320 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000321
Peter Collingbournee1e35f72013-06-28 20:45:28 +0000322 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000323 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000324 VTT = LoadCXXVTT();
325 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000326 } else {
327 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +0000328 VTT = CGM.getVTables().GetAddrOfVTT(RD);
329 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssonc997d422010-01-02 01:01:18 +0000330 }
331
332 return VTT;
333}
334
John McCall182ab512010-07-21 01:23:41 +0000335namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000336 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000337 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000338 const CXXRecordDecl *BaseClass;
339 bool BaseIsVirtual;
340 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
341 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000342
John McCallad346f42011-07-12 20:27:29 +0000343 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000344 const CXXRecordDecl *DerivedClass =
345 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
346
347 const CXXDestructorDecl *D = BaseClass->getDestructor();
348 llvm::Value *Addr =
349 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
350 DerivedClass, BaseClass,
351 BaseIsVirtual);
Douglas Gregor378e1e72013-01-31 05:50:40 +0000352 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
353 /*Delegating=*/false, Addr);
John McCall182ab512010-07-21 01:23:41 +0000354 }
355 };
John McCall7e1dff72010-09-17 02:31:44 +0000356
357 /// A visitor which checks whether an initializer uses 'this' in a
358 /// way which requires the vtable to be properly set.
359 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
360 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
361
362 bool UsesThis;
363
364 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
365
366 // Black-list all explicit and implicit references to 'this'.
367 //
368 // Do we need to worry about external references to 'this' derived
369 // from arbitrary code? If so, then anything which runs arbitrary
370 // external code might potentially access the vtable.
371 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
372 };
373}
374
375static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
376 DynamicThisUseChecker Checker(C);
377 Checker.Visit(const_cast<Expr*>(Init));
378 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000379}
380
Anders Carlsson607d0372009-12-24 22:46:43 +0000381static void EmitBaseInitializer(CodeGenFunction &CGF,
382 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000383 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000384 CXXCtorType CtorType) {
385 assert(BaseInit->isBaseInitializer() &&
386 "Must have base initializer!");
387
388 llvm::Value *ThisPtr = CGF.LoadCXXThis();
389
390 const Type *BaseType = BaseInit->getBaseClass();
391 CXXRecordDecl *BaseClassDecl =
392 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
393
Anders Carlsson80638c52010-04-12 00:51:03 +0000394 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000395
396 // The base constructor doesn't construct virtual bases.
397 if (CtorType == Ctor_Base && isBaseVirtual)
398 return;
399
John McCall7e1dff72010-09-17 02:31:44 +0000400 // If the initializer for the base (other than the constructor
401 // itself) accesses 'this' in any way, we need to initialize the
402 // vtables.
403 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
404 CGF.InitializeVTablePointers(ClassDecl);
405
John McCallbff225e2010-02-16 04:15:37 +0000406 // We can pretend to be a complete class because it only matters for
407 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000408 llvm::Value *V =
409 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000410 BaseClassDecl,
411 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000412 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000413 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000414 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000415 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000416 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +0000417 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000418
419 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000420
David Blaikie4e4d0842012-03-11 07:00:24 +0000421 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000422 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000423 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
424 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000425}
426
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000427static void EmitAggMemberInitializer(CodeGenFunction &CGF,
428 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000429 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000430 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000431 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000432 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000433 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000434 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000435 LValue LV = LHS;
Eli Friedmanf3940782011-12-03 00:54:26 +0000436
Richard Smith7c3e6152013-06-12 22:31:48 +0000437 if (ArrayIndexVar) {
438 // If we have an array index variable, load it and use it as an offset.
439 // Then, increment the value.
440 llvm::Value *Dest = LHS.getAddress();
441 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
442 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
443 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
444 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
445 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl924db712012-02-19 15:41:54 +0000446
Richard Smith7c3e6152013-06-12 22:31:48 +0000447 // Update the LValue.
448 LV.setAddress(Dest);
449 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
450 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000451 }
John McCall558d2ab2010-09-15 10:14:12 +0000452
Richard Smith7c3e6152013-06-12 22:31:48 +0000453 switch (CGF.getEvaluationKind(T)) {
454 case TEK_Scalar:
455 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
456 break;
457 case TEK_Complex:
458 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
459 break;
460 case TEK_Aggregate: {
461 AggValueSlot Slot =
462 AggValueSlot::forLValue(LV,
463 AggValueSlot::IsDestructed,
464 AggValueSlot::DoesNotNeedGCBarriers,
465 AggValueSlot::IsNotAliased);
466
467 CGF.EmitAggExpr(Init, Slot);
468 break;
469 }
470 }
Sebastian Redl924db712012-02-19 15:41:54 +0000471
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000472 return;
473 }
Richard Smith7c3e6152013-06-12 22:31:48 +0000474
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000475 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
476 assert(Array && "Array initialization without the array type?");
477 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000478 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000479 assert(IndexVar && "Array index variable not loaded");
480
481 // Initialize this index variable to zero.
482 llvm::Value* Zero
483 = llvm::Constant::getNullValue(
484 CGF.ConvertType(CGF.getContext().getSizeType()));
485 CGF.Builder.CreateStore(Zero, IndexVar);
486
487 // Start the loop with a block that tests the condition.
488 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
489 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
490
491 CGF.EmitBlock(CondBlock);
492
493 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
494 // Generate: if (loop-index < number-of-elements) fall to the loop body,
495 // otherwise, go to the block after the for-loop.
496 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000497 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000498 llvm::Value *NumElementsPtr =
499 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000500 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
501 "isless");
502
503 // If the condition is true, execute the body.
504 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
505
506 CGF.EmitBlock(ForBody);
507 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smith7c3e6152013-06-12 22:31:48 +0000508
509 // Inside the loop body recurse to emit the inner loop or, eventually, the
510 // constructor call.
511 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
512 Array->getElementType(), ArrayIndexes, Index + 1);
513
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000514 CGF.EmitBlock(ContinueBlock);
515
516 // Emit the increment of the loop counter.
517 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
518 Counter = CGF.Builder.CreateLoad(IndexVar);
519 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
520 CGF.Builder.CreateStore(NextVal, IndexVar);
521
522 // Finally, branch back up to the condition for the next iteration.
523 CGF.EmitBranch(CondBlock);
524
525 // Emit the fall-through block.
526 CGF.EmitBlock(AfterFor, true);
527}
John McCall182ab512010-07-21 01:23:41 +0000528
Anders Carlsson607d0372009-12-24 22:46:43 +0000529static void EmitMemberInitializer(CodeGenFunction &CGF,
530 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000531 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000532 const CXXConstructorDecl *Constructor,
533 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000534 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000535 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000536 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000537
538 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000539 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000540 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000541
542 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +0000543 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedman859c65c2012-08-08 03:51:37 +0000544 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman377ecc72012-04-16 03:54:45 +0000545
Francois Pichet00eb3f92010-12-04 09:14:42 +0000546 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedman859c65c2012-08-08 03:51:37 +0000547 // If we are initializing an anonymous union field, drill down to
548 // the field.
549 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
550 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
551 IEnd = IndirectField->chain_end();
552 for ( ; I != IEnd; ++I)
553 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichet00eb3f92010-12-04 09:14:42 +0000554 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000555 } else {
Eli Friedman859c65c2012-08-08 03:51:37 +0000556 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000557 }
558
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000559 // Special case: if we are in a copy or move constructor, and we are copying
560 // an array of PODs or classes with trivial copy constructors, ignore the
561 // AST and perform the copy we know is equivalent.
562 // FIXME: This is hacky at best... if we had a bit more explicit information
563 // in the AST, we could generalize it more easily.
564 const ConstantArrayType *Array
565 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rosea7b87972013-08-07 16:16:48 +0000566 if (Array && Constructor->isDefaulted() &&
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000567 Constructor->isCopyOrMoveConstructor()) {
568 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smithe9385362012-11-07 23:56:21 +0000569 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000570 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smithe9385362012-11-07 23:56:21 +0000571 (CE && CE->getConstructor()->isTrivial())) {
572 // Find the source pointer. We know it's the last argument because
573 // we know we're in an implicit copy constructor.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000574 unsigned SrcArgIndex = Args.size() - 1;
575 llvm::Value *SrcPtr
576 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman377ecc72012-04-16 03:54:45 +0000577 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
578 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000579
580 // Copy the aggregate.
581 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier649b4a12012-03-29 17:37:10 +0000582 LHS.isVolatileQualified());
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000583 return;
584 }
585 }
586
587 ArrayRef<VarDecl *> ArrayIndexes;
588 if (MemberInit->getNumArrayIndices())
589 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000590 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000591}
592
Eli Friedmanb74ed082012-02-14 02:31:03 +0000593void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
594 LValue LHS, Expr *Init,
595 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000596 QualType FieldType = Field->getType();
John McCall9d232c82013-03-07 21:37:08 +0000597 switch (getEvaluationKind(FieldType)) {
598 case TEK_Scalar:
John McCallf85e1932011-06-15 23:02:42 +0000599 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000600 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000601 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000602 RValue RHS = RValue::get(EmitScalarExpr(Init));
603 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000604 }
John McCall9d232c82013-03-07 21:37:08 +0000605 break;
606 case TEK_Complex:
607 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
608 break;
609 case TEK_Aggregate: {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000610 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000611 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000612 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000613
614 // The LHS is a pointer to the first object we'll be constructing, as
615 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000616 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
617 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000618 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000619 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
620 BasePtr);
621 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000622
623 // Create an array index that will be used to walk over all of the
624 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000625 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000626 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000627 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000628
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000629
630 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000631 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000632 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000633 }
634
Eli Friedmanb74ed082012-02-14 02:31:03 +0000635 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000636 ArrayIndexes, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000637 }
John McCall9d232c82013-03-07 21:37:08 +0000638 }
John McCall074cae02013-02-01 05:11:40 +0000639
640 // Ensure that we destroy this object if an exception is thrown
641 // later in the constructor.
642 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
643 if (needsEHCleanup(dtorKind))
644 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlsson607d0372009-12-24 22:46:43 +0000645}
646
John McCallc0bf4622010-02-23 00:48:20 +0000647/// Checks whether the given constructor is a valid subject for the
648/// complete-to-base constructor delegation optimization, i.e.
649/// emitting the complete constructor as a simple call to the base
650/// constructor.
651static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
652
653 // Currently we disable the optimization for classes with virtual
654 // bases because (1) the addresses of parameter variables need to be
655 // consistent across all initializers but (2) the delegate function
656 // call necessarily creates a second copy of the parameter variable.
657 //
658 // The limiting example (purely theoretical AFAIK):
659 // struct A { A(int &c) { c++; } };
660 // struct B : virtual A {
661 // B(int count) : A(count) { printf("%d\n", count); }
662 // };
663 // ...although even this example could in principle be emitted as a
664 // delegation since the address of the parameter doesn't escape.
665 if (Ctor->getParent()->getNumVBases()) {
666 // TODO: white-list trivial vbase initializers. This case wouldn't
667 // be subject to the restrictions below.
668
669 // TODO: white-list cases where:
670 // - there are no non-reference parameters to the constructor
671 // - the initializers don't access any non-reference parameters
672 // - the initializers don't take the address of non-reference
673 // parameters
674 // - etc.
675 // If we ever add any of the above cases, remember that:
676 // - function-try-blocks will always blacklist this optimization
677 // - we need to perform the constructor prologue and cleanup in
678 // EmitConstructorBody.
679
680 return false;
681 }
682
683 // We also disable the optimization for variadic functions because
684 // it's impossible to "re-pass" varargs.
685 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
686 return false;
687
Sean Hunt059ce0d2011-05-01 07:04:31 +0000688 // FIXME: Decide if we can do a delegation of a delegating constructor.
689 if (Ctor->isDelegatingConstructor())
690 return false;
691
John McCallc0bf4622010-02-23 00:48:20 +0000692 return true;
693}
694
John McCall9fc6a772010-02-19 09:25:03 +0000695/// EmitConstructorBody - Emits the body of the current constructor.
696void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
697 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
698 CXXCtorType CtorType = CurGD.getCtorType();
699
John McCallc0bf4622010-02-23 00:48:20 +0000700 // Before we go any further, try the complete->base constructor
701 // delegation optimization.
Timur Iskhodzhanov85607912012-04-20 08:05:00 +0000702 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCall64aa4b32013-04-16 22:48:15 +0000703 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000704 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000705 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000706 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
707 return;
708 }
709
John McCall9fc6a772010-02-19 09:25:03 +0000710 Stmt *Body = Ctor->getBody();
711
John McCallc0bf4622010-02-23 00:48:20 +0000712 // Enter the function-try-block before the constructor prologue if
713 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000714 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000715 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000716 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000717
Richard Smith7c3e6152013-06-12 22:31:48 +0000718 RunCleanupsScope RunCleanups(*this);
John McCall9fc6a772010-02-19 09:25:03 +0000719
John McCall56ea3772012-03-30 04:25:03 +0000720 // TODO: in restricted cases, we can emit the vbase initializers of
721 // a complete ctor and then delegate to the base ctor.
722
John McCallc0bf4622010-02-23 00:48:20 +0000723 // Emit the constructor prologue, i.e. the base and member
724 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000725 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000726
727 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000728 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000729 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
730 else if (Body)
731 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000732
733 // Emit any cleanup blocks associated with the member or base
734 // initializers, which includes (along the exceptional path) the
735 // destructors for those members and bases that were fully
736 // constructed.
Richard Smith7c3e6152013-06-12 22:31:48 +0000737 RunCleanups.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000738
John McCallc0bf4622010-02-23 00:48:20 +0000739 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000740 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000741}
742
Lang Hames56c00c42013-02-17 07:22:09 +0000743namespace {
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000744 /// RAII object to indicate that codegen is copying the value representation
745 /// instead of the object representation. Useful when copying a struct or
746 /// class which has uninitialized members and we're only performing
747 /// lvalue-to-rvalue conversion on the object but not its members.
748 class CopyingValueRepresentation {
749 public:
750 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
751 : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
752 SO.Bool = false;
753 SO.Enum = false;
754 CGF.SanOpts = &SO;
755 }
756 ~CopyingValueRepresentation() {
757 CGF.SanOpts = OldSanOpts;
758 }
759 private:
760 CodeGenFunction &CGF;
761 SanitizerOptions SO;
762 const SanitizerOptions *OldSanOpts;
763 };
764}
765
766namespace {
Lang Hames56c00c42013-02-17 07:22:09 +0000767 class FieldMemcpyizer {
768 public:
769 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
770 const VarDecl *SrcRec)
771 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
772 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
773 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
774 LastAddedFieldIndex(0) { }
775
776 static bool isMemcpyableField(FieldDecl *F) {
777 Qualifiers Qual = F->getType().getQualifiers();
778 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
779 return false;
780 return true;
781 }
782
783 void addMemcpyableField(FieldDecl *F) {
784 if (FirstField == 0)
785 addInitialField(F);
786 else
787 addNextField(F);
788 }
789
790 CharUnits getMemcpySize() const {
791 unsigned LastFieldSize =
792 LastField->isBitField() ?
793 LastField->getBitWidthValue(CGF.getContext()) :
794 CGF.getContext().getTypeSize(LastField->getType());
795 uint64_t MemcpySizeBits =
796 LastFieldOffset + LastFieldSize - FirstFieldOffset +
797 CGF.getContext().getCharWidth() - 1;
798 CharUnits MemcpySize =
799 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
800 return MemcpySize;
801 }
802
803 void emitMemcpy() {
804 // Give the subclass a chance to bail out if it feels the memcpy isn't
805 // worth it (e.g. Hasn't aggregated enough data).
806 if (FirstField == 0) {
807 return;
808 }
809
Lang Hames5e8577e2013-02-27 04:14:49 +0000810 CharUnits Alignment;
Lang Hames56c00c42013-02-17 07:22:09 +0000811
812 if (FirstField->isBitField()) {
813 const CGRecordLayout &RL =
814 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
815 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000816 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
817 } else {
Lang Hames23742cd2013-03-05 20:27:24 +0000818 Alignment = CGF.getContext().getDeclAlign(FirstField);
Lang Hames5e8577e2013-02-27 04:14:49 +0000819 }
Lang Hames56c00c42013-02-17 07:22:09 +0000820
Lang Hames5e8577e2013-02-27 04:14:49 +0000821 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
822 Alignment) == 0 && "Bad field alignment.");
823
Lang Hames56c00c42013-02-17 07:22:09 +0000824 CharUnits MemcpySize = getMemcpySize();
825 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
826 llvm::Value *ThisPtr = CGF.LoadCXXThis();
827 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
828 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
829 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
830 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
831 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
832
833 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
834 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
835 MemcpySize, Alignment);
836 reset();
837 }
838
839 void reset() {
840 FirstField = 0;
841 }
842
843 protected:
844 CodeGenFunction &CGF;
845 const CXXRecordDecl *ClassDecl;
846
847 private:
848
849 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
850 CharUnits Size, CharUnits Alignment) {
851 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
852 llvm::Type *DBP =
853 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
854 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
855
856 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
857 llvm::Type *SBP =
858 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
859 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
860
861 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
862 Alignment.getQuantity());
863 }
864
865 void addInitialField(FieldDecl *F) {
866 FirstField = F;
867 LastField = F;
868 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
869 LastFieldOffset = FirstFieldOffset;
870 LastAddedFieldIndex = F->getFieldIndex();
871 return;
872 }
873
874 void addNextField(FieldDecl *F) {
John McCall402cd222013-05-07 05:20:46 +0000875 // For the most part, the following invariant will hold:
876 // F->getFieldIndex() == LastAddedFieldIndex + 1
877 // The one exception is that Sema won't add a copy-initializer for an
878 // unnamed bitfield, which will show up here as a gap in the sequence.
879 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
880 "Cannot aggregate fields out of order.");
Lang Hames56c00c42013-02-17 07:22:09 +0000881 LastAddedFieldIndex = F->getFieldIndex();
882
883 // The 'first' and 'last' fields are chosen by offset, rather than field
884 // index. This allows the code to support bitfields, as well as regular
885 // fields.
886 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
887 if (FOffset < FirstFieldOffset) {
888 FirstField = F;
889 FirstFieldOffset = FOffset;
890 } else if (FOffset > LastFieldOffset) {
891 LastField = F;
892 LastFieldOffset = FOffset;
893 }
894 }
895
896 const VarDecl *SrcRec;
897 const ASTRecordLayout &RecLayout;
898 FieldDecl *FirstField;
899 FieldDecl *LastField;
900 uint64_t FirstFieldOffset, LastFieldOffset;
901 unsigned LastAddedFieldIndex;
902 };
903
904 class ConstructorMemcpyizer : public FieldMemcpyizer {
905 private:
906
907 /// Get source argument for copy constructor. Returns null if not a copy
908 /// constructor.
909 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
910 FunctionArgList &Args) {
Jordan Rosea7b87972013-08-07 16:16:48 +0000911 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
Lang Hames56c00c42013-02-17 07:22:09 +0000912 return Args[Args.size() - 1];
913 return 0;
914 }
915
916 // Returns true if a CXXCtorInitializer represents a member initialization
917 // that can be rolled into a memcpy.
918 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
919 if (!MemcpyableCtor)
920 return false;
921 FieldDecl *Field = MemberInit->getMember();
922 assert(Field != 0 && "No field for member init.");
923 QualType FieldType = Field->getType();
924 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
925
926 // Bail out on non-POD, not-trivially-constructable members.
927 if (!(CE && CE->getConstructor()->isTrivial()) &&
928 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
929 FieldType->isReferenceType()))
930 return false;
931
932 // Bail out on volatile fields.
933 if (!isMemcpyableField(Field))
934 return false;
935
936 // Otherwise we're good.
937 return true;
938 }
939
940 public:
941 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
942 FunctionArgList &Args)
943 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
944 ConstructorDecl(CD),
Jordan Rosea7b87972013-08-07 16:16:48 +0000945 MemcpyableCtor(CD->isDefaulted() &&
Lang Hames56c00c42013-02-17 07:22:09 +0000946 CD->isCopyOrMoveConstructor() &&
947 CGF.getLangOpts().getGC() == LangOptions::NonGC),
948 Args(Args) { }
949
950 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
951 if (isMemberInitMemcpyable(MemberInit)) {
952 AggregatedInits.push_back(MemberInit);
953 addMemcpyableField(MemberInit->getMember());
954 } else {
955 emitAggregatedInits();
956 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
957 ConstructorDecl, Args);
958 }
959 }
960
961 void emitAggregatedInits() {
962 if (AggregatedInits.size() <= 1) {
963 // This memcpy is too small to be worthwhile. Fall back on default
964 // codegen.
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000965 if (!AggregatedInits.empty()) {
966 CopyingValueRepresentation CVR(CGF);
Lang Hames56c00c42013-02-17 07:22:09 +0000967 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky62a3bba2013-09-11 02:03:20 +0000968 AggregatedInits[0], ConstructorDecl, Args);
Lang Hames56c00c42013-02-17 07:22:09 +0000969 }
970 reset();
971 return;
972 }
973
974 pushEHDestructors();
975 emitMemcpy();
976 AggregatedInits.clear();
977 }
978
979 void pushEHDestructors() {
980 llvm::Value *ThisPtr = CGF.LoadCXXThis();
981 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
982 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
983
984 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
985 QualType FieldType = AggregatedInits[i]->getMember()->getType();
986 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
987 if (CGF.needsEHCleanup(dtorKind))
988 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
989 }
990 }
991
992 void finish() {
993 emitAggregatedInits();
994 }
995
996 private:
997 const CXXConstructorDecl *ConstructorDecl;
998 bool MemcpyableCtor;
999 FunctionArgList &Args;
1000 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1001 };
1002
1003 class AssignmentMemcpyizer : public FieldMemcpyizer {
1004 private:
1005
1006 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001007 // exists. Otherwise returns null.
1008 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hames56c00c42013-02-17 07:22:09 +00001009 if (!AssignmentsMemcpyable)
1010 return 0;
1011 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1012 // Recognise trivial assignments.
1013 if (BO->getOpcode() != BO_Assign)
1014 return 0;
1015 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1016 if (!ME)
1017 return 0;
1018 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1019 if (!Field || !isMemcpyableField(Field))
1020 return 0;
1021 Stmt *RHS = BO->getRHS();
1022 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1023 RHS = EC->getSubExpr();
1024 if (!RHS)
1025 return 0;
1026 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1027 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1028 return 0;
1029 return Field;
1030 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1031 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1032 if (!(MD && (MD->isCopyAssignmentOperator() ||
1033 MD->isMoveAssignmentOperator()) &&
1034 MD->isTrivial()))
1035 return 0;
1036 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1037 if (!IOA)
1038 return 0;
1039 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1040 if (!Field || !isMemcpyableField(Field))
1041 return 0;
1042 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1043 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1044 return 0;
1045 return Field;
1046 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1047 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1048 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1049 return 0;
1050 Expr *DstPtr = CE->getArg(0);
1051 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1052 DstPtr = DC->getSubExpr();
1053 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1054 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1055 return 0;
1056 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1057 if (!ME)
1058 return 0;
1059 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1060 if (!Field || !isMemcpyableField(Field))
1061 return 0;
1062 Expr *SrcPtr = CE->getArg(1);
1063 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1064 SrcPtr = SC->getSubExpr();
1065 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1066 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1067 return 0;
1068 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1069 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1070 return 0;
1071 return Field;
1072 }
1073
1074 return 0;
1075 }
1076
1077 bool AssignmentsMemcpyable;
1078 SmallVector<Stmt*, 16> AggregatedStmts;
1079
1080 public:
1081
1082 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1083 FunctionArgList &Args)
1084 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1085 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1086 assert(Args.size() == 2);
1087 }
1088
1089 void emitAssignment(Stmt *S) {
1090 FieldDecl *F = getMemcpyableField(S);
1091 if (F) {
1092 addMemcpyableField(F);
1093 AggregatedStmts.push_back(S);
1094 } else {
1095 emitAggregatedStmts();
1096 CGF.EmitStmt(S);
1097 }
1098 }
1099
1100 void emitAggregatedStmts() {
1101 if (AggregatedStmts.size() <= 1) {
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001102 if (!AggregatedStmts.empty()) {
1103 CopyingValueRepresentation CVR(CGF);
1104 CGF.EmitStmt(AggregatedStmts[0]);
1105 }
Lang Hames56c00c42013-02-17 07:22:09 +00001106 reset();
1107 }
1108
1109 emitMemcpy();
1110 AggregatedStmts.clear();
1111 }
1112
1113 void finish() {
1114 emitAggregatedStmts();
1115 }
1116 };
1117
1118}
1119
Anders Carlsson607d0372009-12-24 22:46:43 +00001120/// EmitCtorPrologue - This routine generates necessary code to initialize
1121/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +00001122void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +00001123 CXXCtorType CtorType,
1124 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +00001125 if (CD->isDelegatingConstructor())
1126 return EmitDelegatingCXXConstructorCall(CD, Args);
1127
Anders Carlsson607d0372009-12-24 22:46:43 +00001128 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001129
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001130 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1131 E = CD->init_end();
1132
1133 llvm::BasicBlock *BaseCtorContinueBB = 0;
1134 if (ClassDecl->getNumVBases() &&
1135 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1136 // The ABIs that don't have constructor variants need to put a branch
1137 // before the virtual base initialization code.
Reid Kleckner90633022013-06-19 15:20:38 +00001138 BaseCtorContinueBB =
1139 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001140 assert(BaseCtorContinueBB);
1141 }
1142
1143 // Virtual base initializers first.
1144 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1145 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1146 }
1147
1148 if (BaseCtorContinueBB) {
1149 // Complete object handler should continue to the remaining initializers.
1150 Builder.CreateBr(BaseCtorContinueBB);
1151 EmitBlock(BaseCtorContinueBB);
1152 }
1153
1154 // Then, non-virtual base initializers.
1155 for (; B != E && (*B)->isBaseInitializer(); B++) {
1156 assert(!(*B)->isBaseVirtual());
1157 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlsson607d0372009-12-24 22:46:43 +00001158 }
1159
Anders Carlsson603d6d12010-03-28 21:07:49 +00001160 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +00001161
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001162 // And finally, initialize class members.
Richard Smithc3bf52c2013-04-20 22:23:05 +00001163 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hames56c00c42013-02-17 07:22:09 +00001164 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001165 for (; B != E; B++) {
1166 CXXCtorInitializer *Member = (*B);
1167 assert(!Member->isBaseInitializer());
1168 assert(Member->isAnyMemberInitializer() &&
1169 "Delegating initializer on non-delegating constructor");
1170 CM.addMemberInitializer(Member);
1171 }
Lang Hames56c00c42013-02-17 07:22:09 +00001172 CM.finish();
Anders Carlsson607d0372009-12-24 22:46:43 +00001173}
1174
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001175static bool
1176FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1177
1178static bool
1179HasTrivialDestructorBody(ASTContext &Context,
1180 const CXXRecordDecl *BaseClassDecl,
1181 const CXXRecordDecl *MostDerivedClassDecl)
1182{
1183 // If the destructor is trivial we don't have to check anything else.
1184 if (BaseClassDecl->hasTrivialDestructor())
1185 return true;
1186
1187 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1188 return false;
1189
1190 // Check fields.
1191 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1192 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001193 const FieldDecl *Field = *I;
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001194
1195 if (!FieldHasTrivialDestructorBody(Context, Field))
1196 return false;
1197 }
1198
1199 // Check non-virtual bases.
1200 for (CXXRecordDecl::base_class_const_iterator I =
1201 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1202 I != E; ++I) {
1203 if (I->isVirtual())
1204 continue;
1205
1206 const CXXRecordDecl *NonVirtualBase =
1207 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1208 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1209 MostDerivedClassDecl))
1210 return false;
1211 }
1212
1213 if (BaseClassDecl == MostDerivedClassDecl) {
1214 // Check virtual bases.
1215 for (CXXRecordDecl::base_class_const_iterator I =
1216 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1217 I != E; ++I) {
1218 const CXXRecordDecl *VirtualBase =
1219 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1220 if (!HasTrivialDestructorBody(Context, VirtualBase,
1221 MostDerivedClassDecl))
1222 return false;
1223 }
1224 }
1225
1226 return true;
1227}
1228
1229static bool
1230FieldHasTrivialDestructorBody(ASTContext &Context,
1231 const FieldDecl *Field)
1232{
1233 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1234
1235 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1236 if (!RT)
1237 return true;
1238
1239 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1240 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1241}
1242
Anders Carlssonffb945f2011-05-14 23:26:09 +00001243/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1244/// any vtable pointers before calling this destructor.
1245static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +00001246 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +00001247 if (!Dtor->hasTrivialBody())
1248 return false;
1249
1250 // Check the fields.
1251 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1252 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1253 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001254 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001255
Anders Carlssonadf5dc32011-05-15 17:36:21 +00001256 if (!FieldHasTrivialDestructorBody(Context, Field))
1257 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +00001258 }
1259
1260 return true;
1261}
1262
John McCall9fc6a772010-02-19 09:25:03 +00001263/// EmitDestructorBody - Emits the body of the current destructor.
1264void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1265 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1266 CXXDtorType DtorType = CurGD.getDtorType();
1267
John McCall50da2ca2010-07-21 05:30:47 +00001268 // The call to operator delete in a deleting destructor happens
1269 // outside of the function-try-block, which means it's always
1270 // possible to delegate the destructor body to the complete
1271 // destructor. Do so.
1272 if (DtorType == Dtor_Deleting) {
1273 EnterDtorCleanups(Dtor, Dtor_Deleting);
1274 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001275 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001276 PopCleanupBlock();
1277 return;
1278 }
1279
John McCall9fc6a772010-02-19 09:25:03 +00001280 Stmt *Body = Dtor->getBody();
1281
1282 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +00001283 // anything else.
1284 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +00001285 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001286 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001287
John McCall50da2ca2010-07-21 05:30:47 +00001288 // Enter the epilogue cleanups.
1289 RunCleanupsScope DtorEpilogue(*this);
1290
John McCall9fc6a772010-02-19 09:25:03 +00001291 // If this is the complete variant, just invoke the base variant;
1292 // the epilogue will destruct the virtual bases. But we can't do
1293 // this optimization if the body is a function-try-block, because
Reid Klecknera4130ba2013-07-22 13:51:44 +00001294 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1295 // always delegate because we might not have a definition in this TU.
John McCall50da2ca2010-07-21 05:30:47 +00001296 switch (DtorType) {
1297 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1298
1299 case Dtor_Complete:
Reid Klecknera4130ba2013-07-22 13:51:44 +00001300 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1301 "can't emit a dtor without a body for non-Microsoft ABIs");
1302
John McCall50da2ca2010-07-21 05:30:47 +00001303 // Enter the cleanup scopes for virtual bases.
1304 EnterDtorCleanups(Dtor, Dtor_Complete);
1305
Reid Klecknera4130ba2013-07-22 13:51:44 +00001306 if (!isTryBody) {
John McCall50da2ca2010-07-21 05:30:47 +00001307 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001308 /*Delegating=*/false, LoadCXXThis());
John McCall50da2ca2010-07-21 05:30:47 +00001309 break;
1310 }
1311 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +00001312
John McCall50da2ca2010-07-21 05:30:47 +00001313 case Dtor_Base:
Reid Klecknera4130ba2013-07-22 13:51:44 +00001314 assert(Body);
1315
John McCall50da2ca2010-07-21 05:30:47 +00001316 // Enter the cleanup scopes for fields and non-virtual bases.
1317 EnterDtorCleanups(Dtor, Dtor_Base);
1318
1319 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +00001320 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1321 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +00001322
1323 if (isTryBody)
1324 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1325 else if (Body)
1326 EmitStmt(Body);
1327 else {
1328 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1329 // nothing to do besides what's in the epilogue
1330 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +00001331 // -fapple-kext must inline any call to this dtor into
1332 // the caller's body.
Richard Smith7edf9e32012-11-01 22:30:59 +00001333 if (getLangOpts().AppleKext)
Bill Wendling72390b32012-12-20 19:27:06 +00001334 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +00001335 break;
John McCall9fc6a772010-02-19 09:25:03 +00001336 }
1337
John McCall50da2ca2010-07-21 05:30:47 +00001338 // Jump out through the epilogue cleanups.
1339 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +00001340
1341 // Exit the try if applicable.
1342 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +00001343 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +00001344}
1345
Lang Hames56c00c42013-02-17 07:22:09 +00001346void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1347 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1348 const Stmt *RootS = AssignOp->getBody();
1349 assert(isa<CompoundStmt>(RootS) &&
1350 "Body of an implicit assignment operator should be compound stmt.");
1351 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1352
1353 LexicalScope Scope(*this, RootCS->getSourceRange());
1354
1355 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1356 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1357 E = RootCS->body_end();
1358 I != E; ++I) {
1359 AM.emitAssignment(*I);
1360 }
1361 AM.finish();
1362}
1363
John McCall50da2ca2010-07-21 05:30:47 +00001364namespace {
1365 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +00001366 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +00001367 CallDtorDelete() {}
1368
John McCallad346f42011-07-12 20:27:29 +00001369 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +00001370 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1371 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1372 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1373 CGF.getContext().getTagDeclType(ClassDecl));
1374 }
1375 };
1376
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001377 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1378 llvm::Value *ShouldDeleteCondition;
1379 public:
1380 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1381 : ShouldDeleteCondition(ShouldDeleteCondition) {
1382 assert(ShouldDeleteCondition != NULL);
1383 }
1384
1385 void Emit(CodeGenFunction &CGF, Flags flags) {
1386 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1387 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1388 llvm::Value *ShouldCallDelete
1389 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1390 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1391
1392 CGF.EmitBlock(callDeleteBB);
1393 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1394 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1395 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1396 CGF.getContext().getTagDeclType(ClassDecl));
1397 CGF.Builder.CreateBr(continueBB);
1398
1399 CGF.EmitBlock(continueBB);
1400 }
1401 };
1402
John McCall9928c482011-07-12 16:41:08 +00001403 class DestroyField : public EHScopeStack::Cleanup {
1404 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001405 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001406 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +00001407
John McCall9928c482011-07-12 16:41:08 +00001408 public:
1409 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1410 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001411 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001412 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +00001413
John McCallad346f42011-07-12 20:27:29 +00001414 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001415 // Find the address of the field.
1416 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman377ecc72012-04-16 03:54:45 +00001417 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1418 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1419 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall9928c482011-07-12 16:41:08 +00001420 assert(LV.isSimple());
1421
1422 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001423 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +00001424 }
1425 };
1426}
1427
Anders Carlsson607d0372009-12-24 22:46:43 +00001428/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1429/// destructor. This is to call destructors on members and base classes
1430/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +00001431void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1432 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +00001433 assert(!DD->isTrivial() &&
1434 "Should not emit dtor epilogue for trivial dtor!");
1435
John McCall50da2ca2010-07-21 05:30:47 +00001436 // The deleting-destructor phase just needs to call the appropriate
1437 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001438 if (DtorType == Dtor_Deleting) {
1439 assert(DD->getOperatorDelete() &&
1440 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001441 if (CXXStructorImplicitParamValue) {
1442 // If there is an implicit param to the deleting dtor, it's a boolean
1443 // telling whether we should call delete at the end of the dtor.
1444 EHStack.pushCleanup<CallDtorDeleteConditional>(
1445 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1446 } else {
1447 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1448 }
John McCall3b477332010-02-18 19:59:28 +00001449 return;
1450 }
1451
John McCall50da2ca2010-07-21 05:30:47 +00001452 const CXXRecordDecl *ClassDecl = DD->getParent();
1453
Richard Smith416f63e2011-09-18 12:11:43 +00001454 // Unions have no bases and do not call field destructors.
1455 if (ClassDecl->isUnion())
1456 return;
1457
John McCall50da2ca2010-07-21 05:30:47 +00001458 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001459 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001460
1461 // We push them in the forward order so that they'll be popped in
1462 // the reverse order.
1463 for (CXXRecordDecl::base_class_const_iterator I =
1464 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001465 I != E; ++I) {
1466 const CXXBaseSpecifier &Base = *I;
1467 CXXRecordDecl *BaseClassDecl
1468 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1469
1470 // Ignore trivial destructors.
1471 if (BaseClassDecl->hasTrivialDestructor())
1472 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001473
John McCall1f0fca52010-07-21 07:22:38 +00001474 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1475 BaseClassDecl,
1476 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001477 }
John McCall50da2ca2010-07-21 05:30:47 +00001478
John McCall3b477332010-02-18 19:59:28 +00001479 return;
1480 }
1481
1482 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001483
1484 // Destroy non-virtual bases.
1485 for (CXXRecordDecl::base_class_const_iterator I =
1486 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1487 const CXXBaseSpecifier &Base = *I;
1488
1489 // Ignore virtual bases.
1490 if (Base.isVirtual())
1491 continue;
1492
1493 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1494
1495 // Ignore trivial destructors.
1496 if (BaseClassDecl->hasTrivialDestructor())
1497 continue;
John McCall3b477332010-02-18 19:59:28 +00001498
John McCall1f0fca52010-07-21 07:22:38 +00001499 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1500 BaseClassDecl,
1501 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001502 }
1503
1504 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001505 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001506 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1507 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001508 const FieldDecl *field = *I;
John McCall9928c482011-07-12 16:41:08 +00001509 QualType type = field->getType();
1510 QualType::DestructionKind dtorKind = type.isDestructedType();
1511 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001512
Richard Smith9a561d52012-02-26 09:11:52 +00001513 // Anonymous union members do not have their destructors called.
1514 const RecordType *RT = type->getAsUnionType();
1515 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1516
John McCall9928c482011-07-12 16:41:08 +00001517 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1518 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1519 getDestroyer(dtorKind),
1520 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001521 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001522}
1523
John McCallc3c07662011-07-13 06:10:41 +00001524/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1525/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001526///
John McCallc3c07662011-07-13 06:10:41 +00001527/// \param ctor the constructor to call for each element
John McCallc3c07662011-07-13 06:10:41 +00001528/// \param arrayType the type of the array to initialize
1529/// \param arrayBegin an arrayType*
1530/// \param zeroInitialize true if each element should be
1531/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001532void
John McCallc3c07662011-07-13 06:10:41 +00001533CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1534 const ConstantArrayType *arrayType,
1535 llvm::Value *arrayBegin,
1536 CallExpr::const_arg_iterator argBegin,
1537 CallExpr::const_arg_iterator argEnd,
1538 bool zeroInitialize) {
1539 QualType elementType;
1540 llvm::Value *numElements =
1541 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001542
John McCallc3c07662011-07-13 06:10:41 +00001543 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1544 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001545}
1546
John McCallc3c07662011-07-13 06:10:41 +00001547/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1548/// constructor for each of several members of an array.
1549///
1550/// \param ctor the constructor to call for each element
1551/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001552/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001553/// \param arrayBegin a T*, where T is the type constructed by ctor
1554/// \param zeroInitialize true if each element should be
1555/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001556void
John McCallc3c07662011-07-13 06:10:41 +00001557CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1558 llvm::Value *numElements,
1559 llvm::Value *arrayBegin,
1560 CallExpr::const_arg_iterator argBegin,
1561 CallExpr::const_arg_iterator argEnd,
1562 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001563
1564 // It's legal for numElements to be zero. This can happen both
1565 // dynamically, because x can be zero in 'new A[x]', and statically,
1566 // because of GCC extensions that permit zero-length arrays. There
1567 // are probably legitimate places where we could assume that this
1568 // doesn't happen, but it's not clear that it's worth it.
1569 llvm::BranchInst *zeroCheckBranch = 0;
1570
1571 // Optimize for a constant count.
1572 llvm::ConstantInt *constantCount
1573 = dyn_cast<llvm::ConstantInt>(numElements);
1574 if (constantCount) {
1575 // Just skip out if the constant count is zero.
1576 if (constantCount->isZero()) return;
1577
1578 // Otherwise, emit the check.
1579 } else {
1580 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1581 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1582 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1583 EmitBlock(loopBB);
1584 }
1585
John McCallc3c07662011-07-13 06:10:41 +00001586 // Find the end of the array.
1587 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1588 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001589
John McCallc3c07662011-07-13 06:10:41 +00001590 // Enter the loop, setting up a phi for the current location to initialize.
1591 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1592 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1593 EmitBlock(loopBB);
1594 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1595 "arrayctor.cur");
1596 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001597
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001598 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001599
1600 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001601
Douglas Gregor59174c02010-07-21 01:10:17 +00001602 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001603 if (zeroInitialize)
1604 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001605
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001606 // C++ [class.temporary]p4:
1607 // There are two contexts in which temporaries are destroyed at a different
1608 // point than the end of the full-expression. The first context is when a
1609 // default constructor is called to initialize an element of an array.
1610 // If the constructor has one or more default arguments, the destruction of
1611 // every temporary created in a default argument expression is sequenced
1612 // before the construction of the next array element, if any.
1613
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001614 {
John McCallf1549f62010-07-06 01:34:17 +00001615 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001616
John McCallc3c07662011-07-13 06:10:41 +00001617 // Evaluate the constructor and its arguments in a regular
1618 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001619 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001620 !ctor->getParent()->hasTrivialDestructor()) {
1621 Destroyer *destroyer = destroyCXXObject;
1622 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1623 }
1624
1625 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001626 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001627 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001628
John McCallc3c07662011-07-13 06:10:41 +00001629 // Go to the next element.
1630 llvm::Value *next =
1631 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1632 "arrayctor.next");
1633 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001634
John McCallc3c07662011-07-13 06:10:41 +00001635 // Check whether that's the end of the loop.
1636 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1637 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1638 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001639
John McCalldd376ca2011-07-13 07:37:11 +00001640 // Patch the earlier check to skip over the loop.
1641 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1642
John McCallc3c07662011-07-13 06:10:41 +00001643 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001644}
1645
John McCallbdc4d802011-07-09 01:37:26 +00001646void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1647 llvm::Value *addr,
1648 QualType type) {
1649 const RecordType *rtype = type->castAs<RecordType>();
1650 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1651 const CXXDestructorDecl *dtor = record->getDestructor();
1652 assert(!dtor->isTrivial());
1653 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001654 /*Delegating=*/false, addr);
John McCallbdc4d802011-07-09 01:37:26 +00001655}
1656
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001657void
1658CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001659 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001660 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001661 llvm::Value *This,
1662 CallExpr::const_arg_iterator ArgBeg,
1663 CallExpr::const_arg_iterator ArgEnd) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001664 // If this is a trivial constructor, just emit what's needed.
John McCall8b6bbeb2010-02-06 00:25:16 +00001665 if (D->isTrivial()) {
1666 if (ArgBeg == ArgEnd) {
1667 // Trivial default constructor, no codegen required.
1668 assert(D->isDefaultConstructor() &&
1669 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001670 return;
1671 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001672
1673 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001674 assert(D->isCopyOrMoveConstructor() &&
1675 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001676
John McCall8b6bbeb2010-02-06 00:25:16 +00001677 const Expr *E = (*ArgBeg);
1678 QualType Ty = E->getType();
1679 llvm::Value *Src = EmitLValue(E).getAddress();
1680 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001681 return;
1682 }
1683
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001684 // Non-trivial constructors are handled in an ABI-specific manner.
Stephen Lin3b50e8d2013-06-30 20:40:16 +00001685 CGM.getCXXABI().EmitConstructorCall(*this, D, Type, ForVirtualBase,
1686 Delegating, This, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001687}
1688
John McCallc0bf4622010-02-23 00:48:20 +00001689void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001690CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1691 llvm::Value *This, llvm::Value *Src,
1692 CallExpr::const_arg_iterator ArgBeg,
1693 CallExpr::const_arg_iterator ArgEnd) {
1694 if (D->isTrivial()) {
1695 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001696 assert(D->isCopyOrMoveConstructor() &&
1697 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001698 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1699 return;
1700 }
Nick Lewycky62a3bba2013-09-11 02:03:20 +00001701 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, clang::Ctor_Complete);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001702 assert(D->isInstance() &&
1703 "Trying to emit a member call expr on a static method!");
1704
1705 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1706
1707 CallArgList Args;
1708
1709 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001710 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001711
1712
1713 // Push the src ptr.
1714 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001715 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001716 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001717 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001718
1719 // Skip over first argument (Src).
1720 ++ArgBeg;
1721 CallExpr::const_arg_iterator Arg = ArgBeg;
1722 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1723 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1724 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001725 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001726 }
1727 // Either we've emitted all the call args, or we have a call to a
1728 // variadic function.
1729 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1730 "Extra arguments in non-variadic function!");
1731 // If we still have any arguments, emit them using the type of the argument.
1732 for (; Arg != ArgEnd; ++Arg) {
1733 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001734 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001735 }
1736
John McCall0f3d0972012-07-07 06:41:13 +00001737 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1738 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001739}
1740
1741void
John McCallc0bf4622010-02-23 00:48:20 +00001742CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1743 CXXCtorType CtorType,
1744 const FunctionArgList &Args) {
1745 CallArgList DelegateArgs;
1746
1747 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1748 assert(I != E && "no parameters to constructor");
1749
1750 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001751 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001752 ++I;
1753
1754 // vtt
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001755 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001756 /*ForVirtualBase=*/false,
1757 /*Delegating=*/true)) {
John McCallc0bf4622010-02-23 00:48:20 +00001758 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001759 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001760
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001761 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001762 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001763 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001764 ++I;
1765 }
1766 }
1767
1768 // Explicit arguments.
1769 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001770 const VarDecl *param = *I;
1771 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001772 }
1773
Manman Ren63fd4082013-03-20 16:59:38 +00001774 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCallde5d3c72012-02-17 03:33:10 +00001775 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren63fd4082013-03-20 16:59:38 +00001776 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallc0bf4622010-02-23 00:48:20 +00001777}
1778
Sean Huntb76af9c2011-05-03 23:05:34 +00001779namespace {
1780 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1781 const CXXDestructorDecl *Dtor;
1782 llvm::Value *Addr;
1783 CXXDtorType Type;
1784
1785 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1786 CXXDtorType Type)
1787 : Dtor(D), Addr(Addr), Type(Type) {}
1788
John McCallad346f42011-07-12 20:27:29 +00001789 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001790 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001791 /*Delegating=*/true, Addr);
Sean Huntb76af9c2011-05-03 23:05:34 +00001792 }
1793 };
1794}
1795
Sean Hunt059ce0d2011-05-01 07:04:31 +00001796void
1797CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1798 const FunctionArgList &Args) {
1799 assert(Ctor->isDelegatingConstructor());
1800
1801 llvm::Value *ThisPtr = LoadCXXThis();
1802
Eli Friedmanf3940782011-12-03 00:54:26 +00001803 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001804 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001805 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001806 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001807 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001808 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001809 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001810
1811 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001812
Sean Huntb76af9c2011-05-03 23:05:34 +00001813 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001814 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001815 CXXDtorType Type =
1816 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1817
1818 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1819 ClassDecl->getDestructor(),
1820 ThisPtr, Type);
1821 }
1822}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001823
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001824void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1825 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001826 bool ForVirtualBase,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001827 bool Delegating,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001828 llvm::Value *This) {
Timur Iskhodzhanov1d4fff52013-02-27 13:46:31 +00001829 llvm::Value *VTT = GetVTTParameter(GlobalDecl(DD, Type),
Douglas Gregor378e1e72013-01-31 05:50:40 +00001830 ForVirtualBase, Delegating);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001831 llvm::Value *Callee = 0;
Richard Smith7edf9e32012-11-01 22:30:59 +00001832 if (getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001833 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1834 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001835
1836 if (!Callee)
1837 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001838
Richard Smith4def70d2012-10-09 19:52:38 +00001839 // FIXME: Provide a source location here.
1840 EmitCXXMemberCall(DD, SourceLocation(), Callee, ReturnValueSlot(), This,
Timur Iskhodzhanov59660c22013-02-13 08:37:51 +00001841 VTT, getContext().getPointerType(getContext().VoidPtrTy),
1842 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001843}
1844
John McCall291ae942010-07-21 01:41:18 +00001845namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001846 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001847 const CXXDestructorDecl *Dtor;
1848 llvm::Value *Addr;
1849
1850 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1851 : Dtor(D), Addr(Addr) {}
1852
John McCallad346f42011-07-12 20:27:29 +00001853 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001854 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor378e1e72013-01-31 05:50:40 +00001855 /*ForVirtualBase=*/false,
1856 /*Delegating=*/false, Addr);
John McCall291ae942010-07-21 01:41:18 +00001857 }
1858 };
1859}
1860
John McCall81407d42010-07-21 06:29:51 +00001861void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1862 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001863 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001864}
1865
John McCallf1549f62010-07-06 01:34:17 +00001866void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1867 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1868 if (!ClassDecl) return;
1869 if (ClassDecl->hasTrivialDestructor()) return;
1870
1871 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001872 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001873 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001874}
1875
Anders Carlssond103f9f2010-03-28 19:40:00 +00001876void
1877CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001878 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001879 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001880 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001881 const CXXRecordDecl *RD = Base.getBase();
1882
Anders Carlssond103f9f2010-03-28 19:40:00 +00001883 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001884 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001885
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001886 bool NeedsVTTParam = CGM.getCXXABI().NeedsVTTParameter(CurGD);
1887
Anders Carlssonc83f1062010-03-29 01:08:49 +00001888 // Check if we need to use a vtable from the VTT.
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001889 if (NeedsVTTParam && (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001890 // Get the secondary vpointer index.
1891 uint64_t VirtualPointerIndex =
1892 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1893
1894 /// Load the VTT.
1895 llvm::Value *VTT = LoadCXXVTT();
1896 if (VirtualPointerIndex)
1897 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1898
1899 // And load the address point from the VTT.
1900 VTableAddressPoint = Builder.CreateLoad(VTT);
1901 } else {
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00001902 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(VTableClass);
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001903 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001904 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001905 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001906 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001907 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001908
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001909 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001910 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001911 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001912
Peter Collingbournee1e35f72013-06-28 20:45:28 +00001913 if (NeedsVTTParam && NearestVBase) {
Anders Carlsson3e79c302010-04-20 18:05:10 +00001914 // We need to use the virtual base offset offset because the virtual base
1915 // might have a different offset in the most derived class.
Reid Klecknerb0f533e2013-05-29 18:02:47 +00001916 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1917 LoadCXXThis(),
1918 VTableClass,
1919 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001920 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001921 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001922 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001923 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001924 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001925
1926 // Apply the offsets.
1927 llvm::Value *VTableField = LoadCXXThis();
1928
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001929 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001930 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1931 NonVirtualOffset,
1932 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001933
Anders Carlssond103f9f2010-03-28 19:40:00 +00001934 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001935 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001936 VTableAddressPoint->getType()->getPointerTo();
1937 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001938 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1939 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001940}
1941
Anders Carlsson603d6d12010-03-28 21:07:49 +00001942void
1943CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001944 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001945 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001946 bool BaseIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001947 const CXXRecordDecl *VTableClass,
1948 VisitedVirtualBasesSetTy& VBases) {
1949 // If this base is a non-virtual primary base the address point has already
1950 // been set.
1951 if (!BaseIsNonVirtualPrimaryBase) {
1952 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001953 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00001954 VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001955 }
1956
1957 const CXXRecordDecl *RD = Base.getBase();
1958
1959 // Traverse bases.
1960 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1961 E = RD->bases_end(); I != E; ++I) {
1962 CXXRecordDecl *BaseDecl
1963 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1964
1965 // Ignore classes without a vtable.
1966 if (!BaseDecl->isDynamicClass())
1967 continue;
1968
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001969 CharUnits BaseOffset;
1970 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001971 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001972
1973 if (I->isVirtual()) {
1974 // Check if we've visited this virtual base before.
1975 if (!VBases.insert(BaseDecl))
1976 continue;
1977
1978 const ASTRecordLayout &Layout =
1979 getContext().getASTRecordLayout(VTableClass);
1980
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001981 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1982 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001983 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001984 } else {
1985 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1986
Ken Dyck4230d522011-03-24 01:21:01 +00001987 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001988 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001989 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001990 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001991 }
1992
Ken Dyck4230d522011-03-24 01:21:01 +00001993 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001994 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001995 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001996 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00001997 VTableClass, VBases);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001998 }
1999}
2000
2001void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2002 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00002003 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002004 return;
2005
Anders Carlsson603d6d12010-03-28 21:07:49 +00002006 // Initialize the vtable pointers for this class and all of its bases.
2007 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00002008 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2009 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00002010 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanov7f918f92013-08-21 17:33:16 +00002011 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00002012}
Dan Gohman043fb9a2010-10-26 18:44:08 +00002013
2014llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00002015 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00002016 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00002017 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2018 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2019 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00002020}
Anders Carlssona2447e02011-05-08 20:32:23 +00002021
Anders Carlssona2447e02011-05-08 20:32:23 +00002022
2023// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2024// quite what we want.
2025static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2026 while (true) {
2027 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2028 E = PE->getSubExpr();
2029 continue;
2030 }
2031
2032 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2033 if (CE->getCastKind() == CK_NoOp) {
2034 E = CE->getSubExpr();
2035 continue;
2036 }
2037 }
2038 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2039 if (UO->getOpcode() == UO_Extension) {
2040 E = UO->getSubExpr();
2041 continue;
2042 }
2043 }
2044 return E;
2045 }
2046}
2047
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002048bool
2049CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2050 const CXXMethodDecl *MD) {
2051 // When building with -fapple-kext, all calls must go through the vtable since
2052 // the kernel linker can do runtime patching of vtables.
2053 if (getLangOpts().AppleKext)
2054 return false;
2055
Anders Carlssona2447e02011-05-08 20:32:23 +00002056 // If the most derived class is marked final, we know that no subclass can
2057 // override this member function and so we can devirtualize it. For example:
2058 //
2059 // struct A { virtual void f(); }
2060 // struct B final : A { };
2061 //
2062 // void f(B *b) {
2063 // b->f();
2064 // }
2065 //
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002066 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssona2447e02011-05-08 20:32:23 +00002067 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2068 return true;
2069
2070 // If the member function is marked 'final', we know that it can't be
2071 // overridden and can therefore devirtualize it.
2072 if (MD->hasAttr<FinalAttr>())
2073 return true;
2074
2075 // Similarly, if the class itself is marked 'final' it can't be overridden
2076 // and we can therefore devirtualize the member function call.
2077 if (MD->getParent()->hasAttr<FinalAttr>())
2078 return true;
2079
2080 Base = skipNoOpCastsAndParens(Base);
2081 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2082 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2083 // This is a record decl. We know the type and can devirtualize it.
2084 return VD->getType()->isRecordType();
2085 }
2086
2087 return false;
2088 }
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002089
2090 // We can devirtualize calls on an object accessed by a class member access
2091 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2092 // a derived class object constructed in the same location.
2093 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2094 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2095 return VD->getType()->isRecordType();
2096
Anders Carlssona2447e02011-05-08 20:32:23 +00002097 // We can always devirtualize calls on temporary object expressions.
2098 if (isa<CXXConstructExpr>(Base))
2099 return true;
2100
2101 // And calls on bound temporaries.
2102 if (isa<CXXBindTemporaryExpr>(Base))
2103 return true;
2104
2105 // Check if this is a call expr that returns a record type.
2106 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2107 return CE->getCallReturnType()->isRecordType();
2108
2109 // We can't devirtualize the call.
2110 return false;
2111}
2112
Anders Carlssona2447e02011-05-08 20:32:23 +00002113llvm::Value *
2114CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2115 const CXXMethodDecl *MD,
2116 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00002117 llvm::FunctionType *fnType =
2118 CGM.getTypes().GetFunctionType(
2119 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00002120
Benjamin Kramer9581ed02013-08-25 22:46:27 +00002121 if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
Timur Iskhodzhanov8f189a92013-08-21 06:25:03 +00002122 return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002123
John McCallde5d3c72012-02-17 03:33:10 +00002124 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00002125}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002126
John McCall0f3d0972012-07-07 06:41:13 +00002127void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *lambda,
2128 CallArgList &callArgs) {
Eli Friedman64bee652012-02-25 02:48:22 +00002129 // Lookup the call operator
John McCall0f3d0972012-07-07 06:41:13 +00002130 DeclarationName operatorName
Eli Friedman21f6ed92012-02-16 03:47:28 +00002131 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
John McCall0f3d0972012-07-07 06:41:13 +00002132 CXXMethodDecl *callOperator =
David Blaikie3bc93e32012-12-19 00:45:41 +00002133 cast<CXXMethodDecl>(lambda->lookup(operatorName).front());
Eli Friedman21f6ed92012-02-16 03:47:28 +00002134
Eli Friedman21f6ed92012-02-16 03:47:28 +00002135 // Get the address of the call operator.
John McCall0f3d0972012-07-07 06:41:13 +00002136 const CGFunctionInfo &calleeFnInfo =
2137 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2138 llvm::Value *callee =
2139 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2140 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman21f6ed92012-02-16 03:47:28 +00002141
John McCall0f3d0972012-07-07 06:41:13 +00002142 // Prepare the return slot.
2143 const FunctionProtoType *FPT =
2144 callOperator->getType()->castAs<FunctionProtoType>();
2145 QualType resultType = FPT->getResultType();
2146 ReturnValueSlot returnSlot;
2147 if (!resultType->isVoidType() &&
2148 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall9d232c82013-03-07 21:37:08 +00002149 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall0f3d0972012-07-07 06:41:13 +00002150 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2151
2152 // We don't need to separately arrange the call arguments because
2153 // the call can't be variadic anyway --- it's impossible to forward
2154 // variadic arguments.
Eli Friedman21f6ed92012-02-16 03:47:28 +00002155
2156 // Now emit our call.
John McCall0f3d0972012-07-07 06:41:13 +00002157 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2158 callArgs, callOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002159
John McCall0f3d0972012-07-07 06:41:13 +00002160 // If necessary, copy the returned value into the slot.
2161 if (!resultType->isVoidType() && returnSlot.isNull())
2162 EmitReturnOfRValue(RV, resultType);
Eli Friedman50f089a2012-12-13 23:37:17 +00002163 else
2164 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman21f6ed92012-02-16 03:47:28 +00002165}
2166
Eli Friedman64bee652012-02-25 02:48:22 +00002167void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2168 const BlockDecl *BD = BlockInfo->getBlockDecl();
2169 const VarDecl *variable = BD->capture_begin()->getVariable();
2170 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2171
2172 // Start building arguments for forwarding call
2173 CallArgList CallArgs;
2174
2175 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2176 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2177 CallArgs.add(RValue::get(ThisPtr), ThisType);
2178
2179 // Add the rest of the parameters.
2180 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2181 E = BD->param_end(); I != E; ++I) {
2182 ParmVarDecl *param = *I;
2183 EmitDelegateCallArg(CallArgs, param);
2184 }
2185
2186 EmitForwardingCallToLambda(Lambda, CallArgs);
2187}
2188
2189void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCallf5ebf9b2013-05-03 07:33:41 +00002190 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman64bee652012-02-25 02:48:22 +00002191 // FIXME: Making this work correctly is nasty because it requires either
2192 // cloning the body of the call operator or making the call operator forward.
John McCallf5ebf9b2013-05-03 07:33:41 +00002193 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002194 return;
2195 }
2196
Eli Friedman64bee652012-02-25 02:48:22 +00002197 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00002198}
2199
2200void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2201 const CXXRecordDecl *Lambda = MD->getParent();
2202
2203 // Start building arguments for forwarding call
2204 CallArgList CallArgs;
2205
2206 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2207 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2208 CallArgs.add(RValue::get(ThisPtr), ThisType);
2209
2210 // Add the rest of the parameters.
2211 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2212 E = MD->param_end(); I != E; ++I) {
2213 ParmVarDecl *param = *I;
2214 EmitDelegateCallArg(CallArgs, param);
2215 }
2216
2217 EmitForwardingCallToLambda(Lambda, CallArgs);
2218}
2219
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002220void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2221 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00002222 // FIXME: Making this work correctly is nasty because it requires either
2223 // cloning the body of the call operator or making the call operator forward.
2224 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00002225 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00002226 }
2227
Douglas Gregor27dd7d92012-02-17 03:02:34 +00002228 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00002229}