blob: 8bdfbf1231eb6ad3c7cd497fe58bc2491a399e2a [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson9a57c5a2009-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 Pateld76c1db2010-08-11 21:04:37 +000014#include "CGDebugInfo.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000015#include "CodeGenFunction.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000016#include "clang/AST/CXXInheritance.h"
John McCall769250e2010-09-17 02:31:44 +000017#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000018#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000019#include "clang/AST/StmtCXX.h"
Devang Patelb6ed3692011-02-22 20:55:26 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000021
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000022using namespace clang;
23using namespace CodeGen;
24
Ken Dycka1a4ae32011-03-22 00:53:26 +000025static CharUnits
Anders Carlssond829a022010-04-24 21:06:20 +000026ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27 const CXXRecordDecl *DerivedClass,
John McCallcf142162010-08-07 06:22:56 +000028 CastExpr::path_const_iterator Start,
29 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +000030 CharUnits Offset = CharUnits::Zero();
Anders Carlssond829a022010-04-24 21:06:20 +000031
32 const CXXRecordDecl *RD = DerivedClass;
33
John McCallcf142162010-08-07 06:22:56 +000034 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-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 Dycka1a4ae32011-03-22 00:53:26 +000045 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlssond829a022010-04-24 21:06:20 +000046
47 RD = BaseDecl;
48 }
49
Ken Dycka1a4ae32011-03-22 00:53:26 +000050 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +000051}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000052
Anders Carlsson9150a2a2009-09-29 03:13:20 +000053llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000054CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-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 Carlsson8a64c1c2010-04-24 21:23:59 +000058
Ken Dycka1a4ae32011-03-22 00:53:26 +000059 CharUnits Offset =
John McCallcf142162010-08-07 06:22:56 +000060 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61 PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +000062 if (Offset.isZero())
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000063 return 0;
64
Chris Lattner2192fe52011-07-18 04:24:23 +000065 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000066 Types.ConvertType(getContext().getPointerDiffType());
67
Ken Dycka1a4ae32011-03-22 00:53:26 +000068 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +000069}
70
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000071/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-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 Carlssonc4ba0cd2010-04-24 23:01:49 +000077CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78 const CXXRecordDecl *Derived,
79 const CXXRecordDecl *Base,
80 bool BaseIsVirtual) {
John McCall6ce74722010-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 Dyck6aa767c2011-03-22 01:21:15 +000087 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +000088 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000089 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +000090 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000091 else
Ken Dyck6aa767c2011-03-22 01:21:15 +000092 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-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 Dyck6aa767c2011-03-22 01:21:15 +000097 if (Offset.isPositive()) {
Chris Lattner2192fe52011-07-18 04:24:23 +000098 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
John McCall6ce74722010-02-16 04:15:37 +000099 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +0000100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000105}
John McCall6ce74722010-02-16 04:15:37 +0000106
Anders Carlsson53cebd12010-04-20 16:03:35 +0000107static llvm::Value *
108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000109 CharUnits NonVirtual, llvm::Value *Virtual) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000110 llvm::Type *PtrDiffTy =
Anders Carlsson53cebd12010-04-20 16:03:35 +0000111 CGF.ConvertType(CGF.getContext().getPointerDiffType());
112
113 llvm::Value *NonVirtualOffset = 0;
Ken Dyckcfc332c2011-03-23 00:45:26 +0000114 if (!NonVirtual.isZero())
115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
116 NonVirtual.getQuantity());
Anders Carlsson53cebd12010-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 Lattner2192fe52011-07-18 04:24:23 +0000128 llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
Anders Carlsson53cebd12010-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 Carlsson9a57c5a2009-09-12 04:27:24 +0000135llvm::Value *
Anders Carlssond829a022010-04-24 21:06:20 +0000136CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000137 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000138 CastExpr::path_const_iterator PathBegin,
139 CastExpr::path_const_iterator PathEnd,
Anders Carlssond829a022010-04-24 21:06:20 +0000140 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000141 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000142
John McCallcf142162010-08-07 06:22:56 +0000143 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlssond829a022010-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 Dycka1a4ae32011-03-22 00:53:26 +0000153 CharUnits NonVirtualOffset =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000154 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallcf142162010-08-07 06:22:56 +0000155 Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000156
157 // Get the base pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000158 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000159 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlssond829a022010-04-24 21:06:20 +0000160
Ken Dycka1a4ae32011-03-22 00:53:26 +0000161 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlssond829a022010-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 Carlsson98981b12011-04-11 00:30:07 +0000175 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssond829a022010-04-24 21:06:20 +0000176 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
177 EmitBlock(CastNotNull);
178 }
179
180 llvm::Value *VirtualOffset = 0;
181
Anders Carlssona376b532011-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 Dycka1a4ae32011-03-22 00:53:26 +0000188 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
189 NonVirtualOffset += VBaseOffset;
Anders Carlssona376b532011-01-29 03:18:56 +0000190 } else
191 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
192 }
Anders Carlssond829a022010-04-24 21:06:20 +0000193
194 // Apply the offsets.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000195 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000196 NonVirtualOffset,
Anders Carlssond829a022010-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 Foad20c0f022011-03-30 11:28:58 +0000208 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssond829a022010-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 Carlsson8c793172009-11-23 17:57:54 +0000219CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000220 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000221 CastExpr::path_const_iterator PathBegin,
222 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000223 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000224 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000225
Anders Carlsson8c793172009-11-23 17:57:54 +0000226 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000227 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000228 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Anders Carlsson8c793172009-11-23 17:57:54 +0000229
Anders Carlsson600f7372010-01-31 01:43:37 +0000230 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000231 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlsson600f7372010-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 Carlsson8c793172009-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 Carlsson98981b12011-04-11 00:30:07 +0000247 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000248 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
249 EmitBlock(CastNotNull);
250 }
251
Anders Carlsson600f7372010-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 Carlsson8c793172009-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 Foad20c0f022011-03-30 11:28:58 +0000266 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-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 Carlsson9a57c5a2009-09-12 04:27:24 +0000274}
Anders Carlsson093bdff2010-03-30 03:27:09 +0000275
Anders Carlssone36a6b32010-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 Carlsson4d205ba2010-05-02 23:33:10 +0000278static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
279 bool ForVirtualBase) {
Anders Carlssona864caf2010-03-23 04:11:45 +0000280 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssone36a6b32010-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 McCall5c60a6f2010-02-18 19:59:28 +0000287
Anders Carlssone36a6b32010-01-02 01:01:18 +0000288 llvm::Value *VTT;
289
John McCall5c60a6f2010-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 Carlssona864caf2010-03-23 04:11:45 +0000295 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000296 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000297 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000298 SubVTTIndex = 0;
299 } else {
Anders Carlsson859b3062010-05-02 23:53:25 +0000300 const ASTRecordLayout &Layout =
301 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck16ffcac2011-03-24 01:21:01 +0000302 CharUnits BaseOffset = ForVirtualBase ?
303 Layout.getVBaseClassOffset(Base) :
304 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000305
306 SubVTTIndex =
307 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000308 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
309 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000310
Anders Carlssona864caf2010-03-23 04:11:45 +0000311 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssone36a6b32010-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 Carlsson883fc722011-01-29 19:16:51 +0000317 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000318 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
319 }
320
321 return VTT;
322}
323
John McCall1d987562010-07-21 01:23:41 +0000324namespace {
John McCallf99a6312010-07-21 05:30:47 +0000325 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000326 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-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 McCall1d987562010-07-21 01:23:41 +0000331
John McCall30317fd2011-07-12 20:27:29 +0000332 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-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 McCall1d987562010-07-21 01:23:41 +0000342 }
343 };
John McCall769250e2010-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 McCall1d987562010-07-21 01:23:41 +0000367}
368
Anders Carlssonfb404882009-12-24 22:46:43 +0000369static void EmitBaseInitializer(CodeGenFunction &CGF,
370 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000371 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-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 Carlsson1c0f8bb2010-04-12 00:51:03 +0000382 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-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 McCall769250e2010-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 McCall6ce74722010-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 Carlssonc4ba0cd2010-04-24 23:01:49 +0000396 llvm::Value *V =
397 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000398 BaseClassDecl,
399 isBaseVirtual);
John McCall6ce74722010-02-16 04:15:37 +0000400
John McCall8d6fc952011-08-25 20:40:09 +0000401 AggValueSlot AggSlot =
402 AggValueSlot::forAddr(V, Qualifiers(),
403 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000404 AggValueSlot::DoesNotNeedGCBarriers,
405 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000406
407 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000408
Anders Carlsson6dc07d42011-02-28 00:33:03 +0000409 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000410 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000411 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
412 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000413}
414
Douglas Gregor94f9a482010-05-05 05:51:00 +0000415static void EmitAggMemberInitializer(CodeGenFunction &CGF,
416 LValue LHS,
417 llvm::Value *ArrayIndexVar,
Alexis Hunt1d792652011-01-08 20:30:50 +0000418 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000419 QualType T,
420 unsigned Index) {
421 if (Index == MemberInit->getNumArrayIndices()) {
John McCallbd309292010-07-06 01:34:17 +0000422 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregor94f9a482010-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 McCall7a626f62010-09-15 10:14:12 +0000434
John McCall31168b02011-06-15 23:02:42 +0000435 if (!CGF.hasAggregateLLVMType(T)) {
John McCall1553b192011-06-16 04:16:24 +0000436 LValue lvalue = CGF.MakeAddrLValue(Dest, T);
437 CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, lvalue, false);
John McCall31168b02011-06-15 23:02:42 +0000438 } else if (T->isAnyComplexType()) {
439 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest,
440 LHS.isVolatileQualified());
441 } else {
John McCall8d6fc952011-08-25 20:40:09 +0000442 AggValueSlot Slot =
443 AggValueSlot::forAddr(Dest, LHS.getQuals(),
444 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000445 AggValueSlot::DoesNotNeedGCBarriers,
446 AggValueSlot::IsNotAliased);
John McCall31168b02011-06-15 23:02:42 +0000447
448 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
449 }
Douglas Gregor94f9a482010-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 Gregor94f9a482010-05-05 05:51:00 +0000476 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000477 llvm::Value *NumElementsPtr =
478 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-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 McCallbd309292010-07-06 01:34:17 +0000489 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregor94f9a482010-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 McCall1d987562010-07-21 01:23:41 +0000511
512namespace {
John McCallcda666c2010-07-21 07:22:38 +0000513 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall1d987562010-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 McCall30317fd2011-07-12 20:27:29 +0000520 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1d987562010-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}
Douglas Gregor94f9a482010-05-05 05:51:00 +0000530
Anders Carlssonfb404882009-12-24 22:46:43 +0000531static void EmitMemberInitializer(CodeGenFunction &CGF,
532 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000533 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000534 const CXXConstructorDecl *Constructor,
535 FunctionArgList &Args) {
Francois Pichetd583da02010-12-04 09:14:42 +0000536 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000537 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000538 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlssonfb404882009-12-24 22:46:43 +0000539
540 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000541 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlssonfb404882009-12-24 22:46:43 +0000542 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
543
544 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCallc4094932010-05-21 01:18:57 +0000545 LValue LHS;
Anders Carlssondb78f0a2010-01-29 05:24:29 +0000546
Anders Carlssonfb404882009-12-24 22:46:43 +0000547 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichetd583da02010-12-04 09:14:42 +0000548 if (MemberInit->isIndirectMemberInitializer()) {
549 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
550 MemberInit->getIndirectMember(), 0);
551 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000552 } else {
553 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000554 }
555
Alexis Hunt1d792652011-01-08 20:30:50 +0000556 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000557 // was implicitly generated, we shouldn't be zeroing memory.
John McCall31168b02011-06-15 23:02:42 +0000558 if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlssonc0964b62010-05-22 17:35:42 +0000559 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000560 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
John McCall31168b02011-06-15 23:02:42 +0000561 if (LHS.isSimple()) {
John McCall1553b192011-06-16 04:16:24 +0000562 CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000563 } else {
564 RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
John McCall55e1fbc2011-06-25 02:11:03 +0000565 CGF.EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000566 }
Douglas Gregor7ae2d772010-01-31 09:12:51 +0000567 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
568 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlssonfb404882009-12-24 22:46:43 +0000569 LHS.isVolatileQualified());
570 } else {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000571 llvm::Value *ArrayIndexVar = 0;
572 const ConstantArrayType *Array
573 = CGF.getContext().getAsConstantArrayType(FieldType);
574 if (Array && Constructor->isImplicit() &&
575 Constructor->isCopyConstructor()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000576 llvm::Type *SizeTy
Douglas Gregor94f9a482010-05-05 05:51:00 +0000577 = CGF.ConvertType(CGF.getContext().getSizeType());
578
579 // The LHS is a pointer to the first object we'll be constructing, as
580 // a flat array.
581 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Chris Lattner2192fe52011-07-18 04:24:23 +0000582 llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000583 BasePtr = llvm::PointerType::getUnqual(BasePtr);
584 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
585 BasePtr);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000586 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000587
588 // Create an array index that will be used to walk over all of the
589 // objects we're constructing.
590 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
591 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
592 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
593
John McCall31168b02011-06-15 23:02:42 +0000594 // If we are copying an array of PODs or classes with trivial copy
Douglas Gregor94f9a482010-05-05 05:51:00 +0000595 // constructors, perform a single aggregate copy.
John McCall31168b02011-06-15 23:02:42 +0000596 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
597 if (BaseElementTy.isPODType(CGF.getContext()) ||
598 (Record && Record->hasTrivialCopyConstructor())) {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000599 // Find the source pointer. We knows it's the last argument because
600 // we know we're in a copy constructor.
601 unsigned SrcArgIndex = Args.size() - 1;
602 llvm::Value *SrcPtr
John McCalla738c252011-03-09 04:27:21 +0000603 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000604 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
605
606 // Copy the aggregate.
607 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
608 LHS.isVolatileQualified());
609 return;
610 }
611
612 // Emit the block variables for the array indices, if any.
613 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCall1c9c3fd2010-10-15 04:57:14 +0000614 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000615 }
616
617 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlssonba631672010-02-06 19:50:17 +0000618
Anders Carlsson6dc07d42011-02-28 00:33:03 +0000619 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlssonba631672010-02-06 19:50:17 +0000620 return;
621
Douglas Gregor94f9a482010-05-05 05:51:00 +0000622 // FIXME: If we have an array of classes w/ non-trivial destructors,
623 // we need to destroy in reverse order of construction along the exception
624 // path.
Anders Carlssonba631672010-02-06 19:50:17 +0000625 const RecordType *RT = FieldType->getAs<RecordType>();
626 if (!RT)
627 return;
628
629 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall1d987562010-07-21 01:23:41 +0000630 if (!RD->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000631 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
632 RD->getDestructor());
Anders Carlssonfb404882009-12-24 22:46:43 +0000633 }
634}
635
John McCallf8ff7b92010-02-23 00:48:20 +0000636/// Checks whether the given constructor is a valid subject for the
637/// complete-to-base constructor delegation optimization, i.e.
638/// emitting the complete constructor as a simple call to the base
639/// constructor.
640static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
641
642 // Currently we disable the optimization for classes with virtual
643 // bases because (1) the addresses of parameter variables need to be
644 // consistent across all initializers but (2) the delegate function
645 // call necessarily creates a second copy of the parameter variable.
646 //
647 // The limiting example (purely theoretical AFAIK):
648 // struct A { A(int &c) { c++; } };
649 // struct B : virtual A {
650 // B(int count) : A(count) { printf("%d\n", count); }
651 // };
652 // ...although even this example could in principle be emitted as a
653 // delegation since the address of the parameter doesn't escape.
654 if (Ctor->getParent()->getNumVBases()) {
655 // TODO: white-list trivial vbase initializers. This case wouldn't
656 // be subject to the restrictions below.
657
658 // TODO: white-list cases where:
659 // - there are no non-reference parameters to the constructor
660 // - the initializers don't access any non-reference parameters
661 // - the initializers don't take the address of non-reference
662 // parameters
663 // - etc.
664 // If we ever add any of the above cases, remember that:
665 // - function-try-blocks will always blacklist this optimization
666 // - we need to perform the constructor prologue and cleanup in
667 // EmitConstructorBody.
668
669 return false;
670 }
671
672 // We also disable the optimization for variadic functions because
673 // it's impossible to "re-pass" varargs.
674 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
675 return false;
676
Alexis Hunt61bc1732011-05-01 07:04:31 +0000677 // FIXME: Decide if we can do a delegation of a delegating constructor.
678 if (Ctor->isDelegatingConstructor())
679 return false;
680
John McCallf8ff7b92010-02-23 00:48:20 +0000681 return true;
682}
683
John McCallb81884d2010-02-19 09:25:03 +0000684/// EmitConstructorBody - Emits the body of the current constructor.
685void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
686 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
687 CXXCtorType CtorType = CurGD.getCtorType();
688
John McCallf8ff7b92010-02-23 00:48:20 +0000689 // Before we go any further, try the complete->base constructor
690 // delegation optimization.
691 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld76c1db2010-08-11 21:04:37 +0000692 if (CGDebugInfo *DI = getDebugInfo())
693 DI->EmitStopPoint(Builder);
John McCallf8ff7b92010-02-23 00:48:20 +0000694 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
695 return;
696 }
697
John McCallb81884d2010-02-19 09:25:03 +0000698 Stmt *Body = Ctor->getBody();
699
John McCallf8ff7b92010-02-23 00:48:20 +0000700 // Enter the function-try-block before the constructor prologue if
701 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000702 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000703 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000704 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000705
John McCallbd309292010-07-06 01:34:17 +0000706 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCallb81884d2010-02-19 09:25:03 +0000707
John McCallf8ff7b92010-02-23 00:48:20 +0000708 // Emit the constructor prologue, i.e. the base and member
709 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000710 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000711
712 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000713 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000714 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
715 else if (Body)
716 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000717
718 // Emit any cleanup blocks associated with the member or base
719 // initializers, which includes (along the exceptional path) the
720 // destructors for those members and bases that were fully
721 // constructed.
John McCallbd309292010-07-06 01:34:17 +0000722 PopCleanupBlocks(CleanupDepth);
John McCallb81884d2010-02-19 09:25:03 +0000723
John McCallf8ff7b92010-02-23 00:48:20 +0000724 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000725 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000726}
727
Anders Carlssonfb404882009-12-24 22:46:43 +0000728/// EmitCtorPrologue - This routine generates necessary code to initialize
729/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +0000730void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000731 CXXCtorType CtorType,
732 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +0000733 if (CD->isDelegatingConstructor())
734 return EmitDelegatingCXXConstructorCall(CD, Args);
735
Anders Carlssonfb404882009-12-24 22:46:43 +0000736 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +0000737
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000738 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlssonfb404882009-12-24 22:46:43 +0000739
Anders Carlssonfb404882009-12-24 22:46:43 +0000740 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
741 E = CD->init_end();
742 B != E; ++B) {
Alexis Hunt1d792652011-01-08 20:30:50 +0000743 CXXCtorInitializer *Member = (*B);
Anders Carlssonfb404882009-12-24 22:46:43 +0000744
Alexis Hunt271c3682011-05-03 20:19:28 +0000745 if (Member->isBaseInitializer()) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000746 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Alexis Hunt271c3682011-05-03 20:19:28 +0000747 } else {
748 assert(Member->isAnyMemberInitializer() &&
749 "Delegating initializer on non-delegating constructor");
Anders Carlsson5dc86332010-02-02 19:58:43 +0000750 MemberInitializers.push_back(Member);
Alexis Hunt271c3682011-05-03 20:19:28 +0000751 }
Anders Carlssonfb404882009-12-24 22:46:43 +0000752 }
753
Anders Carlssond5895932010-03-28 21:07:49 +0000754 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +0000755
John McCallbd309292010-07-06 01:34:17 +0000756 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregor94f9a482010-05-05 05:51:00 +0000757 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlssonfb404882009-12-24 22:46:43 +0000758}
759
Anders Carlsson49c0bd22011-05-15 17:36:21 +0000760static bool
761FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
762
763static bool
764HasTrivialDestructorBody(ASTContext &Context,
765 const CXXRecordDecl *BaseClassDecl,
766 const CXXRecordDecl *MostDerivedClassDecl)
767{
768 // If the destructor is trivial we don't have to check anything else.
769 if (BaseClassDecl->hasTrivialDestructor())
770 return true;
771
772 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
773 return false;
774
775 // Check fields.
776 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
777 E = BaseClassDecl->field_end(); I != E; ++I) {
778 const FieldDecl *Field = *I;
779
780 if (!FieldHasTrivialDestructorBody(Context, Field))
781 return false;
782 }
783
784 // Check non-virtual bases.
785 for (CXXRecordDecl::base_class_const_iterator I =
786 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
787 I != E; ++I) {
788 if (I->isVirtual())
789 continue;
790
791 const CXXRecordDecl *NonVirtualBase =
792 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
793 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
794 MostDerivedClassDecl))
795 return false;
796 }
797
798 if (BaseClassDecl == MostDerivedClassDecl) {
799 // Check virtual bases.
800 for (CXXRecordDecl::base_class_const_iterator I =
801 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
802 I != E; ++I) {
803 const CXXRecordDecl *VirtualBase =
804 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
805 if (!HasTrivialDestructorBody(Context, VirtualBase,
806 MostDerivedClassDecl))
807 return false;
808 }
809 }
810
811 return true;
812}
813
814static bool
815FieldHasTrivialDestructorBody(ASTContext &Context,
816 const FieldDecl *Field)
817{
818 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
819
820 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
821 if (!RT)
822 return true;
823
824 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
825 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
826}
827
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000828/// CanSkipVTablePointerInitialization - Check whether we need to initialize
829/// any vtable pointers before calling this destructor.
830static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +0000831 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000832 if (!Dtor->hasTrivialBody())
833 return false;
834
835 // Check the fields.
836 const CXXRecordDecl *ClassDecl = Dtor->getParent();
837 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
838 E = ClassDecl->field_end(); I != E; ++I) {
839 const FieldDecl *Field = *I;
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000840
Anders Carlsson49c0bd22011-05-15 17:36:21 +0000841 if (!FieldHasTrivialDestructorBody(Context, Field))
842 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000843 }
844
845 return true;
846}
847
John McCallb81884d2010-02-19 09:25:03 +0000848/// EmitDestructorBody - Emits the body of the current destructor.
849void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
850 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
851 CXXDtorType DtorType = CurGD.getDtorType();
852
John McCallf99a6312010-07-21 05:30:47 +0000853 // The call to operator delete in a deleting destructor happens
854 // outside of the function-try-block, which means it's always
855 // possible to delegate the destructor body to the complete
856 // destructor. Do so.
857 if (DtorType == Dtor_Deleting) {
858 EnterDtorCleanups(Dtor, Dtor_Deleting);
859 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
860 LoadCXXThis());
861 PopCleanupBlock();
862 return;
863 }
864
John McCallb81884d2010-02-19 09:25:03 +0000865 Stmt *Body = Dtor->getBody();
866
867 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +0000868 // anything else.
869 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +0000870 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000871 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000872
John McCallf99a6312010-07-21 05:30:47 +0000873 // Enter the epilogue cleanups.
874 RunCleanupsScope DtorEpilogue(*this);
875
John McCallb81884d2010-02-19 09:25:03 +0000876 // If this is the complete variant, just invoke the base variant;
877 // the epilogue will destruct the virtual bases. But we can't do
878 // this optimization if the body is a function-try-block, because
879 // we'd introduce *two* handler blocks.
John McCallf99a6312010-07-21 05:30:47 +0000880 switch (DtorType) {
881 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
882
883 case Dtor_Complete:
884 // Enter the cleanup scopes for virtual bases.
885 EnterDtorCleanups(Dtor, Dtor_Complete);
886
887 if (!isTryBody) {
888 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
889 LoadCXXThis());
890 break;
891 }
892 // Fallthrough: act like we're in the base variant.
John McCallb81884d2010-02-19 09:25:03 +0000893
John McCallf99a6312010-07-21 05:30:47 +0000894 case Dtor_Base:
895 // Enter the cleanup scopes for fields and non-virtual bases.
896 EnterDtorCleanups(Dtor, Dtor_Base);
897
898 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000899 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
900 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +0000901
902 if (isTryBody)
903 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
904 else if (Body)
905 EmitStmt(Body);
906 else {
907 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
908 // nothing to do besides what's in the epilogue
909 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +0000910 // -fapple-kext must inline any call to this dtor into
911 // the caller's body.
912 if (getContext().getLangOptions().AppleKext)
913 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +0000914 break;
John McCallb81884d2010-02-19 09:25:03 +0000915 }
916
John McCallf99a6312010-07-21 05:30:47 +0000917 // Jump out through the epilogue cleanups.
918 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000919
920 // Exit the try if applicable.
921 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000922 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000923}
924
John McCallf99a6312010-07-21 05:30:47 +0000925namespace {
926 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +0000927 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000928 CallDtorDelete() {}
929
John McCall30317fd2011-07-12 20:27:29 +0000930 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +0000931 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
932 const CXXRecordDecl *ClassDecl = Dtor->getParent();
933 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
934 CGF.getContext().getTagDeclType(ClassDecl));
935 }
936 };
937
John McCall4bd0fb12011-07-12 16:41:08 +0000938 class DestroyField : public EHScopeStack::Cleanup {
939 const FieldDecl *field;
940 CodeGenFunction::Destroyer &destroyer;
941 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +0000942
John McCall4bd0fb12011-07-12 16:41:08 +0000943 public:
944 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
945 bool useEHCleanupForArray)
946 : field(field), destroyer(*destroyer),
947 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +0000948
John McCall30317fd2011-07-12 20:27:29 +0000949 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +0000950 // Find the address of the field.
951 llvm::Value *thisValue = CGF.LoadCXXThis();
952 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
953 assert(LV.isSimple());
954
955 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +0000956 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +0000957 }
958 };
959}
960
Anders Carlssonfb404882009-12-24 22:46:43 +0000961/// EmitDtorEpilogue - Emit all code that comes at the end of class's
962/// destructor. This is to call destructors on members and base classes
963/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +0000964void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
965 CXXDtorType DtorType) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000966 assert(!DD->isTrivial() &&
967 "Should not emit dtor epilogue for trivial dtor!");
968
John McCallf99a6312010-07-21 05:30:47 +0000969 // The deleting-destructor phase just needs to call the appropriate
970 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +0000971 if (DtorType == Dtor_Deleting) {
972 assert(DD->getOperatorDelete() &&
973 "operator delete missing - EmitDtorEpilogue");
John McCallcda666c2010-07-21 07:22:38 +0000974 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall5c60a6f2010-02-18 19:59:28 +0000975 return;
976 }
977
John McCallf99a6312010-07-21 05:30:47 +0000978 const CXXRecordDecl *ClassDecl = DD->getParent();
979
980 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +0000981 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +0000982
983 // We push them in the forward order so that they'll be popped in
984 // the reverse order.
985 for (CXXRecordDecl::base_class_const_iterator I =
986 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall5c60a6f2010-02-18 19:59:28 +0000987 I != E; ++I) {
988 const CXXBaseSpecifier &Base = *I;
989 CXXRecordDecl *BaseClassDecl
990 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
991
992 // Ignore trivial destructors.
993 if (BaseClassDecl->hasTrivialDestructor())
994 continue;
John McCallf99a6312010-07-21 05:30:47 +0000995
John McCallcda666c2010-07-21 07:22:38 +0000996 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
997 BaseClassDecl,
998 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +0000999 }
John McCallf99a6312010-07-21 05:30:47 +00001000
John McCall5c60a6f2010-02-18 19:59:28 +00001001 return;
1002 }
1003
1004 assert(DtorType == Dtor_Base);
John McCallf99a6312010-07-21 05:30:47 +00001005
1006 // Destroy non-virtual bases.
1007 for (CXXRecordDecl::base_class_const_iterator I =
1008 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1009 const CXXBaseSpecifier &Base = *I;
1010
1011 // Ignore virtual bases.
1012 if (Base.isVirtual())
1013 continue;
1014
1015 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1016
1017 // Ignore trivial destructors.
1018 if (BaseClassDecl->hasTrivialDestructor())
1019 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001020
John McCallcda666c2010-07-21 07:22:38 +00001021 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1022 BaseClassDecl,
1023 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001024 }
1025
1026 // Destroy direct fields.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001027 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlssonfb404882009-12-24 22:46:43 +00001028 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1029 E = ClassDecl->field_end(); I != E; ++I) {
John McCall4bd0fb12011-07-12 16:41:08 +00001030 const FieldDecl *field = *I;
1031 QualType type = field->getType();
1032 QualType::DestructionKind dtorKind = type.isDestructedType();
1033 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001034
John McCall4bd0fb12011-07-12 16:41:08 +00001035 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1036 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1037 getDestroyer(dtorKind),
1038 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001039 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001040}
1041
John McCallf677a8e2011-07-13 06:10:41 +00001042/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1043/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001044///
John McCallf677a8e2011-07-13 06:10:41 +00001045/// \param ctor the constructor to call for each element
1046/// \param argBegin,argEnd the arguments to evaluate and pass to the
1047/// constructor
1048/// \param arrayType the type of the array to initialize
1049/// \param arrayBegin an arrayType*
1050/// \param zeroInitialize true if each element should be
1051/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001052void
John McCallf677a8e2011-07-13 06:10:41 +00001053CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1054 const ConstantArrayType *arrayType,
1055 llvm::Value *arrayBegin,
1056 CallExpr::const_arg_iterator argBegin,
1057 CallExpr::const_arg_iterator argEnd,
1058 bool zeroInitialize) {
1059 QualType elementType;
1060 llvm::Value *numElements =
1061 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001062
John McCallf677a8e2011-07-13 06:10:41 +00001063 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1064 argBegin, argEnd, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001065}
1066
John McCallf677a8e2011-07-13 06:10:41 +00001067/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1068/// constructor for each of several members of an array.
1069///
1070/// \param ctor the constructor to call for each element
1071/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001072/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001073/// \param argBegin,argEnd the arguments to evaluate and pass to the
1074/// constructor
1075/// \param arrayBegin a T*, where T is the type constructed by ctor
1076/// \param zeroInitialize true if each element should be
1077/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001078void
John McCallf677a8e2011-07-13 06:10:41 +00001079CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1080 llvm::Value *numElements,
1081 llvm::Value *arrayBegin,
1082 CallExpr::const_arg_iterator argBegin,
1083 CallExpr::const_arg_iterator argEnd,
1084 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001085
1086 // It's legal for numElements to be zero. This can happen both
1087 // dynamically, because x can be zero in 'new A[x]', and statically,
1088 // because of GCC extensions that permit zero-length arrays. There
1089 // are probably legitimate places where we could assume that this
1090 // doesn't happen, but it's not clear that it's worth it.
1091 llvm::BranchInst *zeroCheckBranch = 0;
1092
1093 // Optimize for a constant count.
1094 llvm::ConstantInt *constantCount
1095 = dyn_cast<llvm::ConstantInt>(numElements);
1096 if (constantCount) {
1097 // Just skip out if the constant count is zero.
1098 if (constantCount->isZero()) return;
1099
1100 // Otherwise, emit the check.
1101 } else {
1102 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1103 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1104 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1105 EmitBlock(loopBB);
1106 }
1107
John McCallf677a8e2011-07-13 06:10:41 +00001108 // Find the end of the array.
1109 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1110 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001111
John McCallf677a8e2011-07-13 06:10:41 +00001112 // Enter the loop, setting up a phi for the current location to initialize.
1113 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1114 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1115 EmitBlock(loopBB);
1116 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1117 "arrayctor.cur");
1118 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001119
Anders Carlsson27da15b2010-01-01 20:29:01 +00001120 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001121
1122 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001123
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001124 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001125 if (zeroInitialize)
1126 EmitNullInitialization(cur, type);
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001127
Anders Carlsson27da15b2010-01-01 20:29:01 +00001128 // C++ [class.temporary]p4:
1129 // There are two contexts in which temporaries are destroyed at a different
1130 // point than the end of the full-expression. The first context is when a
1131 // default constructor is called to initialize an element of an array.
1132 // If the constructor has one or more default arguments, the destruction of
1133 // every temporary created in a default argument expression is sequenced
1134 // before the construction of the next array element, if any.
1135
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001136 {
John McCallbd309292010-07-06 01:34:17 +00001137 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001138
John McCallf677a8e2011-07-13 06:10:41 +00001139 // Evaluate the constructor and its arguments in a regular
1140 // partial-destroy cleanup.
1141 if (getLangOptions().Exceptions &&
1142 !ctor->getParent()->hasTrivialDestructor()) {
1143 Destroyer *destroyer = destroyCXXObject;
1144 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1145 }
1146
1147 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1148 cur, argBegin, argEnd);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001149 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001150
John McCallf677a8e2011-07-13 06:10:41 +00001151 // Go to the next element.
1152 llvm::Value *next =
1153 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1154 "arrayctor.next");
1155 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001156
John McCallf677a8e2011-07-13 06:10:41 +00001157 // Check whether that's the end of the loop.
1158 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1159 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1160 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001161
John McCall6549b312011-07-13 07:37:11 +00001162 // Patch the earlier check to skip over the loop.
1163 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1164
John McCallf677a8e2011-07-13 06:10:41 +00001165 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001166}
1167
John McCall82fe67b2011-07-09 01:37:26 +00001168void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1169 llvm::Value *addr,
1170 QualType type) {
1171 const RecordType *rtype = type->castAs<RecordType>();
1172 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1173 const CXXDestructorDecl *dtor = record->getDestructor();
1174 assert(!dtor->isTrivial());
1175 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1176 addr);
1177}
1178
Anders Carlsson27da15b2010-01-01 20:29:01 +00001179void
1180CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlssone11f9ce2010-05-02 23:20:53 +00001181 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001182 llvm::Value *This,
1183 CallExpr::const_arg_iterator ArgBeg,
1184 CallExpr::const_arg_iterator ArgEnd) {
Devang Patelb6ed3692011-02-22 20:55:26 +00001185
1186 CGDebugInfo *DI = getDebugInfo();
1187 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1188 // If debug info for this class has been emitted then this is the right time
1189 // to do so.
1190 const CXXRecordDecl *Parent = D->getParent();
1191 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1192 Parent->getLocation());
1193 }
1194
John McCallca972cd2010-02-06 00:25:16 +00001195 if (D->isTrivial()) {
1196 if (ArgBeg == ArgEnd) {
1197 // Trivial default constructor, no codegen required.
1198 assert(D->isDefaultConstructor() &&
1199 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001200 return;
1201 }
John McCallca972cd2010-02-06 00:25:16 +00001202
1203 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1204 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1205
John McCallca972cd2010-02-06 00:25:16 +00001206 const Expr *E = (*ArgBeg);
1207 QualType Ty = E->getType();
1208 llvm::Value *Src = EmitLValue(E).getAddress();
1209 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001210 return;
1211 }
1212
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001213 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001214 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1215
Anders Carlssone36a6b32010-01-02 01:01:18 +00001216 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001217}
1218
John McCallf8ff7b92010-02-23 00:48:20 +00001219void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001220CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1221 llvm::Value *This, llvm::Value *Src,
1222 CallExpr::const_arg_iterator ArgBeg,
1223 CallExpr::const_arg_iterator ArgEnd) {
1224 if (D->isTrivial()) {
1225 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1226 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1227 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1228 return;
1229 }
1230 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1231 clang::Ctor_Complete);
1232 assert(D->isInstance() &&
1233 "Trying to emit a member call expr on a static method!");
1234
1235 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1236
1237 CallArgList Args;
1238
1239 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001240 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001241
1242
1243 // Push the src ptr.
1244 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001245 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001246 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001247 Args.add(RValue::get(Src), QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001248
1249 // Skip over first argument (Src).
1250 ++ArgBeg;
1251 CallExpr::const_arg_iterator Arg = ArgBeg;
1252 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1253 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1254 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall32ea9692011-03-11 20:59:21 +00001255 EmitCallArg(Args, *Arg, *I);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001256 }
1257 // Either we've emitted all the call args, or we have a call to a
1258 // variadic function.
1259 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1260 "Extra arguments in non-variadic function!");
1261 // If we still have any arguments, emit them using the type of the argument.
1262 for (; Arg != ArgEnd; ++Arg) {
1263 QualType ArgType = Arg->getType();
John McCall32ea9692011-03-11 20:59:21 +00001264 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001265 }
1266
Eli Friedmanf481cca2011-08-09 17:38:12 +00001267 EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
1268 ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001269}
1270
1271void
John McCallf8ff7b92010-02-23 00:48:20 +00001272CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1273 CXXCtorType CtorType,
1274 const FunctionArgList &Args) {
1275 CallArgList DelegateArgs;
1276
1277 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1278 assert(I != E && "no parameters to constructor");
1279
1280 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001281 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001282 ++I;
1283
1284 // vtt
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001285 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1286 /*ForVirtualBase=*/false)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001287 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001288 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001289
Anders Carlssona864caf2010-03-23 04:11:45 +00001290 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001291 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001292 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001293 ++I;
1294 }
1295 }
1296
1297 // Explicit arguments.
1298 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001299 const VarDecl *param = *I;
1300 EmitDelegateCallArg(DelegateArgs, param);
John McCallf8ff7b92010-02-23 00:48:20 +00001301 }
1302
1303 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1304 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1305 ReturnValueSlot(), DelegateArgs, Ctor);
1306}
1307
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001308namespace {
1309 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1310 const CXXDestructorDecl *Dtor;
1311 llvm::Value *Addr;
1312 CXXDtorType Type;
1313
1314 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1315 CXXDtorType Type)
1316 : Dtor(D), Addr(Addr), Type(Type) {}
1317
John McCall30317fd2011-07-12 20:27:29 +00001318 void Emit(CodeGenFunction &CGF, Flags flags) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001319 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1320 Addr);
1321 }
1322 };
1323}
1324
Alexis Hunt61bc1732011-05-01 07:04:31 +00001325void
1326CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1327 const FunctionArgList &Args) {
1328 assert(Ctor->isDelegatingConstructor());
1329
1330 llvm::Value *ThisPtr = LoadCXXThis();
1331
John McCall31168b02011-06-15 23:02:42 +00001332 AggValueSlot AggSlot =
John McCall8d6fc952011-08-25 20:40:09 +00001333 AggValueSlot::forAddr(ThisPtr, Qualifiers(),
1334 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001335 AggValueSlot::DoesNotNeedGCBarriers,
1336 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001337
1338 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001339
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001340 const CXXRecordDecl *ClassDecl = Ctor->getParent();
1341 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1342 CXXDtorType Type =
1343 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1344
1345 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1346 ClassDecl->getDestructor(),
1347 ThisPtr, Type);
1348 }
1349}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001350
Anders Carlsson27da15b2010-01-01 20:29:01 +00001351void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1352 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001353 bool ForVirtualBase,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001354 llvm::Value *This) {
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001355 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1356 ForVirtualBase);
Fariborz Jahanian265c3252011-02-01 23:22:34 +00001357 llvm::Value *Callee = 0;
1358 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +00001359 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1360 DD->getParent());
Fariborz Jahanian265c3252011-02-01 23:22:34 +00001361
1362 if (!Callee)
1363 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001364
Anders Carlssone36a6b32010-01-02 01:01:18 +00001365 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001366}
1367
John McCall53cad2e2010-07-21 01:41:18 +00001368namespace {
John McCallcda666c2010-07-21 07:22:38 +00001369 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001370 const CXXDestructorDecl *Dtor;
1371 llvm::Value *Addr;
1372
1373 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1374 : Dtor(D), Addr(Addr) {}
1375
John McCall30317fd2011-07-12 20:27:29 +00001376 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall53cad2e2010-07-21 01:41:18 +00001377 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1378 /*ForVirtualBase=*/false, Addr);
1379 }
1380 };
1381}
1382
John McCall8680f872010-07-21 06:29:51 +00001383void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1384 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001385 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001386}
1387
John McCallbd309292010-07-06 01:34:17 +00001388void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1389 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1390 if (!ClassDecl) return;
1391 if (ClassDecl->hasTrivialDestructor()) return;
1392
1393 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001394 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001395 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001396}
1397
Anders Carlsson27da15b2010-01-01 20:29:01 +00001398llvm::Value *
Anders Carlsson84673e22010-01-31 01:36:53 +00001399CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1400 const CXXRecordDecl *ClassDecl,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001401 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00001402 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyckbb4e9772011-04-07 12:37:09 +00001403 CharUnits VBaseOffsetOffset =
Anders Carlssona864caf2010-03-23 04:11:45 +00001404 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001405
1406 llvm::Value *VBaseOffsetPtr =
Ken Dyckbb4e9772011-04-07 12:37:09 +00001407 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1408 "vbase.offset.ptr");
Chris Lattner2192fe52011-07-18 04:24:23 +00001409 llvm::Type *PtrDiffTy =
Anders Carlsson27da15b2010-01-01 20:29:01 +00001410 ConvertType(getContext().getPointerDiffType());
1411
1412 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1413 PtrDiffTy->getPointerTo());
1414
1415 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1416
1417 return VBaseOffset;
1418}
1419
Anders Carlssone87fae92010-03-28 19:40:00 +00001420void
1421CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001422 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001423 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001424 llvm::Constant *VTable,
1425 const CXXRecordDecl *VTableClass) {
Anders Carlsson58890272010-03-29 01:08:49 +00001426 const CXXRecordDecl *RD = Base.getBase();
1427
Anders Carlssone87fae92010-03-28 19:40:00 +00001428 // Compute the address point.
Anders Carlsson58890272010-03-29 01:08:49 +00001429 llvm::Value *VTableAddressPoint;
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001430
Anders Carlsson58890272010-03-29 01:08:49 +00001431 // Check if we need to use a vtable from the VTT.
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001432 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlsson652758c2010-04-20 05:22:15 +00001433 (RD->getNumVBases() || NearestVBase)) {
Anders Carlsson58890272010-03-29 01:08:49 +00001434 // Get the secondary vpointer index.
1435 uint64_t VirtualPointerIndex =
1436 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1437
1438 /// Load the VTT.
1439 llvm::Value *VTT = LoadCXXVTT();
1440 if (VirtualPointerIndex)
1441 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1442
1443 // And load the address point from the VTT.
1444 VTableAddressPoint = Builder.CreateLoad(VTT);
1445 } else {
Anders Carlssonf6f24c62010-03-29 02:08:26 +00001446 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlsson58890272010-03-29 01:08:49 +00001447 VTableAddressPoint =
Anders Carlssone87fae92010-03-28 19:40:00 +00001448 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlsson58890272010-03-29 01:08:49 +00001449 }
Anders Carlssone87fae92010-03-28 19:40:00 +00001450
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001451 // Compute where to store the address point.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001452 llvm::Value *VirtualOffset = 0;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001453 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001454
1455 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1456 // We need to use the virtual base offset offset because the virtual base
1457 // might have a different offset in the most derived class.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001458 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1459 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001460 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001461 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001462 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001463 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001464 }
Anders Carlssonc58fb552010-05-03 00:29:58 +00001465
1466 // Apply the offsets.
1467 llvm::Value *VTableField = LoadCXXThis();
1468
Ken Dyckcfc332c2011-03-23 00:45:26 +00001469 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlssonc58fb552010-05-03 00:29:58 +00001470 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1471 NonVirtualOffset,
1472 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001473
Anders Carlssone87fae92010-03-28 19:40:00 +00001474 // Finally, store the address point.
Chris Lattner2192fe52011-07-18 04:24:23 +00001475 llvm::Type *AddressPointPtrTy =
Anders Carlssone87fae92010-03-28 19:40:00 +00001476 VTableAddressPoint->getType()->getPointerTo();
1477 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1478 Builder.CreateStore(VTableAddressPoint, VTableField);
1479}
1480
Anders Carlssond5895932010-03-28 21:07:49 +00001481void
1482CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001483 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001484 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001485 bool BaseIsNonVirtualPrimaryBase,
1486 llvm::Constant *VTable,
1487 const CXXRecordDecl *VTableClass,
1488 VisitedVirtualBasesSetTy& VBases) {
1489 // If this base is a non-virtual primary base the address point has already
1490 // been set.
1491 if (!BaseIsNonVirtualPrimaryBase) {
1492 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001493 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1494 VTable, VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00001495 }
1496
1497 const CXXRecordDecl *RD = Base.getBase();
1498
1499 // Traverse bases.
1500 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1501 E = RD->bases_end(); I != E; ++I) {
1502 CXXRecordDecl *BaseDecl
1503 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1504
1505 // Ignore classes without a vtable.
1506 if (!BaseDecl->isDynamicClass())
1507 continue;
1508
Ken Dyck3fb4c892011-03-23 01:04:18 +00001509 CharUnits BaseOffset;
1510 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00001511 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00001512
1513 if (I->isVirtual()) {
1514 // Check if we've visited this virtual base before.
1515 if (!VBases.insert(BaseDecl))
1516 continue;
1517
1518 const ASTRecordLayout &Layout =
1519 getContext().getASTRecordLayout(VTableClass);
1520
Ken Dyck3fb4c892011-03-23 01:04:18 +00001521 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1522 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00001523 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00001524 } else {
1525 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1526
Ken Dyck16ffcac2011-03-24 01:21:01 +00001527 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001528 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00001529 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00001530 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00001531 }
1532
Ken Dyck16ffcac2011-03-24 01:21:01 +00001533 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlsson652758c2010-04-20 05:22:15 +00001534 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001535 BaseOffsetFromNearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00001536 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001537 VTable, VTableClass, VBases);
1538 }
1539}
1540
1541void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1542 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001543 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00001544 return;
1545
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001546 // Get the VTable.
1547 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlssonb35ea552010-03-24 03:57:14 +00001548
Anders Carlssond5895932010-03-28 21:07:49 +00001549 // Initialize the vtable pointers for this class and all of its bases.
1550 VisitedVirtualBasesSetTy VBases;
Ken Dyck16ffcac2011-03-24 01:21:01 +00001551 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1552 /*NearestVBase=*/0,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001553 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlssond5895932010-03-28 21:07:49 +00001554 /*BaseIsNonVirtualPrimaryBase=*/false,
1555 VTable, RD, VBases);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001556}
Dan Gohman8fc50c22010-10-26 18:44:08 +00001557
1558llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00001559 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00001560 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1561 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1562}
Anders Carlssonc36783e2011-05-08 20:32:23 +00001563
1564static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1565 const Expr *E = Base;
1566
1567 while (true) {
1568 E = E->IgnoreParens();
1569 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1570 if (CE->getCastKind() == CK_DerivedToBase ||
1571 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1572 CE->getCastKind() == CK_NoOp) {
1573 E = CE->getSubExpr();
1574 continue;
1575 }
1576 }
1577
1578 break;
1579 }
1580
1581 QualType DerivedType = E->getType();
1582 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1583 DerivedType = PTy->getPointeeType();
1584
1585 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1586}
1587
1588// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1589// quite what we want.
1590static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1591 while (true) {
1592 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1593 E = PE->getSubExpr();
1594 continue;
1595 }
1596
1597 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1598 if (CE->getCastKind() == CK_NoOp) {
1599 E = CE->getSubExpr();
1600 continue;
1601 }
1602 }
1603 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1604 if (UO->getOpcode() == UO_Extension) {
1605 E = UO->getSubExpr();
1606 continue;
1607 }
1608 }
1609 return E;
1610 }
1611}
1612
1613/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1614/// function call on the given expr can be devirtualized.
1615/// expr can be devirtualized.
1616static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1617 const CXXMethodDecl *MD) {
1618 // If the most derived class is marked final, we know that no subclass can
1619 // override this member function and so we can devirtualize it. For example:
1620 //
1621 // struct A { virtual void f(); }
1622 // struct B final : A { };
1623 //
1624 // void f(B *b) {
1625 // b->f();
1626 // }
1627 //
1628 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1629 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1630 return true;
1631
1632 // If the member function is marked 'final', we know that it can't be
1633 // overridden and can therefore devirtualize it.
1634 if (MD->hasAttr<FinalAttr>())
1635 return true;
1636
1637 // Similarly, if the class itself is marked 'final' it can't be overridden
1638 // and we can therefore devirtualize the member function call.
1639 if (MD->getParent()->hasAttr<FinalAttr>())
1640 return true;
1641
1642 Base = skipNoOpCastsAndParens(Base);
1643 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1644 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1645 // This is a record decl. We know the type and can devirtualize it.
1646 return VD->getType()->isRecordType();
1647 }
1648
1649 return false;
1650 }
1651
1652 // We can always devirtualize calls on temporary object expressions.
1653 if (isa<CXXConstructExpr>(Base))
1654 return true;
1655
1656 // And calls on bound temporaries.
1657 if (isa<CXXBindTemporaryExpr>(Base))
1658 return true;
1659
1660 // Check if this is a call expr that returns a record type.
1661 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1662 return CE->getCallReturnType()->isRecordType();
1663
1664 // We can't devirtualize the call.
1665 return false;
1666}
1667
1668static bool UseVirtualCall(ASTContext &Context,
1669 const CXXOperatorCallExpr *CE,
1670 const CXXMethodDecl *MD) {
1671 if (!MD->isVirtual())
1672 return false;
1673
1674 // When building with -fapple-kext, all calls must go through the vtable since
1675 // the kernel linker can do runtime patching of vtables.
1676 if (Context.getLangOptions().AppleKext)
1677 return true;
1678
1679 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1680}
1681
1682llvm::Value *
1683CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1684 const CXXMethodDecl *MD,
1685 llvm::Value *This) {
1686 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +00001687 llvm::Type *Ty =
Anders Carlssonc36783e2011-05-08 20:32:23 +00001688 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1689 FPT->isVariadic());
1690
1691 if (UseVirtualCall(getContext(), E, MD))
1692 return BuildVirtualCall(MD, This, Ty);
1693
1694 return CGM.GetAddrOfFunction(MD, Ty);
1695}