blob: ca8b6576c7ad41d2260502e050079ab1f8201528 [file] [log] [blame]
Anders Carlsson5b955922009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson5d58a1d2009-09-12 04:27:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code dealing with C++ code generation of classes
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld67ef0e2010-08-11 21:04:37 +000014#include "CGDebugInfo.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000015#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000016#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000017#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000018#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000019#include "clang/AST/StmtCXX.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000020#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000021
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000022using namespace clang;
23using namespace CodeGen;
24
Ken Dyck55c02582011-03-22 00:53:26 +000025static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000026ComputeNonVirtualBaseClassOffset(ASTContext &Context,
27 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000028 CastExpr::path_const_iterator Start,
29 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000030 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000031
32 const CXXRecordDecl *RD = DerivedClass;
33
John McCallf871d0c2010-08-07 06:22:56 +000034 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000035 const CXXBaseSpecifier *Base = *I;
36 assert(!Base->isVirtual() && "Should not see virtual bases here!");
37
38 // Get the layout.
39 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
40
41 const CXXRecordDecl *BaseDecl =
42 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
43
44 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000045 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000046
47 RD = BaseDecl;
48 }
49
Ken Dyck55c02582011-03-22 00:53:26 +000050 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000051}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000052
Anders Carlsson84080ec2009-09-29 03:13:20 +000053llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000054CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000055 CastExpr::path_const_iterator PathBegin,
56 CastExpr::path_const_iterator PathEnd) {
57 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000058
Ken Dyck55c02582011-03-22 00:53:26 +000059 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000060 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000062 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000063 return 0;
64
65 const llvm::Type *PtrDiffTy =
66 Types.ConvertType(getContext().getPointerDiffType());
67
Ken Dyck55c02582011-03-22 00:53:26 +000068 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000069}
70
Anders Carlsson8561a862010-04-24 23:01:49 +000071/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000072/// This should only be used for (1) non-virtual bases or (2) virtual bases
73/// when the type is known to be complete (e.g. in complete destructors).
74///
75/// The object pointed to by 'This' is assumed to be non-null.
76llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000077CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
78 const CXXRecordDecl *Derived,
79 const CXXRecordDecl *Base,
80 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000081 // 'this' must be a pointer (in some address space) to Derived.
82 assert(This->getType()->isPointerTy() &&
83 cast<llvm::PointerType>(This->getType())->getElementType()
84 == ConvertType(Derived));
85
86 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000087 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000088 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000089 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000090 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000091 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000092 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000093
94 // Shift and cast down to the base type.
95 // TODO: for complete types, this should be possible with a GEP.
96 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +000097 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +000098 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
99 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000105}
John McCallbff225e2010-02-16 04:15:37 +0000106
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000107static llvm::Value *
108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000109 CharUnits NonVirtual, llvm::Value *Virtual) {
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000110 const llvm::Type *PtrDiffTy =
111 CGF.ConvertType(CGF.getContext().getPointerDiffType());
112
113 llvm::Value *NonVirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000114 if (!NonVirtual.isZero())
115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
116 NonVirtual.getQuantity());
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000117
118 llvm::Value *BaseOffset;
119 if (Virtual) {
120 if (NonVirtualOffset)
121 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
122 else
123 BaseOffset = Virtual;
124 } else
125 BaseOffset = NonVirtualOffset;
126
127 // Apply the base offset.
128 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
129 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
130 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
131
132 return ThisPtr;
133}
134
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000135llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000136CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000137 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000138 CastExpr::path_const_iterator PathBegin,
139 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000140 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000141 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000142
John McCallf871d0c2010-08-07 06:22:56 +0000143 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000144 const CXXRecordDecl *VBase = 0;
145
146 // Get the virtual base.
147 if ((*Start)->isVirtual()) {
148 VBase =
149 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
150 ++Start;
151 }
152
Ken Dyck55c02582011-03-22 00:53:26 +0000153 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000154 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000155 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000156
157 // Get the base pointer type.
158 const llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000159 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000160
Ken Dyck55c02582011-03-22 00:53:26 +0000161 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000162 // Just cast back.
163 return Builder.CreateBitCast(Value, BasePtrTy);
164 }
165
166 llvm::BasicBlock *CastNull = 0;
167 llvm::BasicBlock *CastNotNull = 0;
168 llvm::BasicBlock *CastEnd = 0;
169
170 if (NullCheckValue) {
171 CastNull = createBasicBlock("cast.null");
172 CastNotNull = createBasicBlock("cast.notnull");
173 CastEnd = createBasicBlock("cast.end");
174
Anders Carlssonb9241242011-04-11 00:30:07 +0000175 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000176 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
177 EmitBlock(CastNotNull);
178 }
179
180 llvm::Value *VirtualOffset = 0;
181
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000182 if (VBase) {
183 if (Derived->hasAttr<FinalAttr>()) {
184 VirtualOffset = 0;
185
186 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
187
Ken Dyck55c02582011-03-22 00:53:26 +0000188 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
189 NonVirtualOffset += VBaseOffset;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000190 } else
191 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
192 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000193
194 // Apply the offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000195 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000196 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000197 VirtualOffset);
198
199 // Cast back.
200 Value = Builder.CreateBitCast(Value, BasePtrTy);
201
202 if (NullCheckValue) {
203 Builder.CreateBr(CastEnd);
204 EmitBlock(CastNull);
205 Builder.CreateBr(CastEnd);
206 EmitBlock(CastEnd);
207
Jay Foadbbf3bac2011-03-30 11:28:58 +0000208 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000209 PHI->addIncoming(Value, CastNotNull);
210 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
211 CastNull);
212 Value = PHI;
213 }
214
215 return Value;
216}
217
218llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000219CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000220 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000221 CastExpr::path_const_iterator PathBegin,
222 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000223 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000224 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000225
Anders Carlssona3697c92009-11-23 17:57:54 +0000226 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000227 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000228 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
229
Anders Carlssona552ea72010-01-31 01:43:37 +0000230 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000231 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000232
233 if (!NonVirtualOffset) {
234 // No offset, we can just cast back.
235 return Builder.CreateBitCast(Value, DerivedPtrTy);
236 }
237
Anders Carlssona3697c92009-11-23 17:57:54 +0000238 llvm::BasicBlock *CastNull = 0;
239 llvm::BasicBlock *CastNotNull = 0;
240 llvm::BasicBlock *CastEnd = 0;
241
242 if (NullCheckValue) {
243 CastNull = createBasicBlock("cast.null");
244 CastNotNull = createBasicBlock("cast.notnull");
245 CastEnd = createBasicBlock("cast.end");
246
Anders Carlssonb9241242011-04-11 00:30:07 +0000247 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000248 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
249 EmitBlock(CastNotNull);
250 }
251
Anders Carlssona552ea72010-01-31 01:43:37 +0000252 // Apply the offset.
253 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
254 Value = Builder.CreateSub(Value, NonVirtualOffset);
255 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
256
257 // Just cast.
258 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000259
260 if (NullCheckValue) {
261 Builder.CreateBr(CastEnd);
262 EmitBlock(CastNull);
263 Builder.CreateBr(CastEnd);
264 EmitBlock(CastEnd);
265
Jay Foadbbf3bac2011-03-30 11:28:58 +0000266 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000267 PHI->addIncoming(Value, CastNotNull);
268 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
269 CastNull);
270 Value = PHI;
271 }
272
273 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000274}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000275
Anders Carlssonc997d422010-01-02 01:01:18 +0000276/// GetVTTParameter - Return the VTT parameter that should be passed to a
277/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000278static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
279 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000280 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000281 // This constructor/destructor does not need a VTT parameter.
282 return 0;
283 }
284
285 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
286 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000287
Anders Carlssonc997d422010-01-02 01:01:18 +0000288 llvm::Value *VTT;
289
John McCall3b477332010-02-18 19:59:28 +0000290 uint64_t SubVTTIndex;
291
292 // If the record matches the base, this is the complete ctor/dtor
293 // variant calling the base variant in a class with virtual bases.
294 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000295 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000296 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000297 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000298 SubVTTIndex = 0;
299 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000300 const ASTRecordLayout &Layout =
301 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000302 CharUnits BaseOffset = ForVirtualBase ?
303 Layout.getVBaseClassOffset(Base) :
304 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000305
306 SubVTTIndex =
307 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000308 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
309 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000310
Anders Carlssonaf440352010-03-23 04:11:45 +0000311 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000312 // A VTT parameter was passed to the constructor, use it.
313 VTT = CGF.LoadCXXVTT();
314 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
315 } else {
316 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000317 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000318 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
319 }
320
321 return VTT;
322}
323
John McCall182ab512010-07-21 01:23:41 +0000324namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000325 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000326 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000327 const CXXRecordDecl *BaseClass;
328 bool BaseIsVirtual;
329 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
330 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000331
332 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000333 const CXXRecordDecl *DerivedClass =
334 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
335
336 const CXXDestructorDecl *D = BaseClass->getDestructor();
337 llvm::Value *Addr =
338 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
339 DerivedClass, BaseClass,
340 BaseIsVirtual);
341 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000342 }
343 };
John McCall7e1dff72010-09-17 02:31:44 +0000344
345 /// A visitor which checks whether an initializer uses 'this' in a
346 /// way which requires the vtable to be properly set.
347 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
348 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
349
350 bool UsesThis;
351
352 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
353
354 // Black-list all explicit and implicit references to 'this'.
355 //
356 // Do we need to worry about external references to 'this' derived
357 // from arbitrary code? If so, then anything which runs arbitrary
358 // external code might potentially access the vtable.
359 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
360 };
361}
362
363static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
364 DynamicThisUseChecker Checker(C);
365 Checker.Visit(const_cast<Expr*>(Init));
366 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000367}
368
Anders Carlsson607d0372009-12-24 22:46:43 +0000369static void EmitBaseInitializer(CodeGenFunction &CGF,
370 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000371 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000372 CXXCtorType CtorType) {
373 assert(BaseInit->isBaseInitializer() &&
374 "Must have base initializer!");
375
376 llvm::Value *ThisPtr = CGF.LoadCXXThis();
377
378 const Type *BaseType = BaseInit->getBaseClass();
379 CXXRecordDecl *BaseClassDecl =
380 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
381
Anders Carlsson80638c52010-04-12 00:51:03 +0000382 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000383
384 // The base constructor doesn't construct virtual bases.
385 if (CtorType == Ctor_Base && isBaseVirtual)
386 return;
387
John McCall7e1dff72010-09-17 02:31:44 +0000388 // If the initializer for the base (other than the constructor
389 // itself) accesses 'this' in any way, we need to initialize the
390 // vtables.
391 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
392 CGF.InitializeVTablePointers(ClassDecl);
393
John McCallbff225e2010-02-16 04:15:37 +0000394 // We can pretend to be a complete class because it only matters for
395 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000396 llvm::Value *V =
397 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000398 BaseClassDecl,
399 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000400
John McCall558d2ab2010-09-15 10:14:12 +0000401 AggValueSlot AggSlot = AggValueSlot::forAddr(V, false, /*Lifetime*/ true);
402
403 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000404
Anders Carlsson7a178512011-02-28 00:33:03 +0000405 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000406 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000407 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
408 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000409}
410
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000411static void EmitAggMemberInitializer(CodeGenFunction &CGF,
412 LValue LHS,
413 llvm::Value *ArrayIndexVar,
Sean Huntcbb67482011-01-08 20:30:50 +0000414 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000415 QualType T,
416 unsigned Index) {
417 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000418 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000419
420 llvm::Value *Dest = LHS.getAddress();
421 if (ArrayIndexVar) {
422 // If we have an array index variable, load it and use it as an offset.
423 // Then, increment the value.
424 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
425 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
426 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
427 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
428 CGF.Builder.CreateStore(Next, ArrayIndexVar);
429 }
John McCall558d2ab2010-09-15 10:14:12 +0000430
431 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.isVolatileQualified(),
432 /*Lifetime*/ true);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000433
John McCall558d2ab2010-09-15 10:14:12 +0000434 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000435
436 return;
437 }
438
439 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
440 assert(Array && "Array initialization without the array type?");
441 llvm::Value *IndexVar
442 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
443 assert(IndexVar && "Array index variable not loaded");
444
445 // Initialize this index variable to zero.
446 llvm::Value* Zero
447 = llvm::Constant::getNullValue(
448 CGF.ConvertType(CGF.getContext().getSizeType()));
449 CGF.Builder.CreateStore(Zero, IndexVar);
450
451 // Start the loop with a block that tests the condition.
452 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
453 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
454
455 CGF.EmitBlock(CondBlock);
456
457 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
458 // Generate: if (loop-index < number-of-elements) fall to the loop body,
459 // otherwise, go to the block after the for-loop.
460 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000461 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000462 llvm::Value *NumElementsPtr =
463 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000464 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
465 "isless");
466
467 // If the condition is true, execute the body.
468 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
469
470 CGF.EmitBlock(ForBody);
471 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
472
473 {
John McCallf1549f62010-07-06 01:34:17 +0000474 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000475
476 // Inside the loop body recurse to emit the inner loop or, eventually, the
477 // constructor call.
478 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
479 Array->getElementType(), Index + 1);
480 }
481
482 CGF.EmitBlock(ContinueBlock);
483
484 // Emit the increment of the loop counter.
485 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
486 Counter = CGF.Builder.CreateLoad(IndexVar);
487 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
488 CGF.Builder.CreateStore(NextVal, IndexVar);
489
490 // Finally, branch back up to the condition for the next iteration.
491 CGF.EmitBranch(CondBlock);
492
493 // Emit the fall-through block.
494 CGF.EmitBlock(AfterFor, true);
495}
John McCall182ab512010-07-21 01:23:41 +0000496
497namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000498 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000499 FieldDecl *Field;
500 CXXDestructorDecl *Dtor;
501
502 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
503 : Field(Field), Dtor(Dtor) {}
504
505 void Emit(CodeGenFunction &CGF, bool IsForEH) {
506 // FIXME: Is this OK for C++0x delegating constructors?
507 llvm::Value *ThisPtr = CGF.LoadCXXThis();
508 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
509
510 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
511 LHS.getAddress());
512 }
513 };
514}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000515
Anders Carlsson607d0372009-12-24 22:46:43 +0000516static void EmitMemberInitializer(CodeGenFunction &CGF,
517 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000518 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000519 const CXXConstructorDecl *Constructor,
520 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000521 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000522 "Must have member initializer!");
523
524 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000525 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000526 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
527
528 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000529 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000530
Anders Carlsson607d0372009-12-24 22:46:43 +0000531 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000532 if (MemberInit->isIndirectMemberInitializer()) {
533 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
534 MemberInit->getIndirectMember(), 0);
535 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000536 } else {
537 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000538 }
539
Sean Huntcbb67482011-01-08 20:30:50 +0000540 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000541 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000542 RValue RHS;
543 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000544 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000545 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000546 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000547 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000548 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000549 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000550 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000551 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
552 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000553 LHS.isVolatileQualified());
554 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000555 llvm::Value *ArrayIndexVar = 0;
556 const ConstantArrayType *Array
557 = CGF.getContext().getAsConstantArrayType(FieldType);
558 if (Array && Constructor->isImplicit() &&
559 Constructor->isCopyConstructor()) {
560 const llvm::Type *SizeTy
561 = CGF.ConvertType(CGF.getContext().getSizeType());
562
563 // The LHS is a pointer to the first object we'll be constructing, as
564 // a flat array.
565 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
566 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
567 BasePtr = llvm::PointerType::getUnqual(BasePtr);
568 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
569 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000570 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000571
572 // Create an array index that will be used to walk over all of the
573 // objects we're constructing.
574 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
575 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
576 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
577
578 // If we are copying an array of scalars or classes with trivial copy
579 // constructors, perform a single aggregate copy.
580 const RecordType *Record = BaseElementTy->getAs<RecordType>();
581 if (!Record ||
582 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
583 // Find the source pointer. We knows it's the last argument because
584 // we know we're in a copy constructor.
585 unsigned SrcArgIndex = Args.size() - 1;
586 llvm::Value *SrcPtr
John McCalld26bc762011-03-09 04:27:21 +0000587 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000588 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
589
590 // Copy the aggregate.
591 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
592 LHS.isVolatileQualified());
593 return;
594 }
595
596 // Emit the block variables for the array indices, if any.
597 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000598 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000599 }
600
601 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000602
Anders Carlsson7a178512011-02-28 00:33:03 +0000603 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000604 return;
605
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000606 // FIXME: If we have an array of classes w/ non-trivial destructors,
607 // we need to destroy in reverse order of construction along the exception
608 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000609 const RecordType *RT = FieldType->getAs<RecordType>();
610 if (!RT)
611 return;
612
613 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000614 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000615 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
616 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000617 }
618}
619
John McCallc0bf4622010-02-23 00:48:20 +0000620/// Checks whether the given constructor is a valid subject for the
621/// complete-to-base constructor delegation optimization, i.e.
622/// emitting the complete constructor as a simple call to the base
623/// constructor.
624static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
625
626 // Currently we disable the optimization for classes with virtual
627 // bases because (1) the addresses of parameter variables need to be
628 // consistent across all initializers but (2) the delegate function
629 // call necessarily creates a second copy of the parameter variable.
630 //
631 // The limiting example (purely theoretical AFAIK):
632 // struct A { A(int &c) { c++; } };
633 // struct B : virtual A {
634 // B(int count) : A(count) { printf("%d\n", count); }
635 // };
636 // ...although even this example could in principle be emitted as a
637 // delegation since the address of the parameter doesn't escape.
638 if (Ctor->getParent()->getNumVBases()) {
639 // TODO: white-list trivial vbase initializers. This case wouldn't
640 // be subject to the restrictions below.
641
642 // TODO: white-list cases where:
643 // - there are no non-reference parameters to the constructor
644 // - the initializers don't access any non-reference parameters
645 // - the initializers don't take the address of non-reference
646 // parameters
647 // - etc.
648 // If we ever add any of the above cases, remember that:
649 // - function-try-blocks will always blacklist this optimization
650 // - we need to perform the constructor prologue and cleanup in
651 // EmitConstructorBody.
652
653 return false;
654 }
655
656 // We also disable the optimization for variadic functions because
657 // it's impossible to "re-pass" varargs.
658 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
659 return false;
660
Sean Hunt059ce0d2011-05-01 07:04:31 +0000661 // FIXME: Decide if we can do a delegation of a delegating constructor.
662 if (Ctor->isDelegatingConstructor())
663 return false;
664
John McCallc0bf4622010-02-23 00:48:20 +0000665 return true;
666}
667
John McCall9fc6a772010-02-19 09:25:03 +0000668/// EmitConstructorBody - Emits the body of the current constructor.
669void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
670 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
671 CXXCtorType CtorType = CurGD.getCtorType();
672
John McCallc0bf4622010-02-23 00:48:20 +0000673 // Before we go any further, try the complete->base constructor
674 // delegation optimization.
675 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000676 if (CGDebugInfo *DI = getDebugInfo())
677 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000678 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
679 return;
680 }
681
John McCall9fc6a772010-02-19 09:25:03 +0000682 Stmt *Body = Ctor->getBody();
683
John McCallc0bf4622010-02-23 00:48:20 +0000684 // Enter the function-try-block before the constructor prologue if
685 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000686 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000687 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000688 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000689
John McCallf1549f62010-07-06 01:34:17 +0000690 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000691
John McCallc0bf4622010-02-23 00:48:20 +0000692 // Emit the constructor prologue, i.e. the base and member
693 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000694 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000695
696 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000697 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000698 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
699 else if (Body)
700 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000701
702 // Emit any cleanup blocks associated with the member or base
703 // initializers, which includes (along the exceptional path) the
704 // destructors for those members and bases that were fully
705 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000706 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000707
John McCallc0bf4622010-02-23 00:48:20 +0000708 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000709 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000710}
711
Anders Carlsson607d0372009-12-24 22:46:43 +0000712/// EmitCtorPrologue - This routine generates necessary code to initialize
713/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000714void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000715 CXXCtorType CtorType,
716 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000717 if (CD->isDelegatingConstructor())
718 return EmitDelegatingCXXConstructorCall(CD, Args);
719
Anders Carlsson607d0372009-12-24 22:46:43 +0000720 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000721
Sean Huntcbb67482011-01-08 20:30:50 +0000722 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000723
Anders Carlsson607d0372009-12-24 22:46:43 +0000724 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
725 E = CD->init_end();
726 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000727 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000728
Anders Carlsson607d0372009-12-24 22:46:43 +0000729 if (Member->isBaseInitializer())
730 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Hunt059ce0d2011-05-01 07:04:31 +0000731 else if (Member->isAnyMemberInitializer())
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000732 MemberInitializers.push_back(Member);
Sean Hunt059ce0d2011-05-01 07:04:31 +0000733 else
734 llvm_unreachable("Delegating initializer on non-delegating constructor");
Anders Carlsson607d0372009-12-24 22:46:43 +0000735 }
736
Anders Carlsson603d6d12010-03-28 21:07:49 +0000737 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000738
John McCallf1549f62010-07-06 01:34:17 +0000739 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000740 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000741}
742
John McCall9fc6a772010-02-19 09:25:03 +0000743/// EmitDestructorBody - Emits the body of the current destructor.
744void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
745 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
746 CXXDtorType DtorType = CurGD.getDtorType();
747
John McCall50da2ca2010-07-21 05:30:47 +0000748 // The call to operator delete in a deleting destructor happens
749 // outside of the function-try-block, which means it's always
750 // possible to delegate the destructor body to the complete
751 // destructor. Do so.
752 if (DtorType == Dtor_Deleting) {
753 EnterDtorCleanups(Dtor, Dtor_Deleting);
754 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
755 LoadCXXThis());
756 PopCleanupBlock();
757 return;
758 }
759
John McCall9fc6a772010-02-19 09:25:03 +0000760 Stmt *Body = Dtor->getBody();
761
762 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000763 // anything else.
764 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000765 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000766 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000767
John McCall50da2ca2010-07-21 05:30:47 +0000768 // Enter the epilogue cleanups.
769 RunCleanupsScope DtorEpilogue(*this);
770
John McCall9fc6a772010-02-19 09:25:03 +0000771 // If this is the complete variant, just invoke the base variant;
772 // the epilogue will destruct the virtual bases. But we can't do
773 // this optimization if the body is a function-try-block, because
774 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000775 switch (DtorType) {
776 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
777
778 case Dtor_Complete:
779 // Enter the cleanup scopes for virtual bases.
780 EnterDtorCleanups(Dtor, Dtor_Complete);
781
782 if (!isTryBody) {
783 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
784 LoadCXXThis());
785 break;
786 }
787 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000788
John McCall50da2ca2010-07-21 05:30:47 +0000789 case Dtor_Base:
790 // Enter the cleanup scopes for fields and non-virtual bases.
791 EnterDtorCleanups(Dtor, Dtor_Base);
792
793 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000794 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000795
796 if (isTryBody)
797 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
798 else if (Body)
799 EmitStmt(Body);
800 else {
801 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
802 // nothing to do besides what's in the epilogue
803 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000804 // -fapple-kext must inline any call to this dtor into
805 // the caller's body.
806 if (getContext().getLangOptions().AppleKext)
807 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000808 break;
John McCall9fc6a772010-02-19 09:25:03 +0000809 }
810
John McCall50da2ca2010-07-21 05:30:47 +0000811 // Jump out through the epilogue cleanups.
812 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000813
814 // Exit the try if applicable.
815 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000816 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000817}
818
John McCall50da2ca2010-07-21 05:30:47 +0000819namespace {
820 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000821 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000822 CallDtorDelete() {}
823
824 void Emit(CodeGenFunction &CGF, bool IsForEH) {
825 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
826 const CXXRecordDecl *ClassDecl = Dtor->getParent();
827 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
828 CGF.getContext().getTagDeclType(ClassDecl));
829 }
830 };
831
John McCall1f0fca52010-07-21 07:22:38 +0000832 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000833 const FieldDecl *Field;
834 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
835
836 void Emit(CodeGenFunction &CGF, bool IsForEH) {
837 QualType FieldType = Field->getType();
838 const ConstantArrayType *Array =
839 CGF.getContext().getAsConstantArrayType(FieldType);
840
841 QualType BaseType =
842 CGF.getContext().getBaseElementType(Array->getElementType());
843 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
844
845 llvm::Value *ThisPtr = CGF.LoadCXXThis();
846 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
847 // FIXME: Qualifiers?
848 /*CVRQualifiers=*/0);
849
850 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
851 llvm::Value *BaseAddrPtr =
852 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
853 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
854 Array, BaseAddrPtr);
855 }
856 };
857
John McCall1f0fca52010-07-21 07:22:38 +0000858 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000859 const FieldDecl *Field;
860 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
861
862 void Emit(CodeGenFunction &CGF, bool IsForEH) {
863 const CXXRecordDecl *FieldClassDecl =
864 Field->getType()->getAsCXXRecordDecl();
865
866 llvm::Value *ThisPtr = CGF.LoadCXXThis();
867 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
868 // FIXME: Qualifiers?
869 /*CVRQualifiers=*/0);
870
871 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
872 Dtor_Complete, /*ForVirtualBase=*/false,
873 LHS.getAddress());
874 }
875 };
876}
877
Anders Carlsson607d0372009-12-24 22:46:43 +0000878/// EmitDtorEpilogue - Emit all code that comes at the end of class's
879/// destructor. This is to call destructors on members and base classes
880/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000881void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
882 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000883 assert(!DD->isTrivial() &&
884 "Should not emit dtor epilogue for trivial dtor!");
885
John McCall50da2ca2010-07-21 05:30:47 +0000886 // The deleting-destructor phase just needs to call the appropriate
887 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000888 if (DtorType == Dtor_Deleting) {
889 assert(DD->getOperatorDelete() &&
890 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000891 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000892 return;
893 }
894
John McCall50da2ca2010-07-21 05:30:47 +0000895 const CXXRecordDecl *ClassDecl = DD->getParent();
896
897 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000898 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000899
900 // We push them in the forward order so that they'll be popped in
901 // the reverse order.
902 for (CXXRecordDecl::base_class_const_iterator I =
903 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000904 I != E; ++I) {
905 const CXXBaseSpecifier &Base = *I;
906 CXXRecordDecl *BaseClassDecl
907 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
908
909 // Ignore trivial destructors.
910 if (BaseClassDecl->hasTrivialDestructor())
911 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000912
John McCall1f0fca52010-07-21 07:22:38 +0000913 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
914 BaseClassDecl,
915 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000916 }
John McCall50da2ca2010-07-21 05:30:47 +0000917
John McCall3b477332010-02-18 19:59:28 +0000918 return;
919 }
920
921 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000922
923 // Destroy non-virtual bases.
924 for (CXXRecordDecl::base_class_const_iterator I =
925 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
926 const CXXBaseSpecifier &Base = *I;
927
928 // Ignore virtual bases.
929 if (Base.isVirtual())
930 continue;
931
932 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
933
934 // Ignore trivial destructors.
935 if (BaseClassDecl->hasTrivialDestructor())
936 continue;
John McCall3b477332010-02-18 19:59:28 +0000937
John McCall1f0fca52010-07-21 07:22:38 +0000938 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
939 BaseClassDecl,
940 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000941 }
942
943 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000944 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
945 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
946 E = ClassDecl->field_end(); I != E; ++I) {
947 const FieldDecl *Field = *I;
948
949 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000950 const ConstantArrayType *Array =
951 getContext().getAsConstantArrayType(FieldType);
952 if (Array)
953 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000954
955 const RecordType *RT = FieldType->getAs<RecordType>();
956 if (!RT)
957 continue;
958
959 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
960 if (FieldClassDecl->hasTrivialDestructor())
961 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000962
Anders Carlsson607d0372009-12-24 22:46:43 +0000963 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000964 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000965 else
John McCall1f0fca52010-07-21 07:22:38 +0000966 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000967 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000968}
969
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000970/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
971/// for-loop to call the default constructor on individual members of the
972/// array.
973/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
974/// array type and 'ArrayPtr' points to the beginning fo the array.
975/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000976///
977/// \param ZeroInitialization True if each element should be zero-initialized
978/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000979void
980CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000981 const ConstantArrayType *ArrayTy,
982 llvm::Value *ArrayPtr,
983 CallExpr::const_arg_iterator ArgBeg,
984 CallExpr::const_arg_iterator ArgEnd,
985 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000986
987 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
988 llvm::Value * NumElements =
989 llvm::ConstantInt::get(SizeTy,
990 getContext().getConstantArrayElementCount(ArrayTy));
991
Douglas Gregor59174c02010-07-21 01:10:17 +0000992 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
993 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000994}
995
996void
997CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
998 llvm::Value *NumElements,
999 llvm::Value *ArrayPtr,
1000 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +00001001 CallExpr::const_arg_iterator ArgEnd,
1002 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001003 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1004
1005 // Create a temporary for the loop index and initialize it with 0.
1006 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1007 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1008 Builder.CreateStore(Zero, IndexPtr);
1009
1010 // Start the loop with a block that tests the condition.
1011 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1012 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1013
1014 EmitBlock(CondBlock);
1015
1016 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1017
1018 // Generate: if (loop-index < number-of-elements fall to the loop body,
1019 // otherwise, go to the block after the for-loop.
1020 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1021 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1022 // If the condition is true, execute the body.
1023 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1024
1025 EmitBlock(ForBody);
1026
1027 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1028 // Inside the loop body, emit the constructor call on the array element.
1029 Counter = Builder.CreateLoad(IndexPtr);
1030 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1031 "arrayidx");
1032
Douglas Gregor59174c02010-07-21 01:10:17 +00001033 // Zero initialize the storage, if requested.
1034 if (ZeroInitialization)
1035 EmitNullInitialization(Address,
1036 getContext().getTypeDeclType(D->getParent()));
1037
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001038 // C++ [class.temporary]p4:
1039 // There are two contexts in which temporaries are destroyed at a different
1040 // point than the end of the full-expression. The first context is when a
1041 // default constructor is called to initialize an element of an array.
1042 // If the constructor has one or more default arguments, the destruction of
1043 // every temporary created in a default argument expression is sequenced
1044 // before the construction of the next array element, if any.
1045
1046 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001047 {
John McCallf1549f62010-07-06 01:34:17 +00001048 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001049
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001050 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001051 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001052 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001053
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001054 EmitBlock(ContinueBlock);
1055
1056 // Emit the increment of the loop counter.
1057 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1058 Counter = Builder.CreateLoad(IndexPtr);
1059 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1060 Builder.CreateStore(NextVal, IndexPtr);
1061
1062 // Finally, branch back up to the condition for the next iteration.
1063 EmitBranch(CondBlock);
1064
1065 // Emit the fall-through block.
1066 EmitBlock(AfterFor, true);
1067}
1068
1069/// EmitCXXAggrDestructorCall - calls the default destructor on array
1070/// elements in reverse order of construction.
1071void
1072CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1073 const ArrayType *Array,
1074 llvm::Value *This) {
1075 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1076 assert(CA && "Do we support VLA for destruction ?");
1077 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1078
1079 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1080 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1081 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1082}
1083
1084/// EmitCXXAggrDestructorCall - calls the default destructor on array
1085/// elements in reverse order of construction.
1086void
1087CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1088 llvm::Value *UpperCount,
1089 llvm::Value *This) {
1090 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1091 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1092
1093 // Create a temporary for the loop index and initialize it with count of
1094 // array elements.
1095 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1096
1097 // Store the number of elements in the index pointer.
1098 Builder.CreateStore(UpperCount, IndexPtr);
1099
1100 // Start the loop with a block that tests the condition.
1101 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1102 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1103
1104 EmitBlock(CondBlock);
1105
1106 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1107
1108 // Generate: if (loop-index != 0 fall to the loop body,
1109 // otherwise, go to the block after the for-loop.
1110 llvm::Value* zeroConstant =
1111 llvm::Constant::getNullValue(SizeLTy);
1112 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1113 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1114 "isne");
1115 // If the condition is true, execute the body.
1116 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1117
1118 EmitBlock(ForBody);
1119
1120 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1121 // Inside the loop body, emit the constructor call on the array element.
1122 Counter = Builder.CreateLoad(IndexPtr);
1123 Counter = Builder.CreateSub(Counter, One);
1124 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001125 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001126
1127 EmitBlock(ContinueBlock);
1128
1129 // Emit the decrement of the loop counter.
1130 Counter = Builder.CreateLoad(IndexPtr);
1131 Counter = Builder.CreateSub(Counter, One, "dec");
1132 Builder.CreateStore(Counter, IndexPtr);
1133
1134 // Finally, branch back up to the condition for the next iteration.
1135 EmitBranch(CondBlock);
1136
1137 // Emit the fall-through block.
1138 EmitBlock(AfterFor, true);
1139}
1140
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001141void
1142CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001143 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001144 llvm::Value *This,
1145 CallExpr::const_arg_iterator ArgBeg,
1146 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001147
1148 CGDebugInfo *DI = getDebugInfo();
1149 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1150 // If debug info for this class has been emitted then this is the right time
1151 // to do so.
1152 const CXXRecordDecl *Parent = D->getParent();
1153 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1154 Parent->getLocation());
1155 }
1156
John McCall8b6bbeb2010-02-06 00:25:16 +00001157 if (D->isTrivial()) {
1158 if (ArgBeg == ArgEnd) {
1159 // Trivial default constructor, no codegen required.
1160 assert(D->isDefaultConstructor() &&
1161 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001162 return;
1163 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001164
1165 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1166 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1167
John McCall8b6bbeb2010-02-06 00:25:16 +00001168 const Expr *E = (*ArgBeg);
1169 QualType Ty = E->getType();
1170 llvm::Value *Src = EmitLValue(E).getAddress();
1171 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001172 return;
1173 }
1174
Anders Carlsson314e6222010-05-02 23:33:10 +00001175 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001176 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1177
Anders Carlssonc997d422010-01-02 01:01:18 +00001178 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001179}
1180
John McCallc0bf4622010-02-23 00:48:20 +00001181void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001182CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1183 llvm::Value *This, llvm::Value *Src,
1184 CallExpr::const_arg_iterator ArgBeg,
1185 CallExpr::const_arg_iterator ArgEnd) {
1186 if (D->isTrivial()) {
1187 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1188 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1189 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1190 return;
1191 }
1192 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1193 clang::Ctor_Complete);
1194 assert(D->isInstance() &&
1195 "Trying to emit a member call expr on a static method!");
1196
1197 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1198
1199 CallArgList Args;
1200
1201 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001202 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001203
1204
1205 // Push the src ptr.
1206 QualType QT = *(FPT->arg_type_begin());
1207 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1208 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001209 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001210
1211 // Skip over first argument (Src).
1212 ++ArgBeg;
1213 CallExpr::const_arg_iterator Arg = ArgBeg;
1214 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1215 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1216 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001217 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001218 }
1219 // Either we've emitted all the call args, or we have a call to a
1220 // variadic function.
1221 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1222 "Extra arguments in non-variadic function!");
1223 // If we still have any arguments, emit them using the type of the argument.
1224 for (; Arg != ArgEnd; ++Arg) {
1225 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001226 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001227 }
1228
1229 QualType ResultType = FPT->getResultType();
1230 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1231 FPT->getExtInfo()),
1232 Callee, ReturnValueSlot(), Args, D);
1233}
1234
1235void
John McCallc0bf4622010-02-23 00:48:20 +00001236CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1237 CXXCtorType CtorType,
1238 const FunctionArgList &Args) {
1239 CallArgList DelegateArgs;
1240
1241 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1242 assert(I != E && "no parameters to constructor");
1243
1244 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001245 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001246 ++I;
1247
1248 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001249 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1250 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001251 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001252 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001253
Anders Carlssonaf440352010-03-23 04:11:45 +00001254 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001255 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001256 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001257 ++I;
1258 }
1259 }
1260
1261 // Explicit arguments.
1262 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001263 const VarDecl *param = *I;
1264 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001265 }
1266
1267 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1268 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1269 ReturnValueSlot(), DelegateArgs, Ctor);
1270}
1271
Sean Hunt059ce0d2011-05-01 07:04:31 +00001272void
1273CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1274 const FunctionArgList &Args) {
1275 assert(Ctor->isDelegatingConstructor());
1276
1277 llvm::Value *ThisPtr = LoadCXXThis();
1278
1279 AggValueSlot AggSlot = AggValueSlot::forAddr(ThisPtr, false, /*Lifetime*/ true);
1280
1281 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
1282}
1283
1284
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001285void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1286 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001287 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001288 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001289 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1290 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001291 llvm::Value *Callee = 0;
1292 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001293 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1294 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001295
1296 if (!Callee)
1297 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001298
Anders Carlssonc997d422010-01-02 01:01:18 +00001299 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001300}
1301
John McCall291ae942010-07-21 01:41:18 +00001302namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001303 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001304 const CXXDestructorDecl *Dtor;
1305 llvm::Value *Addr;
1306
1307 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1308 : Dtor(D), Addr(Addr) {}
1309
1310 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1311 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1312 /*ForVirtualBase=*/false, Addr);
1313 }
1314 };
1315}
1316
John McCall81407d42010-07-21 06:29:51 +00001317void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1318 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001319 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001320}
1321
John McCallf1549f62010-07-06 01:34:17 +00001322void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1323 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1324 if (!ClassDecl) return;
1325 if (ClassDecl->hasTrivialDestructor()) return;
1326
1327 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001328 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001329 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001330}
1331
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001332llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001333CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1334 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001335 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001336 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001337 CharUnits VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001338 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001339
1340 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001341 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1342 "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001343 const llvm::Type *PtrDiffTy =
1344 ConvertType(getContext().getPointerDiffType());
1345
1346 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1347 PtrDiffTy->getPointerTo());
1348
1349 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1350
1351 return VBaseOffset;
1352}
1353
Anders Carlssond103f9f2010-03-28 19:40:00 +00001354void
1355CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001356 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001357 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001358 llvm::Constant *VTable,
1359 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001360 const CXXRecordDecl *RD = Base.getBase();
1361
Anders Carlssond103f9f2010-03-28 19:40:00 +00001362 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001363 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001364
Anders Carlssonc83f1062010-03-29 01:08:49 +00001365 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001366 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001367 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001368 // Get the secondary vpointer index.
1369 uint64_t VirtualPointerIndex =
1370 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1371
1372 /// Load the VTT.
1373 llvm::Value *VTT = LoadCXXVTT();
1374 if (VirtualPointerIndex)
1375 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1376
1377 // And load the address point from the VTT.
1378 VTableAddressPoint = Builder.CreateLoad(VTT);
1379 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001380 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001381 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001382 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001383 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001384
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001385 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001386 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001387 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001388
1389 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1390 // We need to use the virtual base offset offset because the virtual base
1391 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001392 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1393 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001394 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001395 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001396 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001397 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001398 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001399
1400 // Apply the offsets.
1401 llvm::Value *VTableField = LoadCXXThis();
1402
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001403 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001404 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1405 NonVirtualOffset,
1406 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001407
Anders Carlssond103f9f2010-03-28 19:40:00 +00001408 // Finally, store the address point.
1409 const llvm::Type *AddressPointPtrTy =
1410 VTableAddressPoint->getType()->getPointerTo();
1411 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1412 Builder.CreateStore(VTableAddressPoint, VTableField);
1413}
1414
Anders Carlsson603d6d12010-03-28 21:07:49 +00001415void
1416CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001417 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001418 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001419 bool BaseIsNonVirtualPrimaryBase,
1420 llvm::Constant *VTable,
1421 const CXXRecordDecl *VTableClass,
1422 VisitedVirtualBasesSetTy& VBases) {
1423 // If this base is a non-virtual primary base the address point has already
1424 // been set.
1425 if (!BaseIsNonVirtualPrimaryBase) {
1426 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001427 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1428 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001429 }
1430
1431 const CXXRecordDecl *RD = Base.getBase();
1432
1433 // Traverse bases.
1434 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1435 E = RD->bases_end(); I != E; ++I) {
1436 CXXRecordDecl *BaseDecl
1437 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1438
1439 // Ignore classes without a vtable.
1440 if (!BaseDecl->isDynamicClass())
1441 continue;
1442
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001443 CharUnits BaseOffset;
1444 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001445 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001446
1447 if (I->isVirtual()) {
1448 // Check if we've visited this virtual base before.
1449 if (!VBases.insert(BaseDecl))
1450 continue;
1451
1452 const ASTRecordLayout &Layout =
1453 getContext().getASTRecordLayout(VTableClass);
1454
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001455 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1456 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001457 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001458 } else {
1459 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1460
Ken Dyck4230d522011-03-24 01:21:01 +00001461 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001462 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001463 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001464 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001465 }
1466
Ken Dyck4230d522011-03-24 01:21:01 +00001467 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001468 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001469 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001470 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001471 VTable, VTableClass, VBases);
1472 }
1473}
1474
1475void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1476 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001477 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001478 return;
1479
Anders Carlsson07036902010-03-26 04:39:42 +00001480 // Get the VTable.
1481 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001482
Anders Carlsson603d6d12010-03-28 21:07:49 +00001483 // Initialize the vtable pointers for this class and all of its bases.
1484 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001485 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1486 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001487 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001488 /*BaseIsNonVirtualPrimaryBase=*/false,
1489 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001490}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001491
1492llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1493 const llvm::Type *Ty) {
1494 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1495 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1496}