blob: 59d5ef78599764b203ae165d5fdcdd1e98444ad9 [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
Devang Pateld67ef0e2010-08-11 21:04:37 +000014#include "CGDebugInfo.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000015#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000016#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000017#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000018#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000019#include "clang/AST/StmtCXX.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000021
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000022using namespace clang;
23using namespace CodeGen;
24
Ken Dyck55c02582011-03-22 00:53:26 +000025static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000026ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000028 CastExpr::path_const_iterator Start,
29 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000030 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000031
32 const CXXRecordDecl *RD = DerivedClass;
33
John McCallf871d0c2010-08-07 06:22:56 +000034 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000035 const CXXBaseSpecifier *Base = *I;
36 assert(!Base->isVirtual() && "Should not see virtual bases here!");
37
38 // Get the layout.
39 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
40
41 const CXXRecordDecl *BaseDecl =
42 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
43
44 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000045 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000046
47 RD = BaseDecl;
48 }
49
Ken Dyck55c02582011-03-22 00:53:26 +000050 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000051}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000052
Anders Carlsson84080ec2009-09-29 03:13:20 +000053llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000054CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000055 CastExpr::path_const_iterator PathBegin,
56 CastExpr::path_const_iterator PathEnd) {
57 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000058
Ken Dyck55c02582011-03-22 00:53:26 +000059 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000060 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000062 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000063 return 0;
64
Chris Lattner2acc6e32011-07-18 04:24:23 +000065 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000066 Types.ConvertType(getContext().getPointerDiffType());
67
Ken Dyck55c02582011-03-22 00:53:26 +000068 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000069}
70
Anders Carlsson8561a862010-04-24 23:01:49 +000071/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000072/// This should only be used for (1) non-virtual bases or (2) virtual bases
73/// when the type is known to be complete (e.g. in complete destructors).
74///
75/// The object pointed to by 'This' is assumed to be non-null.
76llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000077CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78 const CXXRecordDecl *Derived,
79 const CXXRecordDecl *Base,
80 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000081 // 'this' must be a pointer (in some address space) to Derived.
82 assert(This->getType()->isPointerTy() &&
83 cast<llvm::PointerType>(This->getType())->getElementType()
84 == ConvertType(Derived));
85
86 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000087 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000088 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000089 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000090 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000091 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000092 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000093
94 // Shift and cast down to the base type.
95 // TODO: for complete types, this should be possible with a GEP.
96 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +000097 if (Offset.isPositive()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000098 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCallbff225e2010-02-16 04:15:37 +000099 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000105}
John McCallbff225e2010-02-16 04:15:37 +0000106
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000107static llvm::Value *
108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000109 CharUnits NonVirtual, llvm::Value *Virtual) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000110 llvm::Type *PtrDiffTy =
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000111 CGF.ConvertType(CGF.getContext().getPointerDiffType());
112
113 llvm::Value *NonVirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000114 if (!NonVirtual.isZero())
115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
116 NonVirtual.getQuantity());
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000117
118 llvm::Value *BaseOffset;
119 if (Virtual) {
120 if (NonVirtualOffset)
121 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
122 else
123 BaseOffset = Virtual;
124 } else
125 BaseOffset = NonVirtualOffset;
126
127 // Apply the base offset.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000128 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000129 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
130 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
131
132 return ThisPtr;
133}
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
146 // Get the virtual base.
147 if ((*Start)->isVirtual()) {
148 VBase =
149 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150 ++Start;
151 }
152
Ken Dyck55c02582011-03-22 00:53:26 +0000153 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000154 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000155 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000156
157 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000158 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000159 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000160
Ken Dyck55c02582011-03-22 00:53:26 +0000161 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000162 // Just cast back.
163 return Builder.CreateBitCast(Value, BasePtrTy);
164 }
165
166 llvm::BasicBlock *CastNull = 0;
167 llvm::BasicBlock *CastNotNull = 0;
168 llvm::BasicBlock *CastEnd = 0;
169
170 if (NullCheckValue) {
171 CastNull = createBasicBlock("cast.null");
172 CastNotNull = createBasicBlock("cast.notnull");
173 CastEnd = createBasicBlock("cast.end");
174
Anders Carlssonb9241242011-04-11 00:30:07 +0000175 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000176 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
177 EmitBlock(CastNotNull);
178 }
179
180 llvm::Value *VirtualOffset = 0;
181
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000182 if (VBase) {
183 if (Derived->hasAttr<FinalAttr>()) {
184 VirtualOffset = 0;
185
186 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
187
Ken Dyck55c02582011-03-22 00:53:26 +0000188 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
189 NonVirtualOffset += VBaseOffset;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000190 } else
191 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
192 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000193
194 // Apply the offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000195 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000196 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000197 VirtualOffset);
198
199 // Cast back.
200 Value = Builder.CreateBitCast(Value, BasePtrTy);
201
202 if (NullCheckValue) {
203 Builder.CreateBr(CastEnd);
204 EmitBlock(CastNull);
205 Builder.CreateBr(CastEnd);
206 EmitBlock(CastEnd);
207
Jay Foadbbf3bac2011-03-30 11:28:58 +0000208 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000209 PHI->addIncoming(Value, CastNotNull);
210 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
211 CastNull);
212 Value = PHI;
213 }
214
215 return Value;
216}
217
218llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000219CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000220 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000221 CastExpr::path_const_iterator PathBegin,
222 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000223 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000224 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000225
Anders Carlssona3697c92009-11-23 17:57:54 +0000226 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000227 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000228 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Anders Carlssona3697c92009-11-23 17:57:54 +0000229
Anders Carlssona552ea72010-01-31 01:43:37 +0000230 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000231 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000232
233 if (!NonVirtualOffset) {
234 // No offset, we can just cast back.
235 return Builder.CreateBitCast(Value, DerivedPtrTy);
236 }
237
Anders Carlssona3697c92009-11-23 17:57:54 +0000238 llvm::BasicBlock *CastNull = 0;
239 llvm::BasicBlock *CastNotNull = 0;
240 llvm::BasicBlock *CastEnd = 0;
241
242 if (NullCheckValue) {
243 CastNull = createBasicBlock("cast.null");
244 CastNotNull = createBasicBlock("cast.notnull");
245 CastEnd = createBasicBlock("cast.end");
246
Anders Carlssonb9241242011-04-11 00:30:07 +0000247 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000248 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
249 EmitBlock(CastNotNull);
250 }
251
Anders Carlssona552ea72010-01-31 01:43:37 +0000252 // Apply the offset.
253 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
254 Value = Builder.CreateSub(Value, NonVirtualOffset);
255 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
256
257 // Just cast.
258 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000259
260 if (NullCheckValue) {
261 Builder.CreateBr(CastEnd);
262 EmitBlock(CastNull);
263 Builder.CreateBr(CastEnd);
264 EmitBlock(CastEnd);
265
Jay Foadbbf3bac2011-03-30 11:28:58 +0000266 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000267 PHI->addIncoming(Value, CastNotNull);
268 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
269 CastNull);
270 Value = PHI;
271 }
272
273 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000274}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000275
Anders Carlssonc997d422010-01-02 01:01:18 +0000276/// GetVTTParameter - Return the VTT parameter that should be passed to a
277/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000278static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
279 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000280 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000281 // This constructor/destructor does not need a VTT parameter.
282 return 0;
283 }
284
285 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
286 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000287
Anders Carlssonc997d422010-01-02 01:01:18 +0000288 llvm::Value *VTT;
289
John McCall3b477332010-02-18 19:59:28 +0000290 uint64_t SubVTTIndex;
291
292 // If the record matches the base, this is the complete ctor/dtor
293 // variant calling the base variant in a class with virtual bases.
294 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000295 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000296 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000297 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000298 SubVTTIndex = 0;
299 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000300 const ASTRecordLayout &Layout =
301 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000302 CharUnits BaseOffset = ForVirtualBase ?
303 Layout.getVBaseClassOffset(Base) :
304 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000305
306 SubVTTIndex =
307 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000308 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
309 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000310
Anders Carlssonaf440352010-03-23 04:11:45 +0000311 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000312 // A VTT parameter was passed to the constructor, use it.
313 VTT = CGF.LoadCXXVTT();
314 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
315 } else {
316 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000317 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000318 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
319 }
320
321 return VTT;
322}
323
John McCall182ab512010-07-21 01:23:41 +0000324namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000325 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000326 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000327 const CXXRecordDecl *BaseClass;
328 bool BaseIsVirtual;
329 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
330 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000331
John McCallad346f42011-07-12 20:27:29 +0000332 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000333 const CXXRecordDecl *DerivedClass =
334 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
335
336 const CXXDestructorDecl *D = BaseClass->getDestructor();
337 llvm::Value *Addr =
338 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
339 DerivedClass, BaseClass,
340 BaseIsVirtual);
341 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000342 }
343 };
John McCall7e1dff72010-09-17 02:31:44 +0000344
345 /// A visitor which checks whether an initializer uses 'this' in a
346 /// way which requires the vtable to be properly set.
347 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
348 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
349
350 bool UsesThis;
351
352 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
353
354 // Black-list all explicit and implicit references to 'this'.
355 //
356 // Do we need to worry about external references to 'this' derived
357 // from arbitrary code? If so, then anything which runs arbitrary
358 // external code might potentially access the vtable.
359 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
360 };
361}
362
363static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
364 DynamicThisUseChecker Checker(C);
365 Checker.Visit(const_cast<Expr*>(Init));
366 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000367}
368
Anders Carlsson607d0372009-12-24 22:46:43 +0000369static void EmitBaseInitializer(CodeGenFunction &CGF,
370 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000371 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000372 CXXCtorType CtorType) {
373 assert(BaseInit->isBaseInitializer() &&
374 "Must have base initializer!");
375
376 llvm::Value *ThisPtr = CGF.LoadCXXThis();
377
378 const Type *BaseType = BaseInit->getBaseClass();
379 CXXRecordDecl *BaseClassDecl =
380 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
381
Anders Carlsson80638c52010-04-12 00:51:03 +0000382 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000383
384 // The base constructor doesn't construct virtual bases.
385 if (CtorType == Ctor_Base && isBaseVirtual)
386 return;
387
John McCall7e1dff72010-09-17 02:31:44 +0000388 // If the initializer for the base (other than the constructor
389 // itself) accesses 'this' in any way, we need to initialize the
390 // vtables.
391 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
392 CGF.InitializeVTablePointers(ClassDecl);
393
John McCallbff225e2010-02-16 04:15:37 +0000394 // We can pretend to be a complete class because it only matters for
395 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000396 llvm::Value *V =
397 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000398 BaseClassDecl,
399 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000400
John McCall7c2349b2011-08-25 20:40:09 +0000401 AggValueSlot AggSlot =
402 AggValueSlot::forAddr(V, Qualifiers(),
403 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000404 AggValueSlot::DoesNotNeedGCBarriers,
405 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000406
407 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000408
Anders Carlsson7a178512011-02-28 00:33:03 +0000409 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000410 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000411 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
412 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000413}
414
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000415static void EmitAggMemberInitializer(CodeGenFunction &CGF,
416 LValue LHS,
417 llvm::Value *ArrayIndexVar,
Sean Huntcbb67482011-01-08 20:30:50 +0000418 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000419 QualType T,
420 unsigned Index) {
421 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000422 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000423
424 llvm::Value *Dest = LHS.getAddress();
425 if (ArrayIndexVar) {
426 // If we have an array index variable, load it and use it as an offset.
427 // Then, increment the value.
428 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
429 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
430 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
431 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
432 CGF.Builder.CreateStore(Next, ArrayIndexVar);
433 }
John McCall558d2ab2010-09-15 10:14:12 +0000434
John McCallf85e1932011-06-15 23:02:42 +0000435 if (!CGF.hasAggregateLLVMType(T)) {
John McCalla07398e2011-06-16 04:16:24 +0000436 LValue lvalue = CGF.MakeAddrLValue(Dest, T);
437 CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, lvalue, false);
John McCallf85e1932011-06-15 23:02:42 +0000438 } else if (T->isAnyComplexType()) {
439 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest,
440 LHS.isVolatileQualified());
441 } else {
John McCall7c2349b2011-08-25 20:40:09 +0000442 AggValueSlot Slot =
443 AggValueSlot::forAddr(Dest, LHS.getQuals(),
444 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000445 AggValueSlot::DoesNotNeedGCBarriers,
446 AggValueSlot::IsNotAliased);
John McCallf85e1932011-06-15 23:02:42 +0000447
448 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
449 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000450
451 return;
452 }
453
454 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
455 assert(Array && "Array initialization without the array type?");
456 llvm::Value *IndexVar
457 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
458 assert(IndexVar && "Array index variable not loaded");
459
460 // Initialize this index variable to zero.
461 llvm::Value* Zero
462 = llvm::Constant::getNullValue(
463 CGF.ConvertType(CGF.getContext().getSizeType()));
464 CGF.Builder.CreateStore(Zero, IndexVar);
465
466 // Start the loop with a block that tests the condition.
467 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
468 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
469
470 CGF.EmitBlock(CondBlock);
471
472 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
473 // Generate: if (loop-index < number-of-elements) fall to the loop body,
474 // otherwise, go to the block after the for-loop.
475 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000476 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000477 llvm::Value *NumElementsPtr =
478 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000479 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
480 "isless");
481
482 // If the condition is true, execute the body.
483 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
484
485 CGF.EmitBlock(ForBody);
486 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
487
488 {
John McCallf1549f62010-07-06 01:34:17 +0000489 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000490
491 // Inside the loop body recurse to emit the inner loop or, eventually, the
492 // constructor call.
493 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
494 Array->getElementType(), Index + 1);
495 }
496
497 CGF.EmitBlock(ContinueBlock);
498
499 // Emit the increment of the loop counter.
500 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
501 Counter = CGF.Builder.CreateLoad(IndexVar);
502 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
503 CGF.Builder.CreateStore(NextVal, IndexVar);
504
505 // Finally, branch back up to the condition for the next iteration.
506 CGF.EmitBranch(CondBlock);
507
508 // Emit the fall-through block.
509 CGF.EmitBlock(AfterFor, true);
510}
John McCall182ab512010-07-21 01:23:41 +0000511
512namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000513 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000514 FieldDecl *Field;
515 CXXDestructorDecl *Dtor;
516
517 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
518 : Field(Field), Dtor(Dtor) {}
519
John McCallad346f42011-07-12 20:27:29 +0000520 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall182ab512010-07-21 01:23:41 +0000521 // FIXME: Is this OK for C++0x delegating constructors?
522 llvm::Value *ThisPtr = CGF.LoadCXXThis();
523 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
524
525 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
526 LHS.getAddress());
527 }
528 };
529}
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000530
531static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
532 bool Moving) {
533 return Moving ? Record->hasTrivialMoveConstructor() :
534 Record->hasTrivialCopyConstructor();
535}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000536
Anders Carlsson607d0372009-12-24 22:46:43 +0000537static void EmitMemberInitializer(CodeGenFunction &CGF,
538 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000539 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000540 const CXXConstructorDecl *Constructor,
541 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000542 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000543 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000544 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000545
546 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000547 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000548 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
549
550 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000551 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000552
Anders Carlsson607d0372009-12-24 22:46:43 +0000553 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000554 if (MemberInit->isIndirectMemberInitializer()) {
555 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
556 MemberInit->getIndirectMember(), 0);
557 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000558 } else {
559 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000560 }
561
John McCall082aade2011-09-15 01:54:21 +0000562 if (!CGF.hasAggregateLLVMType(Field->getType())) {
John McCallf85e1932011-06-15 23:02:42 +0000563 if (LHS.isSimple()) {
John McCalla07398e2011-06-16 04:16:24 +0000564 CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000565 } else {
566 RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
John McCall545d9962011-06-25 02:11:03 +0000567 CGF.EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000568 }
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000569 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
570 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000571 LHS.isVolatileQualified());
572 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000573 llvm::Value *ArrayIndexVar = 0;
574 const ConstantArrayType *Array
575 = CGF.getContext().getAsConstantArrayType(FieldType);
Douglas Gregorb681fb12011-09-22 15:15:51 +0000576 if (Array && Constructor->isCopyOrMoveConstructor()) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000577 llvm::Type *SizeTy
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000578 = CGF.ConvertType(CGF.getContext().getSizeType());
579
580 // The LHS is a pointer to the first object we'll be constructing, as
581 // a flat array.
582 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Chris Lattner2acc6e32011-07-18 04:24:23 +0000583 llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000584 BasePtr = llvm::PointerType::getUnqual(BasePtr);
585 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
586 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000587 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000588
589 // Create an array index that will be used to walk over all of the
590 // objects we're constructing.
591 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
592 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
593 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
594
John McCallf85e1932011-06-15 23:02:42 +0000595 // If we are copying an array of PODs or classes with trivial copy
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000596 // constructors, perform a single aggregate copy.
John McCallf85e1932011-06-15 23:02:42 +0000597 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
598 if (BaseElementTy.isPODType(CGF.getContext()) ||
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000599 (Record && hasTrivialCopyOrMoveConstructor(Record,
600 Constructor->isMoveConstructor()))) {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000601 // Find the source pointer. We knows it's the last argument because
602 // we know we're in a copy constructor.
603 unsigned SrcArgIndex = Args.size() - 1;
604 llvm::Value *SrcPtr
John McCalld26bc762011-03-09 04:27:21 +0000605 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000606 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
607
608 // Copy the aggregate.
609 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
610 LHS.isVolatileQualified());
611 return;
612 }
613
614 // Emit the block variables for the array indices, if any.
615 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000616 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000617 }
618
619 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000620
Anders Carlsson7a178512011-02-28 00:33:03 +0000621 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000622 return;
623
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000624 // FIXME: If we have an array of classes w/ non-trivial destructors,
625 // we need to destroy in reverse order of construction along the exception
626 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000627 const RecordType *RT = FieldType->getAs<RecordType>();
628 if (!RT)
629 return;
630
631 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000632 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000633 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
634 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000635 }
636}
637
John McCallc0bf4622010-02-23 00:48:20 +0000638/// Checks whether the given constructor is a valid subject for the
639/// complete-to-base constructor delegation optimization, i.e.
640/// emitting the complete constructor as a simple call to the base
641/// constructor.
642static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
643
644 // Currently we disable the optimization for classes with virtual
645 // bases because (1) the addresses of parameter variables need to be
646 // consistent across all initializers but (2) the delegate function
647 // call necessarily creates a second copy of the parameter variable.
648 //
649 // The limiting example (purely theoretical AFAIK):
650 // struct A { A(int &c) { c++; } };
651 // struct B : virtual A {
652 // B(int count) : A(count) { printf("%d\n", count); }
653 // };
654 // ...although even this example could in principle be emitted as a
655 // delegation since the address of the parameter doesn't escape.
656 if (Ctor->getParent()->getNumVBases()) {
657 // TODO: white-list trivial vbase initializers. This case wouldn't
658 // be subject to the restrictions below.
659
660 // TODO: white-list cases where:
661 // - there are no non-reference parameters to the constructor
662 // - the initializers don't access any non-reference parameters
663 // - the initializers don't take the address of non-reference
664 // parameters
665 // - etc.
666 // If we ever add any of the above cases, remember that:
667 // - function-try-blocks will always blacklist this optimization
668 // - we need to perform the constructor prologue and cleanup in
669 // EmitConstructorBody.
670
671 return false;
672 }
673
674 // We also disable the optimization for variadic functions because
675 // it's impossible to "re-pass" varargs.
676 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
677 return false;
678
Sean Hunt059ce0d2011-05-01 07:04:31 +0000679 // FIXME: Decide if we can do a delegation of a delegating constructor.
680 if (Ctor->isDelegatingConstructor())
681 return false;
682
John McCallc0bf4622010-02-23 00:48:20 +0000683 return true;
684}
685
John McCall9fc6a772010-02-19 09:25:03 +0000686/// EmitConstructorBody - Emits the body of the current constructor.
687void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
688 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
689 CXXCtorType CtorType = CurGD.getCtorType();
690
John McCallc0bf4622010-02-23 00:48:20 +0000691 // Before we go any further, try the complete->base constructor
692 // delegation optimization.
693 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000694 if (CGDebugInfo *DI = getDebugInfo())
695 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000696 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
697 return;
698 }
699
John McCall9fc6a772010-02-19 09:25:03 +0000700 Stmt *Body = Ctor->getBody();
701
John McCallc0bf4622010-02-23 00:48:20 +0000702 // Enter the function-try-block before the constructor prologue if
703 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000704 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000705 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000706 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000707
John McCallf1549f62010-07-06 01:34:17 +0000708 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000709
John McCallc0bf4622010-02-23 00:48:20 +0000710 // Emit the constructor prologue, i.e. the base and member
711 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000712 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000713
714 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000715 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000716 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
717 else if (Body)
718 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000719
720 // Emit any cleanup blocks associated with the member or base
721 // initializers, which includes (along the exceptional path) the
722 // destructors for those members and bases that were fully
723 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000724 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000725
John McCallc0bf4622010-02-23 00:48:20 +0000726 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000727 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000728}
729
Anders Carlsson607d0372009-12-24 22:46:43 +0000730/// EmitCtorPrologue - This routine generates necessary code to initialize
731/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000732void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000733 CXXCtorType CtorType,
734 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000735 if (CD->isDelegatingConstructor())
736 return EmitDelegatingCXXConstructorCall(CD, Args);
737
Anders Carlsson607d0372009-12-24 22:46:43 +0000738 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000739
Chris Lattner5f9e2722011-07-23 10:55:15 +0000740 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000741
Anders Carlsson607d0372009-12-24 22:46:43 +0000742 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
743 E = CD->init_end();
744 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000745 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000746
Sean Huntd49bd552011-05-03 20:19:28 +0000747 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000748 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000749 } else {
750 assert(Member->isAnyMemberInitializer() &&
751 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000752 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000753 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000754 }
755
Anders Carlsson603d6d12010-03-28 21:07:49 +0000756 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000757
John McCallf1549f62010-07-06 01:34:17 +0000758 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000759 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000760}
761
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000762static bool
763FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
764
765static bool
766HasTrivialDestructorBody(ASTContext &Context,
767 const CXXRecordDecl *BaseClassDecl,
768 const CXXRecordDecl *MostDerivedClassDecl)
769{
770 // If the destructor is trivial we don't have to check anything else.
771 if (BaseClassDecl->hasTrivialDestructor())
772 return true;
773
774 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
775 return false;
776
777 // Check fields.
778 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
779 E = BaseClassDecl->field_end(); I != E; ++I) {
780 const FieldDecl *Field = *I;
781
782 if (!FieldHasTrivialDestructorBody(Context, Field))
783 return false;
784 }
785
786 // Check non-virtual bases.
787 for (CXXRecordDecl::base_class_const_iterator I =
788 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
789 I != E; ++I) {
790 if (I->isVirtual())
791 continue;
792
793 const CXXRecordDecl *NonVirtualBase =
794 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
795 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
796 MostDerivedClassDecl))
797 return false;
798 }
799
800 if (BaseClassDecl == MostDerivedClassDecl) {
801 // Check virtual bases.
802 for (CXXRecordDecl::base_class_const_iterator I =
803 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
804 I != E; ++I) {
805 const CXXRecordDecl *VirtualBase =
806 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
807 if (!HasTrivialDestructorBody(Context, VirtualBase,
808 MostDerivedClassDecl))
809 return false;
810 }
811 }
812
813 return true;
814}
815
816static bool
817FieldHasTrivialDestructorBody(ASTContext &Context,
818 const FieldDecl *Field)
819{
820 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
821
822 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
823 if (!RT)
824 return true;
825
826 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
827 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
828}
829
Anders Carlssonffb945f2011-05-14 23:26:09 +0000830/// CanSkipVTablePointerInitialization - Check whether we need to initialize
831/// any vtable pointers before calling this destructor.
832static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000833 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000834 if (!Dtor->hasTrivialBody())
835 return false;
836
837 // Check the fields.
838 const CXXRecordDecl *ClassDecl = Dtor->getParent();
839 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
840 E = ClassDecl->field_end(); I != E; ++I) {
841 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000842
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000843 if (!FieldHasTrivialDestructorBody(Context, Field))
844 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000845 }
846
847 return true;
848}
849
John McCall9fc6a772010-02-19 09:25:03 +0000850/// EmitDestructorBody - Emits the body of the current destructor.
851void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
852 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
853 CXXDtorType DtorType = CurGD.getDtorType();
854
John McCall50da2ca2010-07-21 05:30:47 +0000855 // The call to operator delete in a deleting destructor happens
856 // outside of the function-try-block, which means it's always
857 // possible to delegate the destructor body to the complete
858 // destructor. Do so.
859 if (DtorType == Dtor_Deleting) {
860 EnterDtorCleanups(Dtor, Dtor_Deleting);
861 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
862 LoadCXXThis());
863 PopCleanupBlock();
864 return;
865 }
866
John McCall9fc6a772010-02-19 09:25:03 +0000867 Stmt *Body = Dtor->getBody();
868
869 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000870 // anything else.
871 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000872 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000873 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000874
John McCall50da2ca2010-07-21 05:30:47 +0000875 // Enter the epilogue cleanups.
876 RunCleanupsScope DtorEpilogue(*this);
877
John McCall9fc6a772010-02-19 09:25:03 +0000878 // If this is the complete variant, just invoke the base variant;
879 // the epilogue will destruct the virtual bases. But we can't do
880 // this optimization if the body is a function-try-block, because
881 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000882 switch (DtorType) {
883 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
884
885 case Dtor_Complete:
886 // Enter the cleanup scopes for virtual bases.
887 EnterDtorCleanups(Dtor, Dtor_Complete);
888
889 if (!isTryBody) {
890 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
891 LoadCXXThis());
892 break;
893 }
894 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000895
John McCall50da2ca2010-07-21 05:30:47 +0000896 case Dtor_Base:
897 // Enter the cleanup scopes for fields and non-virtual bases.
898 EnterDtorCleanups(Dtor, Dtor_Base);
899
900 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000901 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
902 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000903
904 if (isTryBody)
905 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
906 else if (Body)
907 EmitStmt(Body);
908 else {
909 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
910 // nothing to do besides what's in the epilogue
911 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000912 // -fapple-kext must inline any call to this dtor into
913 // the caller's body.
914 if (getContext().getLangOptions().AppleKext)
915 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000916 break;
John McCall9fc6a772010-02-19 09:25:03 +0000917 }
918
John McCall50da2ca2010-07-21 05:30:47 +0000919 // Jump out through the epilogue cleanups.
920 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000921
922 // Exit the try if applicable.
923 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000924 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000925}
926
John McCall50da2ca2010-07-21 05:30:47 +0000927namespace {
928 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000929 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000930 CallDtorDelete() {}
931
John McCallad346f42011-07-12 20:27:29 +0000932 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000933 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
934 const CXXRecordDecl *ClassDecl = Dtor->getParent();
935 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
936 CGF.getContext().getTagDeclType(ClassDecl));
937 }
938 };
939
John McCall9928c482011-07-12 16:41:08 +0000940 class DestroyField : public EHScopeStack::Cleanup {
941 const FieldDecl *field;
942 CodeGenFunction::Destroyer &destroyer;
943 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +0000944
John McCall9928c482011-07-12 16:41:08 +0000945 public:
946 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
947 bool useEHCleanupForArray)
948 : field(field), destroyer(*destroyer),
949 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +0000950
John McCallad346f42011-07-12 20:27:29 +0000951 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000952 // Find the address of the field.
953 llvm::Value *thisValue = CGF.LoadCXXThis();
954 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
955 assert(LV.isSimple());
956
957 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000958 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +0000959 }
960 };
961}
962
Anders Carlsson607d0372009-12-24 22:46:43 +0000963/// EmitDtorEpilogue - Emit all code that comes at the end of class's
964/// destructor. This is to call destructors on members and base classes
965/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000966void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
967 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000968 assert(!DD->isTrivial() &&
969 "Should not emit dtor epilogue for trivial dtor!");
970
John McCall50da2ca2010-07-21 05:30:47 +0000971 // The deleting-destructor phase just needs to call the appropriate
972 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000973 if (DtorType == Dtor_Deleting) {
974 assert(DD->getOperatorDelete() &&
975 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000976 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000977 return;
978 }
979
John McCall50da2ca2010-07-21 05:30:47 +0000980 const CXXRecordDecl *ClassDecl = DD->getParent();
981
Richard Smith416f63e2011-09-18 12:11:43 +0000982 // Unions have no bases and do not call field destructors.
983 if (ClassDecl->isUnion())
984 return;
985
John McCall50da2ca2010-07-21 05:30:47 +0000986 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000987 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000988
989 // We push them in the forward order so that they'll be popped in
990 // the reverse order.
991 for (CXXRecordDecl::base_class_const_iterator I =
992 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000993 I != E; ++I) {
994 const CXXBaseSpecifier &Base = *I;
995 CXXRecordDecl *BaseClassDecl
996 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
997
998 // Ignore trivial destructors.
999 if (BaseClassDecl->hasTrivialDestructor())
1000 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001001
John McCall1f0fca52010-07-21 07:22:38 +00001002 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1003 BaseClassDecl,
1004 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001005 }
John McCall50da2ca2010-07-21 05:30:47 +00001006
John McCall3b477332010-02-18 19:59:28 +00001007 return;
1008 }
1009
1010 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001011
1012 // Destroy non-virtual bases.
1013 for (CXXRecordDecl::base_class_const_iterator I =
1014 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1015 const CXXBaseSpecifier &Base = *I;
1016
1017 // Ignore virtual bases.
1018 if (Base.isVirtual())
1019 continue;
1020
1021 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1022
1023 // Ignore trivial destructors.
1024 if (BaseClassDecl->hasTrivialDestructor())
1025 continue;
John McCall3b477332010-02-18 19:59:28 +00001026
John McCall1f0fca52010-07-21 07:22:38 +00001027 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1028 BaseClassDecl,
1029 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001030 }
1031
1032 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001033 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001034 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1035 E = ClassDecl->field_end(); I != E; ++I) {
John McCall9928c482011-07-12 16:41:08 +00001036 const FieldDecl *field = *I;
1037 QualType type = field->getType();
1038 QualType::DestructionKind dtorKind = type.isDestructedType();
1039 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001040
John McCall9928c482011-07-12 16:41:08 +00001041 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1042 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1043 getDestroyer(dtorKind),
1044 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001045 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001046}
1047
John McCallc3c07662011-07-13 06:10:41 +00001048/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1049/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001050///
John McCallc3c07662011-07-13 06:10:41 +00001051/// \param ctor the constructor to call for each element
1052/// \param argBegin,argEnd the arguments to evaluate and pass to the
1053/// constructor
1054/// \param arrayType the type of the array to initialize
1055/// \param arrayBegin an arrayType*
1056/// \param zeroInitialize true if each element should be
1057/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001058void
John McCallc3c07662011-07-13 06:10:41 +00001059CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1060 const ConstantArrayType *arrayType,
1061 llvm::Value *arrayBegin,
1062 CallExpr::const_arg_iterator argBegin,
1063 CallExpr::const_arg_iterator argEnd,
1064 bool zeroInitialize) {
1065 QualType elementType;
1066 llvm::Value *numElements =
1067 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001068
John McCallc3c07662011-07-13 06:10:41 +00001069 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1070 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001071}
1072
John McCallc3c07662011-07-13 06:10:41 +00001073/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1074/// constructor for each of several members of an array.
1075///
1076/// \param ctor the constructor to call for each element
1077/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001078/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001079/// \param argBegin,argEnd the arguments to evaluate and pass to the
1080/// constructor
1081/// \param arrayBegin a T*, where T is the type constructed by ctor
1082/// \param zeroInitialize true if each element should be
1083/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001084void
John McCallc3c07662011-07-13 06:10:41 +00001085CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1086 llvm::Value *numElements,
1087 llvm::Value *arrayBegin,
1088 CallExpr::const_arg_iterator argBegin,
1089 CallExpr::const_arg_iterator argEnd,
1090 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001091
1092 // It's legal for numElements to be zero. This can happen both
1093 // dynamically, because x can be zero in 'new A[x]', and statically,
1094 // because of GCC extensions that permit zero-length arrays. There
1095 // are probably legitimate places where we could assume that this
1096 // doesn't happen, but it's not clear that it's worth it.
1097 llvm::BranchInst *zeroCheckBranch = 0;
1098
1099 // Optimize for a constant count.
1100 llvm::ConstantInt *constantCount
1101 = dyn_cast<llvm::ConstantInt>(numElements);
1102 if (constantCount) {
1103 // Just skip out if the constant count is zero.
1104 if (constantCount->isZero()) return;
1105
1106 // Otherwise, emit the check.
1107 } else {
1108 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1109 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1110 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1111 EmitBlock(loopBB);
1112 }
1113
John McCallc3c07662011-07-13 06:10:41 +00001114 // Find the end of the array.
1115 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1116 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001117
John McCallc3c07662011-07-13 06:10:41 +00001118 // Enter the loop, setting up a phi for the current location to initialize.
1119 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1120 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1121 EmitBlock(loopBB);
1122 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1123 "arrayctor.cur");
1124 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001125
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001126 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001127
1128 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001129
Douglas Gregor59174c02010-07-21 01:10:17 +00001130 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001131 if (zeroInitialize)
1132 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001133
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001134 // C++ [class.temporary]p4:
1135 // There are two contexts in which temporaries are destroyed at a different
1136 // point than the end of the full-expression. The first context is when a
1137 // default constructor is called to initialize an element of an array.
1138 // If the constructor has one or more default arguments, the destruction of
1139 // every temporary created in a default argument expression is sequenced
1140 // before the construction of the next array element, if any.
1141
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001142 {
John McCallf1549f62010-07-06 01:34:17 +00001143 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001144
John McCallc3c07662011-07-13 06:10:41 +00001145 // Evaluate the constructor and its arguments in a regular
1146 // partial-destroy cleanup.
1147 if (getLangOptions().Exceptions &&
1148 !ctor->getParent()->hasTrivialDestructor()) {
1149 Destroyer *destroyer = destroyCXXObject;
1150 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1151 }
1152
1153 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1154 cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001155 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001156
John McCallc3c07662011-07-13 06:10:41 +00001157 // Go to the next element.
1158 llvm::Value *next =
1159 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1160 "arrayctor.next");
1161 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001162
John McCallc3c07662011-07-13 06:10:41 +00001163 // Check whether that's the end of the loop.
1164 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1165 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1166 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001167
John McCalldd376ca2011-07-13 07:37:11 +00001168 // Patch the earlier check to skip over the loop.
1169 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1170
John McCallc3c07662011-07-13 06:10:41 +00001171 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001172}
1173
John McCallbdc4d802011-07-09 01:37:26 +00001174void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1175 llvm::Value *addr,
1176 QualType type) {
1177 const RecordType *rtype = type->castAs<RecordType>();
1178 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1179 const CXXDestructorDecl *dtor = record->getDestructor();
1180 assert(!dtor->isTrivial());
1181 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1182 addr);
1183}
1184
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001185void
1186CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001187 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001188 llvm::Value *This,
1189 CallExpr::const_arg_iterator ArgBeg,
1190 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001191
1192 CGDebugInfo *DI = getDebugInfo();
1193 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1194 // If debug info for this class has been emitted then this is the right time
1195 // to do so.
1196 const CXXRecordDecl *Parent = D->getParent();
1197 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1198 Parent->getLocation());
1199 }
1200
John McCall8b6bbeb2010-02-06 00:25:16 +00001201 if (D->isTrivial()) {
1202 if (ArgBeg == ArgEnd) {
1203 // Trivial default constructor, no codegen required.
1204 assert(D->isDefaultConstructor() &&
1205 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001206 return;
1207 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001208
1209 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001210 assert(D->isCopyOrMoveConstructor() &&
1211 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001212
John McCall8b6bbeb2010-02-06 00:25:16 +00001213 const Expr *E = (*ArgBeg);
1214 QualType Ty = E->getType();
1215 llvm::Value *Src = EmitLValue(E).getAddress();
1216 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001217 return;
1218 }
1219
Anders Carlsson314e6222010-05-02 23:33:10 +00001220 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001221 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1222
Anders Carlssonc997d422010-01-02 01:01:18 +00001223 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001224}
1225
John McCallc0bf4622010-02-23 00:48:20 +00001226void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001227CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1228 llvm::Value *This, llvm::Value *Src,
1229 CallExpr::const_arg_iterator ArgBeg,
1230 CallExpr::const_arg_iterator ArgEnd) {
1231 if (D->isTrivial()) {
1232 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001233 assert(D->isCopyOrMoveConstructor() &&
1234 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001235 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1236 return;
1237 }
1238 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1239 clang::Ctor_Complete);
1240 assert(D->isInstance() &&
1241 "Trying to emit a member call expr on a static method!");
1242
1243 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1244
1245 CallArgList Args;
1246
1247 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001248 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001249
1250
1251 // Push the src ptr.
1252 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001253 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001254 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001255 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001256
1257 // Skip over first argument (Src).
1258 ++ArgBeg;
1259 CallExpr::const_arg_iterator Arg = ArgBeg;
1260 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1261 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1262 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001263 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001264 }
1265 // Either we've emitted all the call args, or we have a call to a
1266 // variadic function.
1267 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1268 "Extra arguments in non-variadic function!");
1269 // If we still have any arguments, emit them using the type of the argument.
1270 for (; Arg != ArgEnd; ++Arg) {
1271 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001272 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001273 }
1274
Eli Friedmanc55db3b2011-08-09 17:38:12 +00001275 EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
1276 ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001277}
1278
1279void
John McCallc0bf4622010-02-23 00:48:20 +00001280CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1281 CXXCtorType CtorType,
1282 const FunctionArgList &Args) {
1283 CallArgList DelegateArgs;
1284
1285 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1286 assert(I != E && "no parameters to constructor");
1287
1288 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001289 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001290 ++I;
1291
1292 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001293 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1294 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001295 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001296 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001297
Anders Carlssonaf440352010-03-23 04:11:45 +00001298 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001299 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001300 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001301 ++I;
1302 }
1303 }
1304
1305 // Explicit arguments.
1306 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001307 const VarDecl *param = *I;
1308 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001309 }
1310
1311 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1312 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1313 ReturnValueSlot(), DelegateArgs, Ctor);
1314}
1315
Sean Huntb76af9c2011-05-03 23:05:34 +00001316namespace {
1317 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1318 const CXXDestructorDecl *Dtor;
1319 llvm::Value *Addr;
1320 CXXDtorType Type;
1321
1322 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1323 CXXDtorType Type)
1324 : Dtor(D), Addr(Addr), Type(Type) {}
1325
John McCallad346f42011-07-12 20:27:29 +00001326 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001327 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1328 Addr);
1329 }
1330 };
1331}
1332
Sean Hunt059ce0d2011-05-01 07:04:31 +00001333void
1334CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1335 const FunctionArgList &Args) {
1336 assert(Ctor->isDelegatingConstructor());
1337
1338 llvm::Value *ThisPtr = LoadCXXThis();
1339
John McCallf85e1932011-06-15 23:02:42 +00001340 AggValueSlot AggSlot =
John McCall7c2349b2011-08-25 20:40:09 +00001341 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
1342 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001343 AggValueSlot::DoesNotNeedGCBarriers,
1344 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001345
1346 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001347
Sean Huntb76af9c2011-05-03 23:05:34 +00001348 const CXXRecordDecl *ClassDecl = Ctor->getParent();
1349 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1350 CXXDtorType Type =
1351 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1352
1353 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1354 ClassDecl->getDestructor(),
1355 ThisPtr, Type);
1356 }
1357}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001358
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001359void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1360 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001361 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001362 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001363 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1364 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001365 llvm::Value *Callee = 0;
1366 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001367 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1368 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001369
1370 if (!Callee)
1371 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001372
Anders Carlssonc997d422010-01-02 01:01:18 +00001373 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001374}
1375
John McCall291ae942010-07-21 01:41:18 +00001376namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001377 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001378 const CXXDestructorDecl *Dtor;
1379 llvm::Value *Addr;
1380
1381 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1382 : Dtor(D), Addr(Addr) {}
1383
John McCallad346f42011-07-12 20:27:29 +00001384 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001385 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1386 /*ForVirtualBase=*/false, Addr);
1387 }
1388 };
1389}
1390
John McCall81407d42010-07-21 06:29:51 +00001391void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1392 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001393 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001394}
1395
John McCallf1549f62010-07-06 01:34:17 +00001396void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1397 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1398 if (!ClassDecl) return;
1399 if (ClassDecl->hasTrivialDestructor()) return;
1400
1401 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001402 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001403 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001404}
1405
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001406llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001407CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1408 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001409 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001410 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001411 CharUnits VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001412 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001413
1414 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001415 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1416 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001417 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001418 ConvertType(getContext().getPointerDiffType());
1419
1420 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1421 PtrDiffTy->getPointerTo());
1422
1423 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1424
1425 return VBaseOffset;
1426}
1427
Anders Carlssond103f9f2010-03-28 19:40:00 +00001428void
1429CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001430 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001431 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001432 llvm::Constant *VTable,
1433 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001434 const CXXRecordDecl *RD = Base.getBase();
1435
Anders Carlssond103f9f2010-03-28 19:40:00 +00001436 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001437 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001438
Anders Carlssonc83f1062010-03-29 01:08:49 +00001439 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001440 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001441 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001442 // Get the secondary vpointer index.
1443 uint64_t VirtualPointerIndex =
1444 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1445
1446 /// Load the VTT.
1447 llvm::Value *VTT = LoadCXXVTT();
1448 if (VirtualPointerIndex)
1449 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1450
1451 // And load the address point from the VTT.
1452 VTableAddressPoint = Builder.CreateLoad(VTT);
1453 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001454 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001455 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001456 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001457 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001458
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001459 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001460 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001461 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001462
1463 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1464 // We need to use the virtual base offset offset because the virtual base
1465 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001466 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1467 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001468 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001469 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001470 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001471 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001472 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001473
1474 // Apply the offsets.
1475 llvm::Value *VTableField = LoadCXXThis();
1476
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001477 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001478 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1479 NonVirtualOffset,
1480 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001481
Anders Carlssond103f9f2010-03-28 19:40:00 +00001482 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001483 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001484 VTableAddressPoint->getType()->getPointerTo();
1485 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1486 Builder.CreateStore(VTableAddressPoint, VTableField);
1487}
1488
Anders Carlsson603d6d12010-03-28 21:07:49 +00001489void
1490CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001491 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001492 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001493 bool BaseIsNonVirtualPrimaryBase,
1494 llvm::Constant *VTable,
1495 const CXXRecordDecl *VTableClass,
1496 VisitedVirtualBasesSetTy& VBases) {
1497 // If this base is a non-virtual primary base the address point has already
1498 // been set.
1499 if (!BaseIsNonVirtualPrimaryBase) {
1500 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001501 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1502 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001503 }
1504
1505 const CXXRecordDecl *RD = Base.getBase();
1506
1507 // Traverse bases.
1508 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1509 E = RD->bases_end(); I != E; ++I) {
1510 CXXRecordDecl *BaseDecl
1511 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1512
1513 // Ignore classes without a vtable.
1514 if (!BaseDecl->isDynamicClass())
1515 continue;
1516
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001517 CharUnits BaseOffset;
1518 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001519 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001520
1521 if (I->isVirtual()) {
1522 // Check if we've visited this virtual base before.
1523 if (!VBases.insert(BaseDecl))
1524 continue;
1525
1526 const ASTRecordLayout &Layout =
1527 getContext().getASTRecordLayout(VTableClass);
1528
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001529 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1530 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001531 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001532 } else {
1533 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1534
Ken Dyck4230d522011-03-24 01:21:01 +00001535 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001536 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001537 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001538 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001539 }
1540
Ken Dyck4230d522011-03-24 01:21:01 +00001541 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001542 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001543 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001544 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001545 VTable, VTableClass, VBases);
1546 }
1547}
1548
1549void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1550 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001551 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001552 return;
1553
Anders Carlsson07036902010-03-26 04:39:42 +00001554 // Get the VTable.
1555 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001556
Anders Carlsson603d6d12010-03-28 21:07:49 +00001557 // Initialize the vtable pointers for this class and all of its bases.
1558 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001559 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1560 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001561 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001562 /*BaseIsNonVirtualPrimaryBase=*/false,
1563 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001564}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001565
1566llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001567 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001568 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1569 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1570}
Anders Carlssona2447e02011-05-08 20:32:23 +00001571
1572static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1573 const Expr *E = Base;
1574
1575 while (true) {
1576 E = E->IgnoreParens();
1577 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1578 if (CE->getCastKind() == CK_DerivedToBase ||
1579 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1580 CE->getCastKind() == CK_NoOp) {
1581 E = CE->getSubExpr();
1582 continue;
1583 }
1584 }
1585
1586 break;
1587 }
1588
1589 QualType DerivedType = E->getType();
1590 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1591 DerivedType = PTy->getPointeeType();
1592
1593 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1594}
1595
1596// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1597// quite what we want.
1598static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1599 while (true) {
1600 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1601 E = PE->getSubExpr();
1602 continue;
1603 }
1604
1605 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1606 if (CE->getCastKind() == CK_NoOp) {
1607 E = CE->getSubExpr();
1608 continue;
1609 }
1610 }
1611 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1612 if (UO->getOpcode() == UO_Extension) {
1613 E = UO->getSubExpr();
1614 continue;
1615 }
1616 }
1617 return E;
1618 }
1619}
1620
1621/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1622/// function call on the given expr can be devirtualized.
1623/// expr can be devirtualized.
1624static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1625 const CXXMethodDecl *MD) {
1626 // If the most derived class is marked final, we know that no subclass can
1627 // override this member function and so we can devirtualize it. For example:
1628 //
1629 // struct A { virtual void f(); }
1630 // struct B final : A { };
1631 //
1632 // void f(B *b) {
1633 // b->f();
1634 // }
1635 //
1636 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1637 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1638 return true;
1639
1640 // If the member function is marked 'final', we know that it can't be
1641 // overridden and can therefore devirtualize it.
1642 if (MD->hasAttr<FinalAttr>())
1643 return true;
1644
1645 // Similarly, if the class itself is marked 'final' it can't be overridden
1646 // and we can therefore devirtualize the member function call.
1647 if (MD->getParent()->hasAttr<FinalAttr>())
1648 return true;
1649
1650 Base = skipNoOpCastsAndParens(Base);
1651 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1652 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1653 // This is a record decl. We know the type and can devirtualize it.
1654 return VD->getType()->isRecordType();
1655 }
1656
1657 return false;
1658 }
1659
1660 // We can always devirtualize calls on temporary object expressions.
1661 if (isa<CXXConstructExpr>(Base))
1662 return true;
1663
1664 // And calls on bound temporaries.
1665 if (isa<CXXBindTemporaryExpr>(Base))
1666 return true;
1667
1668 // Check if this is a call expr that returns a record type.
1669 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1670 return CE->getCallReturnType()->isRecordType();
1671
1672 // We can't devirtualize the call.
1673 return false;
1674}
1675
1676static bool UseVirtualCall(ASTContext &Context,
1677 const CXXOperatorCallExpr *CE,
1678 const CXXMethodDecl *MD) {
1679 if (!MD->isVirtual())
1680 return false;
1681
1682 // When building with -fapple-kext, all calls must go through the vtable since
1683 // the kernel linker can do runtime patching of vtables.
1684 if (Context.getLangOptions().AppleKext)
1685 return true;
1686
1687 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1688}
1689
1690llvm::Value *
1691CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1692 const CXXMethodDecl *MD,
1693 llvm::Value *This) {
1694 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001695 llvm::Type *Ty =
Anders Carlssona2447e02011-05-08 20:32:23 +00001696 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1697 FPT->isVariadic());
1698
1699 if (UseVirtualCall(getContext(), E, MD))
1700 return BuildVirtualCall(MD, This, Ty);
1701
1702 return CGM.GetAddrOfFunction(MD, Ty);
1703}