blob: fbbf9a554d608ab77101c8131b886ab49896397a [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()) {
John McCall6ce74722010-02-16 04:15:37 +000098 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +000099 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000100 }
101 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
102
103 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000104}
John McCall6ce74722010-02-16 04:15:37 +0000105
Anders Carlsson53cebd12010-04-20 16:03:35 +0000106static llvm::Value *
107ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000108 CharUnits NonVirtual, llvm::Value *Virtual) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000109 llvm::Type *PtrDiffTy =
Anders Carlsson53cebd12010-04-20 16:03:35 +0000110 CGF.ConvertType(CGF.getContext().getPointerDiffType());
111
112 llvm::Value *NonVirtualOffset = 0;
Ken Dyckcfc332c2011-03-23 00:45:26 +0000113 if (!NonVirtual.isZero())
114 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
115 NonVirtual.getQuantity());
Anders Carlsson53cebd12010-04-20 16:03:35 +0000116
117 llvm::Value *BaseOffset;
118 if (Virtual) {
119 if (NonVirtualOffset)
120 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
121 else
122 BaseOffset = Virtual;
123 } else
124 BaseOffset = NonVirtualOffset;
125
126 // Apply the base offset.
Chris Lattnerece04092012-02-07 00:39:47 +0000127 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy);
Anders Carlsson53cebd12010-04-20 16:03:35 +0000128 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
129
130 return ThisPtr;
131}
132
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000133llvm::Value *
Anders Carlssond829a022010-04-24 21:06:20 +0000134CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000135 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000136 CastExpr::path_const_iterator PathBegin,
137 CastExpr::path_const_iterator PathEnd,
Anders Carlssond829a022010-04-24 21:06:20 +0000138 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000139 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000140
John McCallcf142162010-08-07 06:22:56 +0000141 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlssond829a022010-04-24 21:06:20 +0000142 const CXXRecordDecl *VBase = 0;
143
144 // Get the virtual base.
145 if ((*Start)->isVirtual()) {
146 VBase =
147 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
148 ++Start;
149 }
150
Ken Dycka1a4ae32011-03-22 00:53:26 +0000151 CharUnits NonVirtualOffset =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000152 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallcf142162010-08-07 06:22:56 +0000153 Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000154
155 // Get the base pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000156 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000157 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlssond829a022010-04-24 21:06:20 +0000158
Ken Dycka1a4ae32011-03-22 00:53:26 +0000159 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlssond829a022010-04-24 21:06:20 +0000160 // Just cast back.
161 return Builder.CreateBitCast(Value, BasePtrTy);
162 }
163
164 llvm::BasicBlock *CastNull = 0;
165 llvm::BasicBlock *CastNotNull = 0;
166 llvm::BasicBlock *CastEnd = 0;
167
168 if (NullCheckValue) {
169 CastNull = createBasicBlock("cast.null");
170 CastNotNull = createBasicBlock("cast.notnull");
171 CastEnd = createBasicBlock("cast.end");
172
Anders Carlsson98981b12011-04-11 00:30:07 +0000173 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssond829a022010-04-24 21:06:20 +0000174 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
175 EmitBlock(CastNotNull);
176 }
177
178 llvm::Value *VirtualOffset = 0;
179
Anders Carlssona376b532011-01-29 03:18:56 +0000180 if (VBase) {
181 if (Derived->hasAttr<FinalAttr>()) {
182 VirtualOffset = 0;
183
184 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
185
Ken Dycka1a4ae32011-03-22 00:53:26 +0000186 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
187 NonVirtualOffset += VBaseOffset;
Anders Carlssona376b532011-01-29 03:18:56 +0000188 } else
189 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
190 }
Anders Carlssond829a022010-04-24 21:06:20 +0000191
192 // Apply the offsets.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000193 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000194 NonVirtualOffset,
Anders Carlssond829a022010-04-24 21:06:20 +0000195 VirtualOffset);
196
197 // Cast back.
198 Value = Builder.CreateBitCast(Value, BasePtrTy);
199
200 if (NullCheckValue) {
201 Builder.CreateBr(CastEnd);
202 EmitBlock(CastNull);
203 Builder.CreateBr(CastEnd);
204 EmitBlock(CastEnd);
205
Jay Foad20c0f022011-03-30 11:28:58 +0000206 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssond829a022010-04-24 21:06:20 +0000207 PHI->addIncoming(Value, CastNotNull);
208 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
209 CastNull);
210 Value = PHI;
211 }
212
213 return Value;
214}
215
216llvm::Value *
Anders Carlsson8c793172009-11-23 17:57:54 +0000217CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000218 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000219 CastExpr::path_const_iterator PathBegin,
220 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000221 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000222 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000223
Anders Carlsson8c793172009-11-23 17:57:54 +0000224 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000225 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000226 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Anders Carlsson8c793172009-11-23 17:57:54 +0000227
Anders Carlsson600f7372010-01-31 01:43:37 +0000228 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000229 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlsson600f7372010-01-31 01:43:37 +0000230
231 if (!NonVirtualOffset) {
232 // No offset, we can just cast back.
233 return Builder.CreateBitCast(Value, DerivedPtrTy);
234 }
235
Anders Carlsson8c793172009-11-23 17:57:54 +0000236 llvm::BasicBlock *CastNull = 0;
237 llvm::BasicBlock *CastNotNull = 0;
238 llvm::BasicBlock *CastEnd = 0;
239
240 if (NullCheckValue) {
241 CastNull = createBasicBlock("cast.null");
242 CastNotNull = createBasicBlock("cast.notnull");
243 CastEnd = createBasicBlock("cast.end");
244
Anders Carlsson98981b12011-04-11 00:30:07 +0000245 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000246 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
247 EmitBlock(CastNotNull);
248 }
249
Anders Carlsson600f7372010-01-31 01:43:37 +0000250 // Apply the offset.
251 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
252 Value = Builder.CreateSub(Value, NonVirtualOffset);
253 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
254
255 // Just cast.
256 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000257
258 if (NullCheckValue) {
259 Builder.CreateBr(CastEnd);
260 EmitBlock(CastNull);
261 Builder.CreateBr(CastEnd);
262 EmitBlock(CastEnd);
263
Jay Foad20c0f022011-03-30 11:28:58 +0000264 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000265 PHI->addIncoming(Value, CastNotNull);
266 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
267 CastNull);
268 Value = PHI;
269 }
270
271 return Value;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000272}
Anders Carlsson093bdff2010-03-30 03:27:09 +0000273
Anders Carlssone36a6b32010-01-02 01:01:18 +0000274/// GetVTTParameter - Return the VTT parameter that should be passed to a
275/// base constructor/destructor with virtual bases.
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000276static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
277 bool ForVirtualBase) {
Anders Carlssona864caf2010-03-23 04:11:45 +0000278 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000279 // This constructor/destructor does not need a VTT parameter.
280 return 0;
281 }
282
283 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
284 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000285
Anders Carlssone36a6b32010-01-02 01:01:18 +0000286 llvm::Value *VTT;
287
John McCall5c60a6f2010-02-18 19:59:28 +0000288 uint64_t SubVTTIndex;
289
290 // If the record matches the base, this is the complete ctor/dtor
291 // variant calling the base variant in a class with virtual bases.
292 if (RD == Base) {
Anders Carlssona864caf2010-03-23 04:11:45 +0000293 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000294 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000295 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000296 SubVTTIndex = 0;
297 } else {
Anders Carlsson859b3062010-05-02 23:53:25 +0000298 const ASTRecordLayout &Layout =
299 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck16ffcac2011-03-24 01:21:01 +0000300 CharUnits BaseOffset = ForVirtualBase ?
301 Layout.getVBaseClassOffset(Base) :
302 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000303
304 SubVTTIndex =
305 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000306 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
307 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000308
Anders Carlssona864caf2010-03-23 04:11:45 +0000309 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000310 // A VTT parameter was passed to the constructor, use it.
311 VTT = CGF.LoadCXXVTT();
312 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
313 } else {
314 // We're the complete constructor, so get the VTT by name.
Anders Carlsson883fc722011-01-29 19:16:51 +0000315 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000316 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
317 }
318
319 return VTT;
320}
321
John McCall1d987562010-07-21 01:23:41 +0000322namespace {
John McCallf99a6312010-07-21 05:30:47 +0000323 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000324 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000325 const CXXRecordDecl *BaseClass;
326 bool BaseIsVirtual;
327 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
328 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000329
John McCall30317fd2011-07-12 20:27:29 +0000330 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +0000331 const CXXRecordDecl *DerivedClass =
332 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
333
334 const CXXDestructorDecl *D = BaseClass->getDestructor();
335 llvm::Value *Addr =
336 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
337 DerivedClass, BaseClass,
338 BaseIsVirtual);
339 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall1d987562010-07-21 01:23:41 +0000340 }
341 };
John McCall769250e2010-09-17 02:31:44 +0000342
343 /// A visitor which checks whether an initializer uses 'this' in a
344 /// way which requires the vtable to be properly set.
345 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
346 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
347
348 bool UsesThis;
349
350 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
351
352 // Black-list all explicit and implicit references to 'this'.
353 //
354 // Do we need to worry about external references to 'this' derived
355 // from arbitrary code? If so, then anything which runs arbitrary
356 // external code might potentially access the vtable.
357 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
358 };
359}
360
361static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
362 DynamicThisUseChecker Checker(C);
363 Checker.Visit(const_cast<Expr*>(Init));
364 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000365}
366
Anders Carlssonfb404882009-12-24 22:46:43 +0000367static void EmitBaseInitializer(CodeGenFunction &CGF,
368 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000369 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000370 CXXCtorType CtorType) {
371 assert(BaseInit->isBaseInitializer() &&
372 "Must have base initializer!");
373
374 llvm::Value *ThisPtr = CGF.LoadCXXThis();
375
376 const Type *BaseType = BaseInit->getBaseClass();
377 CXXRecordDecl *BaseClassDecl =
378 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
379
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000380 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000381
382 // The base constructor doesn't construct virtual bases.
383 if (CtorType == Ctor_Base && isBaseVirtual)
384 return;
385
John McCall769250e2010-09-17 02:31:44 +0000386 // If the initializer for the base (other than the constructor
387 // itself) accesses 'this' in any way, we need to initialize the
388 // vtables.
389 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
390 CGF.InitializeVTablePointers(ClassDecl);
391
John McCall6ce74722010-02-16 04:15:37 +0000392 // We can pretend to be a complete class because it only matters for
393 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000394 llvm::Value *V =
395 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000396 BaseClassDecl,
397 isBaseVirtual);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000398 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall8d6fc952011-08-25 20:40:09 +0000399 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000400 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000401 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000402 AggValueSlot::DoesNotNeedGCBarriers,
403 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000404
405 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000406
Anders Carlsson6dc07d42011-02-28 00:33:03 +0000407 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000408 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000409 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
410 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000411}
412
Douglas Gregor94f9a482010-05-05 05:51:00 +0000413static void EmitAggMemberInitializer(CodeGenFunction &CGF,
414 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000415 Expr *Init,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000416 llvm::Value *ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000417 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000418 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000419 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000420 if (Index == ArrayIndexes.size()) {
John McCallbd309292010-07-06 01:34:17 +0000421 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000422
423 LValue LV = LHS;
Douglas Gregor94f9a482010-05-05 05:51:00 +0000424 if (ArrayIndexVar) {
425 // If we have an array index variable, load it and use it as an offset.
426 // Then, increment the value.
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000427 llvm::Value *Dest = LHS.getAddress();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000428 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");
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000432 CGF.Builder.CreateStore(Next, ArrayIndexVar);
433
434 // Update the LValue.
435 LV.setAddress(Dest);
Eli Friedmana0544d62011-12-03 04:14:32 +0000436 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000437 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000438 }
John McCall7a626f62010-09-15 10:14:12 +0000439
John McCall31168b02011-06-15 23:02:42 +0000440 if (!CGF.hasAggregateLLVMType(T)) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000441 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
John McCall31168b02011-06-15 23:02:42 +0000442 } else if (T->isAnyComplexType()) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000443 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000444 LV.isVolatileQualified());
445 } else {
John McCall8d6fc952011-08-25 20:40:09 +0000446 AggValueSlot Slot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000447 AggValueSlot::forLValue(LV,
448 AggValueSlot::IsDestructed,
449 AggValueSlot::DoesNotNeedGCBarriers,
450 AggValueSlot::IsNotAliased);
John McCall31168b02011-06-15 23:02:42 +0000451
Eli Friedman6ae63022012-02-14 02:15:49 +0000452 CGF.EmitAggExpr(Init, Slot);
John McCall31168b02011-06-15 23:02:42 +0000453 }
Douglas Gregor94f9a482010-05-05 05:51:00 +0000454
455 return;
456 }
457
458 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
459 assert(Array && "Array initialization without the array type?");
460 llvm::Value *IndexVar
Eli Friedman6ae63022012-02-14 02:15:49 +0000461 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000462 assert(IndexVar && "Array index variable not loaded");
463
464 // Initialize this index variable to zero.
465 llvm::Value* Zero
466 = llvm::Constant::getNullValue(
467 CGF.ConvertType(CGF.getContext().getSizeType()));
468 CGF.Builder.CreateStore(Zero, IndexVar);
469
470 // Start the loop with a block that tests the condition.
471 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
472 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
473
474 CGF.EmitBlock(CondBlock);
475
476 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
477 // Generate: if (loop-index < number-of-elements) fall to the loop body,
478 // otherwise, go to the block after the for-loop.
479 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000480 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000481 llvm::Value *NumElementsPtr =
482 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000483 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
484 "isless");
485
486 // If the condition is true, execute the body.
487 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
488
489 CGF.EmitBlock(ForBody);
490 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
491
492 {
John McCallbd309292010-07-06 01:34:17 +0000493 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000494
495 // Inside the loop body recurse to emit the inner loop or, eventually, the
496 // constructor call.
Eli Friedman6ae63022012-02-14 02:15:49 +0000497 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
498 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000499 }
500
501 CGF.EmitBlock(ContinueBlock);
502
503 // Emit the increment of the loop counter.
504 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
505 Counter = CGF.Builder.CreateLoad(IndexVar);
506 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
507 CGF.Builder.CreateStore(NextVal, IndexVar);
508
509 // Finally, branch back up to the condition for the next iteration.
510 CGF.EmitBranch(CondBlock);
511
512 // Emit the fall-through block.
513 CGF.EmitBlock(AfterFor, true);
514}
John McCall1d987562010-07-21 01:23:41 +0000515
516namespace {
John McCallcda666c2010-07-21 07:22:38 +0000517 struct CallMemberDtor : EHScopeStack::Cleanup {
Eli Friedman6ae63022012-02-14 02:15:49 +0000518 llvm::Value *V;
John McCall1d987562010-07-21 01:23:41 +0000519 CXXDestructorDecl *Dtor;
520
Eli Friedman6ae63022012-02-14 02:15:49 +0000521 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
522 : V(V), Dtor(Dtor) {}
John McCall1d987562010-07-21 01:23:41 +0000523
John McCall30317fd2011-07-12 20:27:29 +0000524 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall1d987562010-07-21 01:23:41 +0000525 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Eli Friedman6ae63022012-02-14 02:15:49 +0000526 V);
John McCall1d987562010-07-21 01:23:41 +0000527 }
528 };
529}
Sebastian Redl22653ba2011-08-30 19:58:05 +0000530
531static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
532 bool Moving) {
533 return Moving ? Record->hasTrivialMoveConstructor() :
534 Record->hasTrivialCopyConstructor();
535}
Eli Friedman6ae63022012-02-14 02:15:49 +0000536
537static void EmitInitializerForField(CodeGenFunction &CGF, FieldDecl *Field,
538 LValue LHS, Expr *Init,
539 ArrayRef<VarDecl *> ArrayIndexes);
540
Anders Carlssonfb404882009-12-24 22:46:43 +0000541static void EmitMemberInitializer(CodeGenFunction &CGF,
542 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000543 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000544 const CXXConstructorDecl *Constructor,
545 FunctionArgList &Args) {
Francois Pichetd583da02010-12-04 09:14:42 +0000546 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000547 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000548 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlssonfb404882009-12-24 22:46:43 +0000549
550 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000551 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000552 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000553
554 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCallc4094932010-05-21 01:18:57 +0000555 LValue LHS;
Anders Carlssondb78f0a2010-01-29 05:24:29 +0000556
Anders Carlssonfb404882009-12-24 22:46:43 +0000557 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichetd583da02010-12-04 09:14:42 +0000558 if (MemberInit->isIndirectMemberInitializer()) {
559 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
560 MemberInit->getIndirectMember(), 0);
561 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000562 } else {
563 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000564 }
565
Eli Friedman6ae63022012-02-14 02:15:49 +0000566 // Special case: if we are in a copy or move constructor, and we are copying
567 // an array of PODs or classes with trivial copy constructors, ignore the
568 // AST and perform the copy we know is equivalent.
569 // FIXME: This is hacky at best... if we had a bit more explicit information
570 // in the AST, we could generalize it more easily.
571 const ConstantArrayType *Array
572 = CGF.getContext().getAsConstantArrayType(FieldType);
573 if (Array && Constructor->isImplicitlyDefined() &&
574 Constructor->isCopyOrMoveConstructor()) {
575 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
576 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
577 if (BaseElementTy.isPODType(CGF.getContext()) ||
578 (Record && hasTrivialCopyOrMoveConstructor(Record,
579 Constructor->isMoveConstructor()))) {
580 // Find the source pointer. We knows it's the last argument because
581 // we know we're in a copy constructor.
582 unsigned SrcArgIndex = Args.size() - 1;
583 llvm::Value *SrcPtr
584 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
585 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
586
587 // Copy the aggregate.
588 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
589 LHS.isVolatileQualified());
590 return;
591 }
592 }
593
594 ArrayRef<VarDecl *> ArrayIndexes;
595 if (MemberInit->getNumArrayIndices())
596 ArrayIndexes = MemberInit->getArrayIndexes();
597 EmitInitializerForField(CGF, Field, LHS, MemberInit->getInit(), ArrayIndexes);
598}
599
600static void EmitInitializerForField(CodeGenFunction &CGF, FieldDecl *Field,
601 LValue LHS, Expr *Init,
602 ArrayRef<VarDecl *> ArrayIndexes) {
603 QualType FieldType = Field->getType();
604 if (!CGF.hasAggregateLLVMType(FieldType)) {
John McCall31168b02011-06-15 23:02:42 +0000605 if (LHS.isSimple()) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000606 CGF.EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000607 } else {
Eli Friedman6ae63022012-02-14 02:15:49 +0000608 RValue RHS = RValue::get(CGF.EmitScalarExpr(Init));
John McCall55e1fbc2011-06-25 02:11:03 +0000609 CGF.EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000610 }
Eli Friedman6ae63022012-02-14 02:15:49 +0000611 } else if (FieldType->isAnyComplexType()) {
612 CGF.EmitComplexExprIntoAddr(Init, LHS.getAddress(),
Anders Carlssonfb404882009-12-24 22:46:43 +0000613 LHS.isVolatileQualified());
614 } else {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000615 llvm::Value *ArrayIndexVar = 0;
Eli Friedman6ae63022012-02-14 02:15:49 +0000616 if (ArrayIndexes.size()) {
Chris Lattner2192fe52011-07-18 04:24:23 +0000617 llvm::Type *SizeTy
Douglas Gregor94f9a482010-05-05 05:51:00 +0000618 = CGF.ConvertType(CGF.getContext().getSizeType());
619
620 // The LHS is a pointer to the first object we'll be constructing, as
621 // a flat array.
Eli Friedman6ae63022012-02-14 02:15:49 +0000622 QualType BaseElementTy = CGF.getContext().getBaseElementType(FieldType);
Chris Lattner2192fe52011-07-18 04:24:23 +0000623 llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000624 BasePtr = llvm::PointerType::getUnqual(BasePtr);
625 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
626 BasePtr);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +0000627 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000628
629 // Create an array index that will be used to walk over all of the
630 // objects we're constructing.
631 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
632 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
633 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
634
Douglas Gregor94f9a482010-05-05 05:51:00 +0000635
636 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000637 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
638 CGF.EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000639 }
640
Eli Friedman6ae63022012-02-14 02:15:49 +0000641 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar, FieldType,
642 ArrayIndexes, 0);
Anders Carlssonba631672010-02-06 19:50:17 +0000643
Anders Carlsson6dc07d42011-02-28 00:33:03 +0000644 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlssonba631672010-02-06 19:50:17 +0000645 return;
646
Douglas Gregor94f9a482010-05-05 05:51:00 +0000647 // FIXME: If we have an array of classes w/ non-trivial destructors,
648 // we need to destroy in reverse order of construction along the exception
649 // path.
Anders Carlssonba631672010-02-06 19:50:17 +0000650 const RecordType *RT = FieldType->getAs<RecordType>();
651 if (!RT)
652 return;
653
654 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall1d987562010-07-21 01:23:41 +0000655 if (!RD->hasTrivialDestructor())
Eli Friedman6ae63022012-02-14 02:15:49 +0000656 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
John McCallcda666c2010-07-21 07:22:38 +0000657 RD->getDestructor());
Anders Carlssonfb404882009-12-24 22:46:43 +0000658 }
659}
660
John McCallf8ff7b92010-02-23 00:48:20 +0000661/// Checks whether the given constructor is a valid subject for the
662/// complete-to-base constructor delegation optimization, i.e.
663/// emitting the complete constructor as a simple call to the base
664/// constructor.
665static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
666
667 // Currently we disable the optimization for classes with virtual
668 // bases because (1) the addresses of parameter variables need to be
669 // consistent across all initializers but (2) the delegate function
670 // call necessarily creates a second copy of the parameter variable.
671 //
672 // The limiting example (purely theoretical AFAIK):
673 // struct A { A(int &c) { c++; } };
674 // struct B : virtual A {
675 // B(int count) : A(count) { printf("%d\n", count); }
676 // };
677 // ...although even this example could in principle be emitted as a
678 // delegation since the address of the parameter doesn't escape.
679 if (Ctor->getParent()->getNumVBases()) {
680 // TODO: white-list trivial vbase initializers. This case wouldn't
681 // be subject to the restrictions below.
682
683 // TODO: white-list cases where:
684 // - there are no non-reference parameters to the constructor
685 // - the initializers don't access any non-reference parameters
686 // - the initializers don't take the address of non-reference
687 // parameters
688 // - etc.
689 // If we ever add any of the above cases, remember that:
690 // - function-try-blocks will always blacklist this optimization
691 // - we need to perform the constructor prologue and cleanup in
692 // EmitConstructorBody.
693
694 return false;
695 }
696
697 // We also disable the optimization for variadic functions because
698 // it's impossible to "re-pass" varargs.
699 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
700 return false;
701
Alexis Hunt61bc1732011-05-01 07:04:31 +0000702 // FIXME: Decide if we can do a delegation of a delegating constructor.
703 if (Ctor->isDelegatingConstructor())
704 return false;
705
John McCallf8ff7b92010-02-23 00:48:20 +0000706 return true;
707}
708
John McCallb81884d2010-02-19 09:25:03 +0000709/// EmitConstructorBody - Emits the body of the current constructor.
710void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
711 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
712 CXXCtorType CtorType = CurGD.getCtorType();
713
John McCallf8ff7b92010-02-23 00:48:20 +0000714 // Before we go any further, try the complete->base constructor
715 // delegation optimization.
716 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld76c1db2010-08-11 21:04:37 +0000717 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher7cdf9482011-10-13 21:45:18 +0000718 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000719 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
720 return;
721 }
722
John McCallb81884d2010-02-19 09:25:03 +0000723 Stmt *Body = Ctor->getBody();
724
John McCallf8ff7b92010-02-23 00:48:20 +0000725 // Enter the function-try-block before the constructor prologue if
726 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000727 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000728 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000729 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000730
John McCallbd309292010-07-06 01:34:17 +0000731 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCallb81884d2010-02-19 09:25:03 +0000732
John McCallf8ff7b92010-02-23 00:48:20 +0000733 // Emit the constructor prologue, i.e. the base and member
734 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000735 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000736
737 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000738 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000739 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
740 else if (Body)
741 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000742
743 // Emit any cleanup blocks associated with the member or base
744 // initializers, which includes (along the exceptional path) the
745 // destructors for those members and bases that were fully
746 // constructed.
John McCallbd309292010-07-06 01:34:17 +0000747 PopCleanupBlocks(CleanupDepth);
John McCallb81884d2010-02-19 09:25:03 +0000748
John McCallf8ff7b92010-02-23 00:48:20 +0000749 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000750 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000751}
752
Anders Carlssonfb404882009-12-24 22:46:43 +0000753/// EmitCtorPrologue - This routine generates necessary code to initialize
754/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +0000755void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000756 CXXCtorType CtorType,
757 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +0000758 if (CD->isDelegatingConstructor())
759 return EmitDelegatingCXXConstructorCall(CD, Args);
760
Anders Carlssonfb404882009-12-24 22:46:43 +0000761 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +0000762
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000763 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlssonfb404882009-12-24 22:46:43 +0000764
Anders Carlssonfb404882009-12-24 22:46:43 +0000765 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
766 E = CD->init_end();
767 B != E; ++B) {
Alexis Hunt1d792652011-01-08 20:30:50 +0000768 CXXCtorInitializer *Member = (*B);
Anders Carlssonfb404882009-12-24 22:46:43 +0000769
Alexis Hunt271c3682011-05-03 20:19:28 +0000770 if (Member->isBaseInitializer()) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000771 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Alexis Hunt271c3682011-05-03 20:19:28 +0000772 } else {
773 assert(Member->isAnyMemberInitializer() &&
774 "Delegating initializer on non-delegating constructor");
Anders Carlsson5dc86332010-02-02 19:58:43 +0000775 MemberInitializers.push_back(Member);
Alexis Hunt271c3682011-05-03 20:19:28 +0000776 }
Anders Carlssonfb404882009-12-24 22:46:43 +0000777 }
778
Anders Carlssond5895932010-03-28 21:07:49 +0000779 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +0000780
John McCallbd309292010-07-06 01:34:17 +0000781 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregor94f9a482010-05-05 05:51:00 +0000782 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlssonfb404882009-12-24 22:46:43 +0000783}
784
Anders Carlsson49c0bd22011-05-15 17:36:21 +0000785static bool
786FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
787
788static bool
789HasTrivialDestructorBody(ASTContext &Context,
790 const CXXRecordDecl *BaseClassDecl,
791 const CXXRecordDecl *MostDerivedClassDecl)
792{
793 // If the destructor is trivial we don't have to check anything else.
794 if (BaseClassDecl->hasTrivialDestructor())
795 return true;
796
797 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
798 return false;
799
800 // Check fields.
801 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
802 E = BaseClassDecl->field_end(); I != E; ++I) {
803 const FieldDecl *Field = *I;
804
805 if (!FieldHasTrivialDestructorBody(Context, Field))
806 return false;
807 }
808
809 // Check non-virtual bases.
810 for (CXXRecordDecl::base_class_const_iterator I =
811 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
812 I != E; ++I) {
813 if (I->isVirtual())
814 continue;
815
816 const CXXRecordDecl *NonVirtualBase =
817 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
818 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
819 MostDerivedClassDecl))
820 return false;
821 }
822
823 if (BaseClassDecl == MostDerivedClassDecl) {
824 // Check virtual bases.
825 for (CXXRecordDecl::base_class_const_iterator I =
826 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
827 I != E; ++I) {
828 const CXXRecordDecl *VirtualBase =
829 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
830 if (!HasTrivialDestructorBody(Context, VirtualBase,
831 MostDerivedClassDecl))
832 return false;
833 }
834 }
835
836 return true;
837}
838
839static bool
840FieldHasTrivialDestructorBody(ASTContext &Context,
841 const FieldDecl *Field)
842{
843 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
844
845 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
846 if (!RT)
847 return true;
848
849 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
850 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
851}
852
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000853/// CanSkipVTablePointerInitialization - Check whether we need to initialize
854/// any vtable pointers before calling this destructor.
855static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +0000856 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000857 if (!Dtor->hasTrivialBody())
858 return false;
859
860 // Check the fields.
861 const CXXRecordDecl *ClassDecl = Dtor->getParent();
862 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
863 E = ClassDecl->field_end(); I != E; ++I) {
864 const FieldDecl *Field = *I;
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000865
Anders Carlsson49c0bd22011-05-15 17:36:21 +0000866 if (!FieldHasTrivialDestructorBody(Context, Field))
867 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000868 }
869
870 return true;
871}
872
John McCallb81884d2010-02-19 09:25:03 +0000873/// EmitDestructorBody - Emits the body of the current destructor.
874void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
875 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
876 CXXDtorType DtorType = CurGD.getDtorType();
877
John McCallf99a6312010-07-21 05:30:47 +0000878 // The call to operator delete in a deleting destructor happens
879 // outside of the function-try-block, which means it's always
880 // possible to delegate the destructor body to the complete
881 // destructor. Do so.
882 if (DtorType == Dtor_Deleting) {
883 EnterDtorCleanups(Dtor, Dtor_Deleting);
884 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
885 LoadCXXThis());
886 PopCleanupBlock();
887 return;
888 }
889
John McCallb81884d2010-02-19 09:25:03 +0000890 Stmt *Body = Dtor->getBody();
891
892 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +0000893 // anything else.
894 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +0000895 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000896 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000897
John McCallf99a6312010-07-21 05:30:47 +0000898 // Enter the epilogue cleanups.
899 RunCleanupsScope DtorEpilogue(*this);
900
John McCallb81884d2010-02-19 09:25:03 +0000901 // If this is the complete variant, just invoke the base variant;
902 // the epilogue will destruct the virtual bases. But we can't do
903 // this optimization if the body is a function-try-block, because
904 // we'd introduce *two* handler blocks.
John McCallf99a6312010-07-21 05:30:47 +0000905 switch (DtorType) {
906 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
907
908 case Dtor_Complete:
909 // Enter the cleanup scopes for virtual bases.
910 EnterDtorCleanups(Dtor, Dtor_Complete);
911
912 if (!isTryBody) {
913 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
914 LoadCXXThis());
915 break;
916 }
917 // Fallthrough: act like we're in the base variant.
John McCallb81884d2010-02-19 09:25:03 +0000918
John McCallf99a6312010-07-21 05:30:47 +0000919 case Dtor_Base:
920 // Enter the cleanup scopes for fields and non-virtual bases.
921 EnterDtorCleanups(Dtor, Dtor_Base);
922
923 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +0000924 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
925 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +0000926
927 if (isTryBody)
928 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
929 else if (Body)
930 EmitStmt(Body);
931 else {
932 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
933 // nothing to do besides what's in the epilogue
934 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +0000935 // -fapple-kext must inline any call to this dtor into
936 // the caller's body.
937 if (getContext().getLangOptions().AppleKext)
938 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +0000939 break;
John McCallb81884d2010-02-19 09:25:03 +0000940 }
941
John McCallf99a6312010-07-21 05:30:47 +0000942 // Jump out through the epilogue cleanups.
943 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000944
945 // Exit the try if applicable.
946 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000947 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000948}
949
John McCallf99a6312010-07-21 05:30:47 +0000950namespace {
951 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +0000952 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000953 CallDtorDelete() {}
954
John McCall30317fd2011-07-12 20:27:29 +0000955 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +0000956 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
957 const CXXRecordDecl *ClassDecl = Dtor->getParent();
958 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
959 CGF.getContext().getTagDeclType(ClassDecl));
960 }
961 };
962
John McCall4bd0fb12011-07-12 16:41:08 +0000963 class DestroyField : public EHScopeStack::Cleanup {
964 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +0000965 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +0000966 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +0000967
John McCall4bd0fb12011-07-12 16:41:08 +0000968 public:
969 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
970 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +0000971 : field(field), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +0000972 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +0000973
John McCall30317fd2011-07-12 20:27:29 +0000974 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +0000975 // Find the address of the field.
976 llvm::Value *thisValue = CGF.LoadCXXThis();
977 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
978 assert(LV.isSimple());
979
980 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +0000981 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +0000982 }
983 };
984}
985
Anders Carlssonfb404882009-12-24 22:46:43 +0000986/// EmitDtorEpilogue - Emit all code that comes at the end of class's
987/// destructor. This is to call destructors on members and base classes
988/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +0000989void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
990 CXXDtorType DtorType) {
Anders Carlssonfb404882009-12-24 22:46:43 +0000991 assert(!DD->isTrivial() &&
992 "Should not emit dtor epilogue for trivial dtor!");
993
John McCallf99a6312010-07-21 05:30:47 +0000994 // The deleting-destructor phase just needs to call the appropriate
995 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +0000996 if (DtorType == Dtor_Deleting) {
997 assert(DD->getOperatorDelete() &&
998 "operator delete missing - EmitDtorEpilogue");
John McCallcda666c2010-07-21 07:22:38 +0000999 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall5c60a6f2010-02-18 19:59:28 +00001000 return;
1001 }
1002
John McCallf99a6312010-07-21 05:30:47 +00001003 const CXXRecordDecl *ClassDecl = DD->getParent();
1004
Richard Smith20104042011-09-18 12:11:43 +00001005 // Unions have no bases and do not call field destructors.
1006 if (ClassDecl->isUnion())
1007 return;
1008
John McCallf99a6312010-07-21 05:30:47 +00001009 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001010 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001011
1012 // We push them in the forward order so that they'll be popped in
1013 // the reverse order.
1014 for (CXXRecordDecl::base_class_const_iterator I =
1015 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall5c60a6f2010-02-18 19:59:28 +00001016 I != E; ++I) {
1017 const CXXBaseSpecifier &Base = *I;
1018 CXXRecordDecl *BaseClassDecl
1019 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1020
1021 // Ignore trivial destructors.
1022 if (BaseClassDecl->hasTrivialDestructor())
1023 continue;
John McCallf99a6312010-07-21 05:30:47 +00001024
John McCallcda666c2010-07-21 07:22:38 +00001025 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1026 BaseClassDecl,
1027 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001028 }
John McCallf99a6312010-07-21 05:30:47 +00001029
John McCall5c60a6f2010-02-18 19:59:28 +00001030 return;
1031 }
1032
1033 assert(DtorType == Dtor_Base);
John McCallf99a6312010-07-21 05:30:47 +00001034
1035 // Destroy non-virtual bases.
1036 for (CXXRecordDecl::base_class_const_iterator I =
1037 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1038 const CXXBaseSpecifier &Base = *I;
1039
1040 // Ignore virtual bases.
1041 if (Base.isVirtual())
1042 continue;
1043
1044 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1045
1046 // Ignore trivial destructors.
1047 if (BaseClassDecl->hasTrivialDestructor())
1048 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001049
John McCallcda666c2010-07-21 07:22:38 +00001050 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1051 BaseClassDecl,
1052 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001053 }
1054
1055 // Destroy direct fields.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001056 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlssonfb404882009-12-24 22:46:43 +00001057 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1058 E = ClassDecl->field_end(); I != E; ++I) {
John McCall4bd0fb12011-07-12 16:41:08 +00001059 const FieldDecl *field = *I;
1060 QualType type = field->getType();
1061 QualType::DestructionKind dtorKind = type.isDestructedType();
1062 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001063
John McCall4bd0fb12011-07-12 16:41:08 +00001064 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1065 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1066 getDestroyer(dtorKind),
1067 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001068 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001069}
1070
John McCallf677a8e2011-07-13 06:10:41 +00001071/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1072/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001073///
John McCallf677a8e2011-07-13 06:10:41 +00001074/// \param ctor the constructor to call for each element
1075/// \param argBegin,argEnd the arguments to evaluate and pass to the
1076/// constructor
1077/// \param arrayType the type of the array to initialize
1078/// \param arrayBegin an arrayType*
1079/// \param zeroInitialize true if each element should be
1080/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001081void
John McCallf677a8e2011-07-13 06:10:41 +00001082CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1083 const ConstantArrayType *arrayType,
1084 llvm::Value *arrayBegin,
1085 CallExpr::const_arg_iterator argBegin,
1086 CallExpr::const_arg_iterator argEnd,
1087 bool zeroInitialize) {
1088 QualType elementType;
1089 llvm::Value *numElements =
1090 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001091
John McCallf677a8e2011-07-13 06:10:41 +00001092 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1093 argBegin, argEnd, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001094}
1095
John McCallf677a8e2011-07-13 06:10:41 +00001096/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1097/// constructor for each of several members of an array.
1098///
1099/// \param ctor the constructor to call for each element
1100/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001101/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001102/// \param argBegin,argEnd the arguments to evaluate and pass to the
1103/// constructor
1104/// \param arrayBegin a T*, where T is the type constructed by ctor
1105/// \param zeroInitialize true if each element should be
1106/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001107void
John McCallf677a8e2011-07-13 06:10:41 +00001108CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1109 llvm::Value *numElements,
1110 llvm::Value *arrayBegin,
1111 CallExpr::const_arg_iterator argBegin,
1112 CallExpr::const_arg_iterator argEnd,
1113 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001114
1115 // It's legal for numElements to be zero. This can happen both
1116 // dynamically, because x can be zero in 'new A[x]', and statically,
1117 // because of GCC extensions that permit zero-length arrays. There
1118 // are probably legitimate places where we could assume that this
1119 // doesn't happen, but it's not clear that it's worth it.
1120 llvm::BranchInst *zeroCheckBranch = 0;
1121
1122 // Optimize for a constant count.
1123 llvm::ConstantInt *constantCount
1124 = dyn_cast<llvm::ConstantInt>(numElements);
1125 if (constantCount) {
1126 // Just skip out if the constant count is zero.
1127 if (constantCount->isZero()) return;
1128
1129 // Otherwise, emit the check.
1130 } else {
1131 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1132 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1133 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1134 EmitBlock(loopBB);
1135 }
1136
John McCallf677a8e2011-07-13 06:10:41 +00001137 // Find the end of the array.
1138 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1139 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001140
John McCallf677a8e2011-07-13 06:10:41 +00001141 // Enter the loop, setting up a phi for the current location to initialize.
1142 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1143 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1144 EmitBlock(loopBB);
1145 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1146 "arrayctor.cur");
1147 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001148
Anders Carlsson27da15b2010-01-01 20:29:01 +00001149 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001150
1151 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001152
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001153 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001154 if (zeroInitialize)
1155 EmitNullInitialization(cur, type);
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001156
Anders Carlsson27da15b2010-01-01 20:29:01 +00001157 // C++ [class.temporary]p4:
1158 // There are two contexts in which temporaries are destroyed at a different
1159 // point than the end of the full-expression. The first context is when a
1160 // default constructor is called to initialize an element of an array.
1161 // If the constructor has one or more default arguments, the destruction of
1162 // every temporary created in a default argument expression is sequenced
1163 // before the construction of the next array element, if any.
1164
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001165 {
John McCallbd309292010-07-06 01:34:17 +00001166 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001167
John McCallf677a8e2011-07-13 06:10:41 +00001168 // Evaluate the constructor and its arguments in a regular
1169 // partial-destroy cleanup.
1170 if (getLangOptions().Exceptions &&
1171 !ctor->getParent()->hasTrivialDestructor()) {
1172 Destroyer *destroyer = destroyCXXObject;
1173 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1174 }
1175
1176 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1177 cur, argBegin, argEnd);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001178 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001179
John McCallf677a8e2011-07-13 06:10:41 +00001180 // Go to the next element.
1181 llvm::Value *next =
1182 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1183 "arrayctor.next");
1184 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001185
John McCallf677a8e2011-07-13 06:10:41 +00001186 // Check whether that's the end of the loop.
1187 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1188 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1189 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001190
John McCall6549b312011-07-13 07:37:11 +00001191 // Patch the earlier check to skip over the loop.
1192 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1193
John McCallf677a8e2011-07-13 06:10:41 +00001194 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001195}
1196
John McCall82fe67b2011-07-09 01:37:26 +00001197void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1198 llvm::Value *addr,
1199 QualType type) {
1200 const RecordType *rtype = type->castAs<RecordType>();
1201 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1202 const CXXDestructorDecl *dtor = record->getDestructor();
1203 assert(!dtor->isTrivial());
1204 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1205 addr);
1206}
1207
Anders Carlsson27da15b2010-01-01 20:29:01 +00001208void
1209CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlssone11f9ce2010-05-02 23:20:53 +00001210 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001211 llvm::Value *This,
1212 CallExpr::const_arg_iterator ArgBeg,
1213 CallExpr::const_arg_iterator ArgEnd) {
Devang Patelb6ed3692011-02-22 20:55:26 +00001214
1215 CGDebugInfo *DI = getDebugInfo();
1216 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
Eric Christopher034ba7e2012-02-01 21:44:56 +00001217 // If debug info for this class has not been emitted then this is the
1218 // right time to do so.
Devang Patelb6ed3692011-02-22 20:55:26 +00001219 const CXXRecordDecl *Parent = D->getParent();
1220 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1221 Parent->getLocation());
1222 }
1223
John McCallca972cd2010-02-06 00:25:16 +00001224 if (D->isTrivial()) {
1225 if (ArgBeg == ArgEnd) {
1226 // Trivial default constructor, no codegen required.
1227 assert(D->isDefaultConstructor() &&
1228 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001229 return;
1230 }
John McCallca972cd2010-02-06 00:25:16 +00001231
1232 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001233 assert(D->isCopyOrMoveConstructor() &&
1234 "trivial 1-arg ctor not a copy/move ctor");
John McCallca972cd2010-02-06 00:25:16 +00001235
John McCallca972cd2010-02-06 00:25:16 +00001236 const Expr *E = (*ArgBeg);
1237 QualType Ty = E->getType();
1238 llvm::Value *Src = EmitLValue(E).getAddress();
1239 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001240 return;
1241 }
1242
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001243 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001244 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1245
Anders Carlssone36a6b32010-01-02 01:01:18 +00001246 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001247}
1248
John McCallf8ff7b92010-02-23 00:48:20 +00001249void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001250CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1251 llvm::Value *This, llvm::Value *Src,
1252 CallExpr::const_arg_iterator ArgBeg,
1253 CallExpr::const_arg_iterator ArgEnd) {
1254 if (D->isTrivial()) {
1255 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001256 assert(D->isCopyOrMoveConstructor() &&
1257 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001258 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1259 return;
1260 }
1261 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1262 clang::Ctor_Complete);
1263 assert(D->isInstance() &&
1264 "Trying to emit a member call expr on a static method!");
1265
1266 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1267
1268 CallArgList Args;
1269
1270 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001271 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001272
1273
1274 // Push the src ptr.
1275 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001276 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001277 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001278 Args.add(RValue::get(Src), QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001279
1280 // Skip over first argument (Src).
1281 ++ArgBeg;
1282 CallExpr::const_arg_iterator Arg = ArgBeg;
1283 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1284 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1285 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall32ea9692011-03-11 20:59:21 +00001286 EmitCallArg(Args, *Arg, *I);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001287 }
1288 // Either we've emitted all the call args, or we have a call to a
1289 // variadic function.
1290 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1291 "Extra arguments in non-variadic function!");
1292 // If we still have any arguments, emit them using the type of the argument.
1293 for (; Arg != ArgEnd; ++Arg) {
1294 QualType ArgType = Arg->getType();
John McCall32ea9692011-03-11 20:59:21 +00001295 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001296 }
1297
Eli Friedmanf481cca2011-08-09 17:38:12 +00001298 EmitCall(CGM.getTypes().getFunctionInfo(Args, FPT), Callee,
1299 ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001300}
1301
1302void
John McCallf8ff7b92010-02-23 00:48:20 +00001303CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1304 CXXCtorType CtorType,
1305 const FunctionArgList &Args) {
1306 CallArgList DelegateArgs;
1307
1308 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1309 assert(I != E && "no parameters to constructor");
1310
1311 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001312 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001313 ++I;
1314
1315 // vtt
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001316 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1317 /*ForVirtualBase=*/false)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001318 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001319 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001320
Anders Carlssona864caf2010-03-23 04:11:45 +00001321 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001322 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001323 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001324 ++I;
1325 }
1326 }
1327
1328 // Explicit arguments.
1329 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001330 const VarDecl *param = *I;
1331 EmitDelegateCallArg(DelegateArgs, param);
John McCallf8ff7b92010-02-23 00:48:20 +00001332 }
1333
1334 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1335 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1336 ReturnValueSlot(), DelegateArgs, Ctor);
1337}
1338
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001339namespace {
1340 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1341 const CXXDestructorDecl *Dtor;
1342 llvm::Value *Addr;
1343 CXXDtorType Type;
1344
1345 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1346 CXXDtorType Type)
1347 : Dtor(D), Addr(Addr), Type(Type) {}
1348
John McCall30317fd2011-07-12 20:27:29 +00001349 void Emit(CodeGenFunction &CGF, Flags flags) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001350 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1351 Addr);
1352 }
1353 };
1354}
1355
Alexis Hunt61bc1732011-05-01 07:04:31 +00001356void
1357CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1358 const FunctionArgList &Args) {
1359 assert(Ctor->isDelegatingConstructor());
1360
1361 llvm::Value *ThisPtr = LoadCXXThis();
1362
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001363 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00001364 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00001365 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001366 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001367 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001368 AggValueSlot::DoesNotNeedGCBarriers,
1369 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001370
1371 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001372
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001373 const CXXRecordDecl *ClassDecl = Ctor->getParent();
1374 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) {
1375 CXXDtorType Type =
1376 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1377
1378 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1379 ClassDecl->getDestructor(),
1380 ThisPtr, Type);
1381 }
1382}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001383
Anders Carlsson27da15b2010-01-01 20:29:01 +00001384void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1385 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001386 bool ForVirtualBase,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001387 llvm::Value *This) {
Anders Carlsson4d205ba2010-05-02 23:33:10 +00001388 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1389 ForVirtualBase);
Fariborz Jahanian265c3252011-02-01 23:22:34 +00001390 llvm::Value *Callee = 0;
1391 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian7f6f81b2011-02-03 19:27:17 +00001392 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1393 DD->getParent());
Fariborz Jahanian265c3252011-02-01 23:22:34 +00001394
1395 if (!Callee)
1396 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001397
Anders Carlssone36a6b32010-01-02 01:01:18 +00001398 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001399}
1400
John McCall53cad2e2010-07-21 01:41:18 +00001401namespace {
John McCallcda666c2010-07-21 07:22:38 +00001402 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001403 const CXXDestructorDecl *Dtor;
1404 llvm::Value *Addr;
1405
1406 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1407 : Dtor(D), Addr(Addr) {}
1408
John McCall30317fd2011-07-12 20:27:29 +00001409 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall53cad2e2010-07-21 01:41:18 +00001410 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1411 /*ForVirtualBase=*/false, Addr);
1412 }
1413 };
1414}
1415
John McCall8680f872010-07-21 06:29:51 +00001416void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1417 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001418 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001419}
1420
John McCallbd309292010-07-06 01:34:17 +00001421void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1422 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1423 if (!ClassDecl) return;
1424 if (ClassDecl->hasTrivialDestructor()) return;
1425
1426 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001427 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001428 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001429}
1430
Anders Carlsson27da15b2010-01-01 20:29:01 +00001431llvm::Value *
Anders Carlsson84673e22010-01-31 01:36:53 +00001432CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1433 const CXXRecordDecl *ClassDecl,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001434 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00001435 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyckbb4e9772011-04-07 12:37:09 +00001436 CharUnits VBaseOffsetOffset =
Peter Collingbournea8341662011-09-26 01:56:30 +00001437 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001438
1439 llvm::Value *VBaseOffsetPtr =
Ken Dyckbb4e9772011-04-07 12:37:09 +00001440 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1441 "vbase.offset.ptr");
Chris Lattner2192fe52011-07-18 04:24:23 +00001442 llvm::Type *PtrDiffTy =
Anders Carlsson27da15b2010-01-01 20:29:01 +00001443 ConvertType(getContext().getPointerDiffType());
1444
1445 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1446 PtrDiffTy->getPointerTo());
1447
1448 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1449
1450 return VBaseOffset;
1451}
1452
Anders Carlssone87fae92010-03-28 19:40:00 +00001453void
1454CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001455 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001456 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001457 llvm::Constant *VTable,
1458 const CXXRecordDecl *VTableClass) {
Anders Carlsson58890272010-03-29 01:08:49 +00001459 const CXXRecordDecl *RD = Base.getBase();
1460
Anders Carlssone87fae92010-03-28 19:40:00 +00001461 // Compute the address point.
Anders Carlsson58890272010-03-29 01:08:49 +00001462 llvm::Value *VTableAddressPoint;
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001463
Anders Carlsson58890272010-03-29 01:08:49 +00001464 // Check if we need to use a vtable from the VTT.
Anders Carlsson383f4cc2010-03-29 02:38:51 +00001465 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlsson652758c2010-04-20 05:22:15 +00001466 (RD->getNumVBases() || NearestVBase)) {
Anders Carlsson58890272010-03-29 01:08:49 +00001467 // Get the secondary vpointer index.
1468 uint64_t VirtualPointerIndex =
1469 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1470
1471 /// Load the VTT.
1472 llvm::Value *VTT = LoadCXXVTT();
1473 if (VirtualPointerIndex)
1474 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1475
1476 // And load the address point from the VTT.
1477 VTableAddressPoint = Builder.CreateLoad(VTT);
1478 } else {
Peter Collingbourne5ee9ee42011-09-26 01:56:41 +00001479 uint64_t AddressPoint =
Peter Collingbourneaffe1112011-09-26 01:56:50 +00001480 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlsson58890272010-03-29 01:08:49 +00001481 VTableAddressPoint =
Anders Carlssone87fae92010-03-28 19:40:00 +00001482 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlsson58890272010-03-29 01:08:49 +00001483 }
Anders Carlssone87fae92010-03-28 19:40:00 +00001484
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001485 // Compute where to store the address point.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001486 llvm::Value *VirtualOffset = 0;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001487 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001488
1489 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1490 // We need to use the virtual base offset offset because the virtual base
1491 // might have a different offset in the most derived class.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001492 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1493 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001494 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001495 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001496 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001497 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001498 }
Anders Carlssonc58fb552010-05-03 00:29:58 +00001499
1500 // Apply the offsets.
1501 llvm::Value *VTableField = LoadCXXThis();
1502
Ken Dyckcfc332c2011-03-23 00:45:26 +00001503 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlssonc58fb552010-05-03 00:29:58 +00001504 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1505 NonVirtualOffset,
1506 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001507
Anders Carlssone87fae92010-03-28 19:40:00 +00001508 // Finally, store the address point.
Chris Lattner2192fe52011-07-18 04:24:23 +00001509 llvm::Type *AddressPointPtrTy =
Anders Carlssone87fae92010-03-28 19:40:00 +00001510 VTableAddressPoint->getType()->getPointerTo();
1511 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1512 Builder.CreateStore(VTableAddressPoint, VTableField);
1513}
1514
Anders Carlssond5895932010-03-28 21:07:49 +00001515void
1516CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001517 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001518 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001519 bool BaseIsNonVirtualPrimaryBase,
1520 llvm::Constant *VTable,
1521 const CXXRecordDecl *VTableClass,
1522 VisitedVirtualBasesSetTy& VBases) {
1523 // If this base is a non-virtual primary base the address point has already
1524 // been set.
1525 if (!BaseIsNonVirtualPrimaryBase) {
1526 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001527 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1528 VTable, VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00001529 }
1530
1531 const CXXRecordDecl *RD = Base.getBase();
1532
1533 // Traverse bases.
1534 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1535 E = RD->bases_end(); I != E; ++I) {
1536 CXXRecordDecl *BaseDecl
1537 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1538
1539 // Ignore classes without a vtable.
1540 if (!BaseDecl->isDynamicClass())
1541 continue;
1542
Ken Dyck3fb4c892011-03-23 01:04:18 +00001543 CharUnits BaseOffset;
1544 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00001545 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00001546
1547 if (I->isVirtual()) {
1548 // Check if we've visited this virtual base before.
1549 if (!VBases.insert(BaseDecl))
1550 continue;
1551
1552 const ASTRecordLayout &Layout =
1553 getContext().getASTRecordLayout(VTableClass);
1554
Ken Dyck3fb4c892011-03-23 01:04:18 +00001555 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1556 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00001557 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00001558 } else {
1559 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1560
Ken Dyck16ffcac2011-03-24 01:21:01 +00001561 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001562 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00001563 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00001564 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00001565 }
1566
Ken Dyck16ffcac2011-03-24 01:21:01 +00001567 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlsson652758c2010-04-20 05:22:15 +00001568 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001569 BaseOffsetFromNearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00001570 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001571 VTable, VTableClass, VBases);
1572 }
1573}
1574
1575void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1576 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001577 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00001578 return;
1579
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001580 // Get the VTable.
1581 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlssonb35ea552010-03-24 03:57:14 +00001582
Anders Carlssond5895932010-03-28 21:07:49 +00001583 // Initialize the vtable pointers for this class and all of its bases.
1584 VisitedVirtualBasesSetTy VBases;
Ken Dyck16ffcac2011-03-24 01:21:01 +00001585 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1586 /*NearestVBase=*/0,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001587 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlssond5895932010-03-28 21:07:49 +00001588 /*BaseIsNonVirtualPrimaryBase=*/false,
1589 VTable, RD, VBases);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001590}
Dan Gohman8fc50c22010-10-26 18:44:08 +00001591
1592llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00001593 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00001594 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1595 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1596}
Anders Carlssonc36783e2011-05-08 20:32:23 +00001597
1598static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1599 const Expr *E = Base;
1600
1601 while (true) {
1602 E = E->IgnoreParens();
1603 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1604 if (CE->getCastKind() == CK_DerivedToBase ||
1605 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1606 CE->getCastKind() == CK_NoOp) {
1607 E = CE->getSubExpr();
1608 continue;
1609 }
1610 }
1611
1612 break;
1613 }
1614
1615 QualType DerivedType = E->getType();
1616 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1617 DerivedType = PTy->getPointeeType();
1618
1619 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1620}
1621
1622// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1623// quite what we want.
1624static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1625 while (true) {
1626 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1627 E = PE->getSubExpr();
1628 continue;
1629 }
1630
1631 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1632 if (CE->getCastKind() == CK_NoOp) {
1633 E = CE->getSubExpr();
1634 continue;
1635 }
1636 }
1637 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1638 if (UO->getOpcode() == UO_Extension) {
1639 E = UO->getSubExpr();
1640 continue;
1641 }
1642 }
1643 return E;
1644 }
1645}
1646
1647/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1648/// function call on the given expr can be devirtualized.
Anders Carlssonc36783e2011-05-08 20:32:23 +00001649static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1650 const CXXMethodDecl *MD) {
1651 // If the most derived class is marked final, we know that no subclass can
1652 // override this member function and so we can devirtualize it. For example:
1653 //
1654 // struct A { virtual void f(); }
1655 // struct B final : A { };
1656 //
1657 // void f(B *b) {
1658 // b->f();
1659 // }
1660 //
1661 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1662 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1663 return true;
1664
1665 // If the member function is marked 'final', we know that it can't be
1666 // overridden and can therefore devirtualize it.
1667 if (MD->hasAttr<FinalAttr>())
1668 return true;
1669
1670 // Similarly, if the class itself is marked 'final' it can't be overridden
1671 // and we can therefore devirtualize the member function call.
1672 if (MD->getParent()->hasAttr<FinalAttr>())
1673 return true;
1674
1675 Base = skipNoOpCastsAndParens(Base);
1676 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1677 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1678 // This is a record decl. We know the type and can devirtualize it.
1679 return VD->getType()->isRecordType();
1680 }
1681
1682 return false;
1683 }
1684
1685 // We can always devirtualize calls on temporary object expressions.
1686 if (isa<CXXConstructExpr>(Base))
1687 return true;
1688
1689 // And calls on bound temporaries.
1690 if (isa<CXXBindTemporaryExpr>(Base))
1691 return true;
1692
1693 // Check if this is a call expr that returns a record type.
1694 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1695 return CE->getCallReturnType()->isRecordType();
1696
1697 // We can't devirtualize the call.
1698 return false;
1699}
1700
1701static bool UseVirtualCall(ASTContext &Context,
1702 const CXXOperatorCallExpr *CE,
1703 const CXXMethodDecl *MD) {
1704 if (!MD->isVirtual())
1705 return false;
1706
1707 // When building with -fapple-kext, all calls must go through the vtable since
1708 // the kernel linker can do runtime patching of vtables.
1709 if (Context.getLangOptions().AppleKext)
1710 return true;
1711
1712 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1713}
1714
1715llvm::Value *
1716CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1717 const CXXMethodDecl *MD,
1718 llvm::Value *This) {
1719 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
Chris Lattner2192fe52011-07-18 04:24:23 +00001720 llvm::Type *Ty =
Anders Carlssonc36783e2011-05-08 20:32:23 +00001721 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD),
1722 FPT->isVariadic());
1723
1724 if (UseVirtualCall(getContext(), E, MD))
1725 return BuildVirtualCall(MD, This, Ty);
1726
1727 return CGM.GetAddrOfFunction(MD, Ty);
1728}