blob: 8e88beb3cf0dc39b7a55fdf37448d0c9b2814a8a [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"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000020
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000021using namespace clang;
22using namespace CodeGen;
23
Anders Carlsson2f1986b2009-10-06 22:43:30 +000024static uint64_t
Anders Carlsson34a2d382010-04-24 21:06:20 +000025ComputeNonVirtualBaseClassOffset(ASTContext &Context,
26 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000027 CastExpr::path_const_iterator Start,
28 CastExpr::path_const_iterator End) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000029 uint64_t Offset = 0;
30
31 const CXXRecordDecl *RD = DerivedClass;
32
John McCallf871d0c2010-08-07 06:22:56 +000033 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000034 const CXXBaseSpecifier *Base = *I;
35 assert(!Base->isVirtual() && "Should not see virtual bases here!");
36
37 // Get the layout.
38 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
39
40 const CXXRecordDecl *BaseDecl =
41 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
42
43 // Add the offset.
Anders Carlssona14f5972010-10-31 23:22:37 +000044 Offset += Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000045
46 RD = BaseDecl;
47 }
48
49 // FIXME: We should not use / 8 here.
50 return Offset / 8;
51}
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
59 uint64_t Offset =
John McCallf871d0c2010-08-07 06:22:56 +000060 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
61 PathBegin, PathEnd);
Anders Carlssona04efdf2010-04-24 21:23:59 +000062 if (!Offset)
63 return 0;
64
65 const llvm::Type *PtrDiffTy =
66 Types.ConvertType(getContext().getPointerDiffType());
67
68 return llvm::ConstantInt::get(PtrDiffTy, Offset);
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.
87 uint64_t Offset;
88 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000089 if (BaseIsVirtual)
Anders Carlssona14f5972010-10-31 23:22:37 +000090 Offset = Layout.getVBaseClassOffsetInBits(Base);
John McCallbff225e2010-02-16 04:15:37 +000091 else
Anders Carlssona14f5972010-10-31 23:22:37 +000092 Offset = Layout.getBaseClassOffsetInBits(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;
97 if (Offset) {
98 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
99 V = Builder.CreateBitCast(V, Int8PtrTy);
100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
101 }
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,
109 uint64_t NonVirtual, llvm::Value *Virtual) {
110 const llvm::Type *PtrDiffTy =
111 CGF.ConvertType(CGF.getContext().getPointerDiffType());
112
113 llvm::Value *NonVirtualOffset = 0;
114 if (NonVirtual)
115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
116
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.
127 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
128 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
129 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
130
131 return ThisPtr;
132}
133
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000134llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000135CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000136 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000137 CastExpr::path_const_iterator PathBegin,
138 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000139 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000140 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000141
John McCallf871d0c2010-08-07 06:22:56 +0000142 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000143 const CXXRecordDecl *VBase = 0;
144
145 // Get the virtual base.
146 if ((*Start)->isVirtual()) {
147 VBase =
148 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
149 ++Start;
150 }
151
152 uint64_t NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000153 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000154 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000155
156 // Get the base pointer type.
157 const llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000158 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000159
160 if (!NonVirtualOffset && !VBase) {
161 // Just cast back.
162 return Builder.CreateBitCast(Value, BasePtrTy);
163 }
164
165 llvm::BasicBlock *CastNull = 0;
166 llvm::BasicBlock *CastNotNull = 0;
167 llvm::BasicBlock *CastEnd = 0;
168
169 if (NullCheckValue) {
170 CastNull = createBasicBlock("cast.null");
171 CastNotNull = createBasicBlock("cast.notnull");
172 CastEnd = createBasicBlock("cast.end");
173
174 llvm::Value *IsNull =
175 Builder.CreateICmpEQ(Value,
176 llvm::Constant::getNullValue(Value->getType()));
177 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
178 EmitBlock(CastNotNull);
179 }
180
181 llvm::Value *VirtualOffset = 0;
182
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000183 if (VBase) {
184 if (Derived->hasAttr<FinalAttr>()) {
185 VirtualOffset = 0;
186
187 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
188
189 uint64_t VBaseOffset = Layout.getVBaseClassOffsetInBits(VBase);
190 NonVirtualOffset += VBaseOffset / 8;
191 } else
192 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
193 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000194
195 // Apply the offsets.
196 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
197 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
208 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
209 PHI->reserveOperandSpace(2);
210 PHI->addIncoming(Value, CastNotNull);
211 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
212 CastNull);
213 Value = PHI;
214 }
215
216 return Value;
217}
218
219llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000220CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000221 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000222 CastExpr::path_const_iterator PathBegin,
223 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000224 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000225 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000226
Anders Carlssona3697c92009-11-23 17:57:54 +0000227 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000228 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000229 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
230
Anders Carlssona552ea72010-01-31 01:43:37 +0000231 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000232 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000233
234 if (!NonVirtualOffset) {
235 // No offset, we can just cast back.
236 return Builder.CreateBitCast(Value, DerivedPtrTy);
237 }
238
Anders Carlssona3697c92009-11-23 17:57:54 +0000239 llvm::BasicBlock *CastNull = 0;
240 llvm::BasicBlock *CastNotNull = 0;
241 llvm::BasicBlock *CastEnd = 0;
242
243 if (NullCheckValue) {
244 CastNull = createBasicBlock("cast.null");
245 CastNotNull = createBasicBlock("cast.notnull");
246 CastEnd = createBasicBlock("cast.end");
247
248 llvm::Value *IsNull =
249 Builder.CreateICmpEQ(Value,
250 llvm::Constant::getNullValue(Value->getType()));
251 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
252 EmitBlock(CastNotNull);
253 }
254
Anders Carlssona552ea72010-01-31 01:43:37 +0000255 // Apply the offset.
256 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
257 Value = Builder.CreateSub(Value, NonVirtualOffset);
258 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
259
260 // Just cast.
261 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000262
263 if (NullCheckValue) {
264 Builder.CreateBr(CastEnd);
265 EmitBlock(CastNull);
266 Builder.CreateBr(CastEnd);
267 EmitBlock(CastEnd);
268
269 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
270 PHI->reserveOperandSpace(2);
271 PHI->addIncoming(Value, CastNotNull);
272 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
273 CastNull);
274 Value = PHI;
275 }
276
277 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000278}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000279
Anders Carlssonc997d422010-01-02 01:01:18 +0000280/// GetVTTParameter - Return the VTT parameter that should be passed to a
281/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000282static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
283 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000284 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000285 // This constructor/destructor does not need a VTT parameter.
286 return 0;
287 }
288
289 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
290 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000291
Anders Carlssonc997d422010-01-02 01:01:18 +0000292 llvm::Value *VTT;
293
John McCall3b477332010-02-18 19:59:28 +0000294 uint64_t SubVTTIndex;
295
296 // If the record matches the base, this is the complete ctor/dtor
297 // variant calling the base variant in a class with virtual bases.
298 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000299 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000300 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000301 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000302 SubVTTIndex = 0;
303 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000304 const ASTRecordLayout &Layout =
305 CGF.getContext().getASTRecordLayout(RD);
306 uint64_t BaseOffset = ForVirtualBase ?
Anders Carlssona14f5972010-10-31 23:22:37 +0000307 Layout.getVBaseClassOffsetInBits(Base) :
308 Layout.getBaseClassOffsetInBits(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000309
310 SubVTTIndex =
311 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000312 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
313 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000314
Anders Carlssonaf440352010-03-23 04:11:45 +0000315 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000316 // A VTT parameter was passed to the constructor, use it.
317 VTT = CGF.LoadCXXVTT();
318 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
319 } else {
320 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000321 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000322 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
323 }
324
325 return VTT;
326}
327
John McCall182ab512010-07-21 01:23:41 +0000328namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000329 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000330 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000331 const CXXRecordDecl *BaseClass;
332 bool BaseIsVirtual;
333 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
334 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000335
336 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000337 const CXXRecordDecl *DerivedClass =
338 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
339
340 const CXXDestructorDecl *D = BaseClass->getDestructor();
341 llvm::Value *Addr =
342 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
343 DerivedClass, BaseClass,
344 BaseIsVirtual);
345 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000346 }
347 };
John McCall7e1dff72010-09-17 02:31:44 +0000348
349 /// A visitor which checks whether an initializer uses 'this' in a
350 /// way which requires the vtable to be properly set.
351 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
352 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
353
354 bool UsesThis;
355
356 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
357
358 // Black-list all explicit and implicit references to 'this'.
359 //
360 // Do we need to worry about external references to 'this' derived
361 // from arbitrary code? If so, then anything which runs arbitrary
362 // external code might potentially access the vtable.
363 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
364 };
365}
366
367static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
368 DynamicThisUseChecker Checker(C);
369 Checker.Visit(const_cast<Expr*>(Init));
370 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000371}
372
Anders Carlsson607d0372009-12-24 22:46:43 +0000373static void EmitBaseInitializer(CodeGenFunction &CGF,
374 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000375 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000376 CXXCtorType CtorType) {
377 assert(BaseInit->isBaseInitializer() &&
378 "Must have base initializer!");
379
380 llvm::Value *ThisPtr = CGF.LoadCXXThis();
381
382 const Type *BaseType = BaseInit->getBaseClass();
383 CXXRecordDecl *BaseClassDecl =
384 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
385
Anders Carlsson80638c52010-04-12 00:51:03 +0000386 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000387
388 // The base constructor doesn't construct virtual bases.
389 if (CtorType == Ctor_Base && isBaseVirtual)
390 return;
391
John McCall7e1dff72010-09-17 02:31:44 +0000392 // If the initializer for the base (other than the constructor
393 // itself) accesses 'this' in any way, we need to initialize the
394 // vtables.
395 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
396 CGF.InitializeVTablePointers(ClassDecl);
397
John McCallbff225e2010-02-16 04:15:37 +0000398 // We can pretend to be a complete class because it only matters for
399 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000400 llvm::Value *V =
401 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000402 BaseClassDecl,
403 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000404
John McCall558d2ab2010-09-15 10:14:12 +0000405 AggValueSlot AggSlot = AggValueSlot::forAddr(V, false, /*Lifetime*/ true);
406
407 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000408
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000409 if (CGF.CGM.getLangOptions().areExceptionsEnabled() &&
410 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000411 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
412 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000413}
414
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000415static void EmitAggMemberInitializer(CodeGenFunction &CGF,
416 LValue LHS,
417 llvm::Value *ArrayIndexVar,
Sean Huntcbb67482011-01-08 20:30:50 +0000418 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000419 QualType T,
420 unsigned Index) {
421 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000422 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000423
424 llvm::Value *Dest = LHS.getAddress();
425 if (ArrayIndexVar) {
426 // If we have an array index variable, load it and use it as an offset.
427 // Then, increment the value.
428 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
429 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
430 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
431 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
432 CGF.Builder.CreateStore(Next, ArrayIndexVar);
433 }
John McCall558d2ab2010-09-15 10:14:12 +0000434
435 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.isVolatileQualified(),
436 /*Lifetime*/ true);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000437
John McCall558d2ab2010-09-15 10:14:12 +0000438 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000439
440 return;
441 }
442
443 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
444 assert(Array && "Array initialization without the array type?");
445 llvm::Value *IndexVar
446 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
447 assert(IndexVar && "Array index variable not loaded");
448
449 // Initialize this index variable to zero.
450 llvm::Value* Zero
451 = llvm::Constant::getNullValue(
452 CGF.ConvertType(CGF.getContext().getSizeType()));
453 CGF.Builder.CreateStore(Zero, IndexVar);
454
455 // Start the loop with a block that tests the condition.
456 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
457 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
458
459 CGF.EmitBlock(CondBlock);
460
461 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
462 // Generate: if (loop-index < number-of-elements) fall to the loop body,
463 // otherwise, go to the block after the for-loop.
464 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000465 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000466 llvm::Value *NumElementsPtr =
467 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000468 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
469 "isless");
470
471 // If the condition is true, execute the body.
472 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
473
474 CGF.EmitBlock(ForBody);
475 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
476
477 {
John McCallf1549f62010-07-06 01:34:17 +0000478 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000479
480 // Inside the loop body recurse to emit the inner loop or, eventually, the
481 // constructor call.
482 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
483 Array->getElementType(), Index + 1);
484 }
485
486 CGF.EmitBlock(ContinueBlock);
487
488 // Emit the increment of the loop counter.
489 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
490 Counter = CGF.Builder.CreateLoad(IndexVar);
491 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
492 CGF.Builder.CreateStore(NextVal, IndexVar);
493
494 // Finally, branch back up to the condition for the next iteration.
495 CGF.EmitBranch(CondBlock);
496
497 // Emit the fall-through block.
498 CGF.EmitBlock(AfterFor, true);
499}
John McCall182ab512010-07-21 01:23:41 +0000500
501namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000502 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000503 FieldDecl *Field;
504 CXXDestructorDecl *Dtor;
505
506 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
507 : Field(Field), Dtor(Dtor) {}
508
509 void Emit(CodeGenFunction &CGF, bool IsForEH) {
510 // FIXME: Is this OK for C++0x delegating constructors?
511 llvm::Value *ThisPtr = CGF.LoadCXXThis();
512 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
513
514 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
515 LHS.getAddress());
516 }
517 };
518}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000519
Anders Carlsson607d0372009-12-24 22:46:43 +0000520static void EmitMemberInitializer(CodeGenFunction &CGF,
521 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000522 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000523 const CXXConstructorDecl *Constructor,
524 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000525 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000526 "Must have member initializer!");
527
528 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000529 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000530 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
531
532 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000533 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000534
Anders Carlsson607d0372009-12-24 22:46:43 +0000535 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000536 if (MemberInit->isIndirectMemberInitializer()) {
537 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
538 MemberInit->getIndirectMember(), 0);
539 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000540 } else {
541 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000542 }
543
Sean Huntcbb67482011-01-08 20:30:50 +0000544 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000545 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000546 RValue RHS;
547 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000548 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000549 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000550 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000551 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000552 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000553 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000554 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000555 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
556 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000557 LHS.isVolatileQualified());
558 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000559 llvm::Value *ArrayIndexVar = 0;
560 const ConstantArrayType *Array
561 = CGF.getContext().getAsConstantArrayType(FieldType);
562 if (Array && Constructor->isImplicit() &&
563 Constructor->isCopyConstructor()) {
564 const llvm::Type *SizeTy
565 = CGF.ConvertType(CGF.getContext().getSizeType());
566
567 // The LHS is a pointer to the first object we'll be constructing, as
568 // a flat array.
569 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
570 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
571 BasePtr = llvm::PointerType::getUnqual(BasePtr);
572 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
573 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000574 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000575
576 // Create an array index that will be used to walk over all of the
577 // objects we're constructing.
578 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
579 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
580 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
581
582 // If we are copying an array of scalars or classes with trivial copy
583 // constructors, perform a single aggregate copy.
584 const RecordType *Record = BaseElementTy->getAs<RecordType>();
585 if (!Record ||
586 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
587 // Find the source pointer. We knows it's the last argument because
588 // we know we're in a copy constructor.
589 unsigned SrcArgIndex = Args.size() - 1;
590 llvm::Value *SrcPtr
591 = CGF.Builder.CreateLoad(
592 CGF.GetAddrOfLocalVar(Args[SrcArgIndex].first));
593 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
594
595 // Copy the aggregate.
596 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
597 LHS.isVolatileQualified());
598 return;
599 }
600
601 // Emit the block variables for the array indices, if any.
602 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000603 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000604 }
605
606 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000607
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000608 if (!CGF.CGM.getLangOptions().areExceptionsEnabled())
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000609 return;
610
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000611 // FIXME: If we have an array of classes w/ non-trivial destructors,
612 // we need to destroy in reverse order of construction along the exception
613 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000614 const RecordType *RT = FieldType->getAs<RecordType>();
615 if (!RT)
616 return;
617
618 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000619 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000620 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
621 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000622 }
623}
624
John McCallc0bf4622010-02-23 00:48:20 +0000625/// Checks whether the given constructor is a valid subject for the
626/// complete-to-base constructor delegation optimization, i.e.
627/// emitting the complete constructor as a simple call to the base
628/// constructor.
629static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
630
631 // Currently we disable the optimization for classes with virtual
632 // bases because (1) the addresses of parameter variables need to be
633 // consistent across all initializers but (2) the delegate function
634 // call necessarily creates a second copy of the parameter variable.
635 //
636 // The limiting example (purely theoretical AFAIK):
637 // struct A { A(int &c) { c++; } };
638 // struct B : virtual A {
639 // B(int count) : A(count) { printf("%d\n", count); }
640 // };
641 // ...although even this example could in principle be emitted as a
642 // delegation since the address of the parameter doesn't escape.
643 if (Ctor->getParent()->getNumVBases()) {
644 // TODO: white-list trivial vbase initializers. This case wouldn't
645 // be subject to the restrictions below.
646
647 // TODO: white-list cases where:
648 // - there are no non-reference parameters to the constructor
649 // - the initializers don't access any non-reference parameters
650 // - the initializers don't take the address of non-reference
651 // parameters
652 // - etc.
653 // If we ever add any of the above cases, remember that:
654 // - function-try-blocks will always blacklist this optimization
655 // - we need to perform the constructor prologue and cleanup in
656 // EmitConstructorBody.
657
658 return false;
659 }
660
661 // We also disable the optimization for variadic functions because
662 // it's impossible to "re-pass" varargs.
663 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
664 return false;
665
666 return true;
667}
668
John McCall9fc6a772010-02-19 09:25:03 +0000669/// EmitConstructorBody - Emits the body of the current constructor.
670void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
671 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
672 CXXCtorType CtorType = CurGD.getCtorType();
673
John McCallc0bf4622010-02-23 00:48:20 +0000674 // Before we go any further, try the complete->base constructor
675 // delegation optimization.
676 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000677 if (CGDebugInfo *DI = getDebugInfo())
678 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000679 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
680 return;
681 }
682
John McCall9fc6a772010-02-19 09:25:03 +0000683 Stmt *Body = Ctor->getBody();
684
John McCallc0bf4622010-02-23 00:48:20 +0000685 // Enter the function-try-block before the constructor prologue if
686 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000687 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000688 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000689 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000690
John McCallf1549f62010-07-06 01:34:17 +0000691 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000692
John McCallc0bf4622010-02-23 00:48:20 +0000693 // Emit the constructor prologue, i.e. the base and member
694 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000695 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000696
697 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000698 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000699 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
700 else if (Body)
701 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000702
703 // Emit any cleanup blocks associated with the member or base
704 // initializers, which includes (along the exceptional path) the
705 // destructors for those members and bases that were fully
706 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000707 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000708
John McCallc0bf4622010-02-23 00:48:20 +0000709 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000710 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000711}
712
Anders Carlsson607d0372009-12-24 22:46:43 +0000713/// EmitCtorPrologue - This routine generates necessary code to initialize
714/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000715void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000716 CXXCtorType CtorType,
717 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000718 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000719
Sean Huntcbb67482011-01-08 20:30:50 +0000720 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000721
Anders Carlsson607d0372009-12-24 22:46:43 +0000722 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
723 E = CD->init_end();
724 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000725 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000726
Anders Carlsson607d0372009-12-24 22:46:43 +0000727 if (Member->isBaseInitializer())
728 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
729 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000730 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000731 }
732
Anders Carlsson603d6d12010-03-28 21:07:49 +0000733 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000734
John McCallf1549f62010-07-06 01:34:17 +0000735 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000736 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000737}
738
John McCall9fc6a772010-02-19 09:25:03 +0000739/// EmitDestructorBody - Emits the body of the current destructor.
740void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
741 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
742 CXXDtorType DtorType = CurGD.getDtorType();
743
John McCall50da2ca2010-07-21 05:30:47 +0000744 // The call to operator delete in a deleting destructor happens
745 // outside of the function-try-block, which means it's always
746 // possible to delegate the destructor body to the complete
747 // destructor. Do so.
748 if (DtorType == Dtor_Deleting) {
749 EnterDtorCleanups(Dtor, Dtor_Deleting);
750 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
751 LoadCXXThis());
752 PopCleanupBlock();
753 return;
754 }
755
John McCall9fc6a772010-02-19 09:25:03 +0000756 Stmt *Body = Dtor->getBody();
757
758 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000759 // anything else.
760 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000761 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000762 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000763
John McCall50da2ca2010-07-21 05:30:47 +0000764 // Enter the epilogue cleanups.
765 RunCleanupsScope DtorEpilogue(*this);
766
John McCall9fc6a772010-02-19 09:25:03 +0000767 // If this is the complete variant, just invoke the base variant;
768 // the epilogue will destruct the virtual bases. But we can't do
769 // this optimization if the body is a function-try-block, because
770 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000771 switch (DtorType) {
772 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
773
774 case Dtor_Complete:
775 // Enter the cleanup scopes for virtual bases.
776 EnterDtorCleanups(Dtor, Dtor_Complete);
777
778 if (!isTryBody) {
779 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
780 LoadCXXThis());
781 break;
782 }
783 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000784
John McCall50da2ca2010-07-21 05:30:47 +0000785 case Dtor_Base:
786 // Enter the cleanup scopes for fields and non-virtual bases.
787 EnterDtorCleanups(Dtor, Dtor_Base);
788
789 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000790 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000791
792 if (isTryBody)
793 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
794 else if (Body)
795 EmitStmt(Body);
796 else {
797 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
798 // nothing to do besides what's in the epilogue
799 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000800 // -fapple-kext must inline any call to this dtor into
801 // the caller's body.
802 if (getContext().getLangOptions().AppleKext)
803 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000804 break;
John McCall9fc6a772010-02-19 09:25:03 +0000805 }
806
John McCall50da2ca2010-07-21 05:30:47 +0000807 // Jump out through the epilogue cleanups.
808 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000809
810 // Exit the try if applicable.
811 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000812 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000813}
814
John McCall50da2ca2010-07-21 05:30:47 +0000815namespace {
816 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000817 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000818 CallDtorDelete() {}
819
820 void Emit(CodeGenFunction &CGF, bool IsForEH) {
821 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
822 const CXXRecordDecl *ClassDecl = Dtor->getParent();
823 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
824 CGF.getContext().getTagDeclType(ClassDecl));
825 }
826 };
827
John McCall1f0fca52010-07-21 07:22:38 +0000828 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000829 const FieldDecl *Field;
830 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
831
832 void Emit(CodeGenFunction &CGF, bool IsForEH) {
833 QualType FieldType = Field->getType();
834 const ConstantArrayType *Array =
835 CGF.getContext().getAsConstantArrayType(FieldType);
836
837 QualType BaseType =
838 CGF.getContext().getBaseElementType(Array->getElementType());
839 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
840
841 llvm::Value *ThisPtr = CGF.LoadCXXThis();
842 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
843 // FIXME: Qualifiers?
844 /*CVRQualifiers=*/0);
845
846 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
847 llvm::Value *BaseAddrPtr =
848 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
849 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
850 Array, BaseAddrPtr);
851 }
852 };
853
John McCall1f0fca52010-07-21 07:22:38 +0000854 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000855 const FieldDecl *Field;
856 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
857
858 void Emit(CodeGenFunction &CGF, bool IsForEH) {
859 const CXXRecordDecl *FieldClassDecl =
860 Field->getType()->getAsCXXRecordDecl();
861
862 llvm::Value *ThisPtr = CGF.LoadCXXThis();
863 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
864 // FIXME: Qualifiers?
865 /*CVRQualifiers=*/0);
866
867 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
868 Dtor_Complete, /*ForVirtualBase=*/false,
869 LHS.getAddress());
870 }
871 };
872}
873
Anders Carlsson607d0372009-12-24 22:46:43 +0000874/// EmitDtorEpilogue - Emit all code that comes at the end of class's
875/// destructor. This is to call destructors on members and base classes
876/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000877void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
878 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000879 assert(!DD->isTrivial() &&
880 "Should not emit dtor epilogue for trivial dtor!");
881
John McCall50da2ca2010-07-21 05:30:47 +0000882 // The deleting-destructor phase just needs to call the appropriate
883 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000884 if (DtorType == Dtor_Deleting) {
885 assert(DD->getOperatorDelete() &&
886 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000887 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000888 return;
889 }
890
John McCall50da2ca2010-07-21 05:30:47 +0000891 const CXXRecordDecl *ClassDecl = DD->getParent();
892
893 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000894 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000895
896 // We push them in the forward order so that they'll be popped in
897 // the reverse order.
898 for (CXXRecordDecl::base_class_const_iterator I =
899 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000900 I != E; ++I) {
901 const CXXBaseSpecifier &Base = *I;
902 CXXRecordDecl *BaseClassDecl
903 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
904
905 // Ignore trivial destructors.
906 if (BaseClassDecl->hasTrivialDestructor())
907 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000908
John McCall1f0fca52010-07-21 07:22:38 +0000909 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
910 BaseClassDecl,
911 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000912 }
John McCall50da2ca2010-07-21 05:30:47 +0000913
John McCall3b477332010-02-18 19:59:28 +0000914 return;
915 }
916
917 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000918
919 // Destroy non-virtual bases.
920 for (CXXRecordDecl::base_class_const_iterator I =
921 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
922 const CXXBaseSpecifier &Base = *I;
923
924 // Ignore virtual bases.
925 if (Base.isVirtual())
926 continue;
927
928 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
929
930 // Ignore trivial destructors.
931 if (BaseClassDecl->hasTrivialDestructor())
932 continue;
John McCall3b477332010-02-18 19:59:28 +0000933
John McCall1f0fca52010-07-21 07:22:38 +0000934 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
935 BaseClassDecl,
936 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000937 }
938
939 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000940 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
941 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
942 E = ClassDecl->field_end(); I != E; ++I) {
943 const FieldDecl *Field = *I;
944
945 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000946 const ConstantArrayType *Array =
947 getContext().getAsConstantArrayType(FieldType);
948 if (Array)
949 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000950
951 const RecordType *RT = FieldType->getAs<RecordType>();
952 if (!RT)
953 continue;
954
955 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
956 if (FieldClassDecl->hasTrivialDestructor())
957 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000958
Anders Carlsson607d0372009-12-24 22:46:43 +0000959 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000960 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000961 else
John McCall1f0fca52010-07-21 07:22:38 +0000962 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000963 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000964}
965
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000966/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
967/// for-loop to call the default constructor on individual members of the
968/// array.
969/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
970/// array type and 'ArrayPtr' points to the beginning fo the array.
971/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000972///
973/// \param ZeroInitialization True if each element should be zero-initialized
974/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000975void
976CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000977 const ConstantArrayType *ArrayTy,
978 llvm::Value *ArrayPtr,
979 CallExpr::const_arg_iterator ArgBeg,
980 CallExpr::const_arg_iterator ArgEnd,
981 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000982
983 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
984 llvm::Value * NumElements =
985 llvm::ConstantInt::get(SizeTy,
986 getContext().getConstantArrayElementCount(ArrayTy));
987
Douglas Gregor59174c02010-07-21 01:10:17 +0000988 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
989 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000990}
991
992void
993CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
994 llvm::Value *NumElements,
995 llvm::Value *ArrayPtr,
996 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000997 CallExpr::const_arg_iterator ArgEnd,
998 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000999 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1000
1001 // Create a temporary for the loop index and initialize it with 0.
1002 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1003 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1004 Builder.CreateStore(Zero, IndexPtr);
1005
1006 // Start the loop with a block that tests the condition.
1007 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1008 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1009
1010 EmitBlock(CondBlock);
1011
1012 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1013
1014 // Generate: if (loop-index < number-of-elements fall to the loop body,
1015 // otherwise, go to the block after the for-loop.
1016 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1017 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1018 // If the condition is true, execute the body.
1019 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1020
1021 EmitBlock(ForBody);
1022
1023 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1024 // Inside the loop body, emit the constructor call on the array element.
1025 Counter = Builder.CreateLoad(IndexPtr);
1026 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1027 "arrayidx");
1028
Douglas Gregor59174c02010-07-21 01:10:17 +00001029 // Zero initialize the storage, if requested.
1030 if (ZeroInitialization)
1031 EmitNullInitialization(Address,
1032 getContext().getTypeDeclType(D->getParent()));
1033
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001034 // C++ [class.temporary]p4:
1035 // There are two contexts in which temporaries are destroyed at a different
1036 // point than the end of the full-expression. The first context is when a
1037 // default constructor is called to initialize an element of an array.
1038 // If the constructor has one or more default arguments, the destruction of
1039 // every temporary created in a default argument expression is sequenced
1040 // before the construction of the next array element, if any.
1041
1042 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001043 {
John McCallf1549f62010-07-06 01:34:17 +00001044 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001045
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001046 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001047 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001048 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001049
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001050 EmitBlock(ContinueBlock);
1051
1052 // Emit the increment of the loop counter.
1053 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1054 Counter = Builder.CreateLoad(IndexPtr);
1055 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1056 Builder.CreateStore(NextVal, IndexPtr);
1057
1058 // Finally, branch back up to the condition for the next iteration.
1059 EmitBranch(CondBlock);
1060
1061 // Emit the fall-through block.
1062 EmitBlock(AfterFor, true);
1063}
1064
1065/// EmitCXXAggrDestructorCall - calls the default destructor on array
1066/// elements in reverse order of construction.
1067void
1068CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1069 const ArrayType *Array,
1070 llvm::Value *This) {
1071 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1072 assert(CA && "Do we support VLA for destruction ?");
1073 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1074
1075 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1076 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1077 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1078}
1079
1080/// EmitCXXAggrDestructorCall - calls the default destructor on array
1081/// elements in reverse order of construction.
1082void
1083CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1084 llvm::Value *UpperCount,
1085 llvm::Value *This) {
1086 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1087 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1088
1089 // Create a temporary for the loop index and initialize it with count of
1090 // array elements.
1091 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1092
1093 // Store the number of elements in the index pointer.
1094 Builder.CreateStore(UpperCount, IndexPtr);
1095
1096 // Start the loop with a block that tests the condition.
1097 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1098 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1099
1100 EmitBlock(CondBlock);
1101
1102 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1103
1104 // Generate: if (loop-index != 0 fall to the loop body,
1105 // otherwise, go to the block after the for-loop.
1106 llvm::Value* zeroConstant =
1107 llvm::Constant::getNullValue(SizeLTy);
1108 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1109 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1110 "isne");
1111 // If the condition is true, execute the body.
1112 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1113
1114 EmitBlock(ForBody);
1115
1116 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1117 // Inside the loop body, emit the constructor call on the array element.
1118 Counter = Builder.CreateLoad(IndexPtr);
1119 Counter = Builder.CreateSub(Counter, One);
1120 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001121 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001122
1123 EmitBlock(ContinueBlock);
1124
1125 // Emit the decrement of the loop counter.
1126 Counter = Builder.CreateLoad(IndexPtr);
1127 Counter = Builder.CreateSub(Counter, One, "dec");
1128 Builder.CreateStore(Counter, IndexPtr);
1129
1130 // Finally, branch back up to the condition for the next iteration.
1131 EmitBranch(CondBlock);
1132
1133 // Emit the fall-through block.
1134 EmitBlock(AfterFor, true);
1135}
1136
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001137void
1138CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001139 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001140 llvm::Value *This,
1141 CallExpr::const_arg_iterator ArgBeg,
1142 CallExpr::const_arg_iterator ArgEnd) {
John McCall8b6bbeb2010-02-06 00:25:16 +00001143 if (D->isTrivial()) {
1144 if (ArgBeg == ArgEnd) {
1145 // Trivial default constructor, no codegen required.
1146 assert(D->isDefaultConstructor() &&
1147 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001148 return;
1149 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001150
1151 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1152 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1153
John McCall8b6bbeb2010-02-06 00:25:16 +00001154 const Expr *E = (*ArgBeg);
1155 QualType Ty = E->getType();
1156 llvm::Value *Src = EmitLValue(E).getAddress();
1157 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001158 return;
1159 }
1160
Anders Carlsson314e6222010-05-02 23:33:10 +00001161 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001162 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1163
Anders Carlssonc997d422010-01-02 01:01:18 +00001164 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001165}
1166
John McCallc0bf4622010-02-23 00:48:20 +00001167void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001168CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1169 llvm::Value *This, llvm::Value *Src,
1170 CallExpr::const_arg_iterator ArgBeg,
1171 CallExpr::const_arg_iterator ArgEnd) {
1172 if (D->isTrivial()) {
1173 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1174 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1175 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1176 return;
1177 }
1178 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1179 clang::Ctor_Complete);
1180 assert(D->isInstance() &&
1181 "Trying to emit a member call expr on a static method!");
1182
1183 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1184
1185 CallArgList Args;
1186
1187 // Push the this ptr.
1188 Args.push_back(std::make_pair(RValue::get(This),
1189 D->getThisType(getContext())));
1190
1191
1192 // Push the src ptr.
1193 QualType QT = *(FPT->arg_type_begin());
1194 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1195 Src = Builder.CreateBitCast(Src, t);
1196 Args.push_back(std::make_pair(RValue::get(Src), QT));
1197
1198 // Skip over first argument (Src).
1199 ++ArgBeg;
1200 CallExpr::const_arg_iterator Arg = ArgBeg;
1201 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1202 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1203 assert(Arg != ArgEnd && "Running over edge of argument list!");
1204 QualType ArgType = *I;
1205 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1206 ArgType));
1207 }
1208 // Either we've emitted all the call args, or we have a call to a
1209 // variadic function.
1210 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1211 "Extra arguments in non-variadic function!");
1212 // If we still have any arguments, emit them using the type of the argument.
1213 for (; Arg != ArgEnd; ++Arg) {
1214 QualType ArgType = Arg->getType();
1215 Args.push_back(std::make_pair(EmitCallArg(*Arg, ArgType),
1216 ArgType));
1217 }
1218
1219 QualType ResultType = FPT->getResultType();
1220 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1221 FPT->getExtInfo()),
1222 Callee, ReturnValueSlot(), Args, D);
1223}
1224
1225void
John McCallc0bf4622010-02-23 00:48:20 +00001226CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1227 CXXCtorType CtorType,
1228 const FunctionArgList &Args) {
1229 CallArgList DelegateArgs;
1230
1231 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1232 assert(I != E && "no parameters to constructor");
1233
1234 // this
1235 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1236 I->second));
1237 ++I;
1238
1239 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001240 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1241 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001242 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1243 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1244
Anders Carlssonaf440352010-03-23 04:11:45 +00001245 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001246 assert(I != E && "cannot skip vtt parameter, already done with args");
1247 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1248 ++I;
1249 }
1250 }
1251
1252 // Explicit arguments.
1253 for (; I != E; ++I) {
John McCallc0bf4622010-02-23 00:48:20 +00001254 const VarDecl *Param = I->first;
1255 QualType ArgType = Param->getType(); // because we're passing it to itself
John McCall27360712010-05-26 22:34:26 +00001256 RValue Arg = EmitDelegateCallArg(Param);
John McCallc0bf4622010-02-23 00:48:20 +00001257
1258 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1259 }
1260
1261 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1262 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1263 ReturnValueSlot(), DelegateArgs, Ctor);
1264}
1265
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001266void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1267 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001268 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001269 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001270 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1271 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001272 llvm::Value *Callee = 0;
1273 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001274 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1275 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001276
1277 if (!Callee)
1278 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001279
Anders Carlssonc997d422010-01-02 01:01:18 +00001280 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001281}
1282
John McCall291ae942010-07-21 01:41:18 +00001283namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001284 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001285 const CXXDestructorDecl *Dtor;
1286 llvm::Value *Addr;
1287
1288 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1289 : Dtor(D), Addr(Addr) {}
1290
1291 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1292 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1293 /*ForVirtualBase=*/false, Addr);
1294 }
1295 };
1296}
1297
John McCall81407d42010-07-21 06:29:51 +00001298void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1299 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001300 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001301}
1302
John McCallf1549f62010-07-06 01:34:17 +00001303void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1304 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1305 if (!ClassDecl) return;
1306 if (ClassDecl->hasTrivialDestructor()) return;
1307
1308 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001309 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001310}
1311
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001312llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001313CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1314 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001315 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001316 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Anders Carlssonbba16072010-03-11 07:15:17 +00001317 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001318 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001319
1320 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001321 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001322 const llvm::Type *PtrDiffTy =
1323 ConvertType(getContext().getPointerDiffType());
1324
1325 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1326 PtrDiffTy->getPointerTo());
1327
1328 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1329
1330 return VBaseOffset;
1331}
1332
Anders Carlssond103f9f2010-03-28 19:40:00 +00001333void
1334CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001335 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001336 uint64_t OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001337 llvm::Constant *VTable,
1338 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001339 const CXXRecordDecl *RD = Base.getBase();
1340
Anders Carlssond103f9f2010-03-28 19:40:00 +00001341 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001342 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001343
Anders Carlssonc83f1062010-03-29 01:08:49 +00001344 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001345 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001346 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001347 // Get the secondary vpointer index.
1348 uint64_t VirtualPointerIndex =
1349 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1350
1351 /// Load the VTT.
1352 llvm::Value *VTT = LoadCXXVTT();
1353 if (VirtualPointerIndex)
1354 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1355
1356 // And load the address point from the VTT.
1357 VTableAddressPoint = Builder.CreateLoad(VTT);
1358 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001359 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001360 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001361 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001362 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001363
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001364 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001365 llvm::Value *VirtualOffset = 0;
1366 uint64_t NonVirtualOffset = 0;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001367
1368 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1369 // We need to use the virtual base offset offset because the virtual base
1370 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001371 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1372 NearestVBase);
1373 NonVirtualOffset = OffsetFromNearestVBase / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001374 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001375 // We can just use the base offset in the complete class.
1376 NonVirtualOffset = Base.getBaseOffset() / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001377 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001378
1379 // Apply the offsets.
1380 llvm::Value *VTableField = LoadCXXThis();
1381
1382 if (NonVirtualOffset || VirtualOffset)
1383 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1384 NonVirtualOffset,
1385 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001386
Anders Carlssond103f9f2010-03-28 19:40:00 +00001387 // Finally, store the address point.
1388 const llvm::Type *AddressPointPtrTy =
1389 VTableAddressPoint->getType()->getPointerTo();
1390 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1391 Builder.CreateStore(VTableAddressPoint, VTableField);
1392}
1393
Anders Carlsson603d6d12010-03-28 21:07:49 +00001394void
1395CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001396 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001397 uint64_t OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001398 bool BaseIsNonVirtualPrimaryBase,
1399 llvm::Constant *VTable,
1400 const CXXRecordDecl *VTableClass,
1401 VisitedVirtualBasesSetTy& VBases) {
1402 // If this base is a non-virtual primary base the address point has already
1403 // been set.
1404 if (!BaseIsNonVirtualPrimaryBase) {
1405 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001406 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1407 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001408 }
1409
1410 const CXXRecordDecl *RD = Base.getBase();
1411
1412 // Traverse bases.
1413 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1414 E = RD->bases_end(); I != E; ++I) {
1415 CXXRecordDecl *BaseDecl
1416 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1417
1418 // Ignore classes without a vtable.
1419 if (!BaseDecl->isDynamicClass())
1420 continue;
1421
1422 uint64_t BaseOffset;
Anders Carlsson42358402010-05-03 00:07:07 +00001423 uint64_t BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001424 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001425
1426 if (I->isVirtual()) {
1427 // Check if we've visited this virtual base before.
1428 if (!VBases.insert(BaseDecl))
1429 continue;
1430
1431 const ASTRecordLayout &Layout =
1432 getContext().getASTRecordLayout(VTableClass);
1433
Anders Carlssona14f5972010-10-31 23:22:37 +00001434 BaseOffset = Layout.getVBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001435 BaseOffsetFromNearestVBase = 0;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001436 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001437 } else {
1438 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1439
Anders Carlssona14f5972010-10-31 23:22:37 +00001440 BaseOffset =
1441 Base.getBaseOffset() + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001442 BaseOffsetFromNearestVBase =
Anders Carlssona14f5972010-10-31 23:22:37 +00001443 OffsetFromNearestVBase + Layout.getBaseClassOffsetInBits(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001444 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001445 }
1446
1447 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001448 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001449 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001450 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001451 VTable, VTableClass, VBases);
1452 }
1453}
1454
1455void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1456 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001457 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001458 return;
1459
Anders Carlsson07036902010-03-26 04:39:42 +00001460 // Get the VTable.
1461 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001462
Anders Carlsson603d6d12010-03-28 21:07:49 +00001463 // Initialize the vtable pointers for this class and all of its bases.
1464 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001465 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson42358402010-05-03 00:07:07 +00001466 /*OffsetFromNearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001467 /*BaseIsNonVirtualPrimaryBase=*/false,
1468 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001469}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001470
1471llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1472 const llvm::Type *Ty) {
1473 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1474 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1475}