blob: 64b1615d7c883e55b01cf98b063326de9dc8d4b0 [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
175 llvm::Value *IsNull =
176 Builder.CreateICmpEQ(Value,
177 llvm::Constant::getNullValue(Value->getType()));
178 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
179 EmitBlock(CastNotNull);
180 }
181
182 llvm::Value *VirtualOffset = 0;
183
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000184 if (VBase) {
185 if (Derived->hasAttr<FinalAttr>()) {
186 VirtualOffset = 0;
187
188 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
189
Ken Dyck55c02582011-03-22 00:53:26 +0000190 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
191 NonVirtualOffset += VBaseOffset;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000192 } else
193 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
194 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000195
196 // Apply the offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000197 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000198 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000199 VirtualOffset);
200
201 // Cast back.
202 Value = Builder.CreateBitCast(Value, BasePtrTy);
203
204 if (NullCheckValue) {
205 Builder.CreateBr(CastEnd);
206 EmitBlock(CastNull);
207 Builder.CreateBr(CastEnd);
208 EmitBlock(CastEnd);
209
210 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
211 PHI->reserveOperandSpace(2);
212 PHI->addIncoming(Value, CastNotNull);
213 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
214 CastNull);
215 Value = PHI;
216 }
217
218 return Value;
219}
220
221llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000222CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000223 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000224 CastExpr::path_const_iterator PathBegin,
225 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000226 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000227 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000228
Anders Carlssona3697c92009-11-23 17:57:54 +0000229 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000230 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000231 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
232
Anders Carlssona552ea72010-01-31 01:43:37 +0000233 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000234 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000235
236 if (!NonVirtualOffset) {
237 // No offset, we can just cast back.
238 return Builder.CreateBitCast(Value, DerivedPtrTy);
239 }
240
Anders Carlssona3697c92009-11-23 17:57:54 +0000241 llvm::BasicBlock *CastNull = 0;
242 llvm::BasicBlock *CastNotNull = 0;
243 llvm::BasicBlock *CastEnd = 0;
244
245 if (NullCheckValue) {
246 CastNull = createBasicBlock("cast.null");
247 CastNotNull = createBasicBlock("cast.notnull");
248 CastEnd = createBasicBlock("cast.end");
249
250 llvm::Value *IsNull =
251 Builder.CreateICmpEQ(Value,
252 llvm::Constant::getNullValue(Value->getType()));
253 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
254 EmitBlock(CastNotNull);
255 }
256
Anders Carlssona552ea72010-01-31 01:43:37 +0000257 // Apply the offset.
258 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
259 Value = Builder.CreateSub(Value, NonVirtualOffset);
260 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
261
262 // Just cast.
263 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000264
265 if (NullCheckValue) {
266 Builder.CreateBr(CastEnd);
267 EmitBlock(CastNull);
268 Builder.CreateBr(CastEnd);
269 EmitBlock(CastEnd);
270
271 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
272 PHI->reserveOperandSpace(2);
273 PHI->addIncoming(Value, CastNotNull);
274 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
275 CastNull);
276 Value = PHI;
277 }
278
279 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000280}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000281
Anders Carlssonc997d422010-01-02 01:01:18 +0000282/// GetVTTParameter - Return the VTT parameter that should be passed to a
283/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000284static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
285 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000286 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000287 // This constructor/destructor does not need a VTT parameter.
288 return 0;
289 }
290
291 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
292 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000293
Anders Carlssonc997d422010-01-02 01:01:18 +0000294 llvm::Value *VTT;
295
John McCall3b477332010-02-18 19:59:28 +0000296 uint64_t SubVTTIndex;
297
298 // If the record matches the base, this is the complete ctor/dtor
299 // variant calling the base variant in a class with virtual bases.
300 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000301 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000302 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000303 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000304 SubVTTIndex = 0;
305 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000306 const ASTRecordLayout &Layout =
307 CGF.getContext().getASTRecordLayout(RD);
308 uint64_t BaseOffset = ForVirtualBase ?
Anders Carlssona14f5972010-10-31 23:22:37 +0000309 Layout.getVBaseClassOffsetInBits(Base) :
310 Layout.getBaseClassOffsetInBits(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000311
312 SubVTTIndex =
313 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000314 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
315 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000316
Anders Carlssonaf440352010-03-23 04:11:45 +0000317 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000318 // A VTT parameter was passed to the constructor, use it.
319 VTT = CGF.LoadCXXVTT();
320 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
321 } else {
322 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000323 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000324 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
325 }
326
327 return VTT;
328}
329
John McCall182ab512010-07-21 01:23:41 +0000330namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000331 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000332 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000333 const CXXRecordDecl *BaseClass;
334 bool BaseIsVirtual;
335 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
336 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000337
338 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000339 const CXXRecordDecl *DerivedClass =
340 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
341
342 const CXXDestructorDecl *D = BaseClass->getDestructor();
343 llvm::Value *Addr =
344 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
345 DerivedClass, BaseClass,
346 BaseIsVirtual);
347 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000348 }
349 };
John McCall7e1dff72010-09-17 02:31:44 +0000350
351 /// A visitor which checks whether an initializer uses 'this' in a
352 /// way which requires the vtable to be properly set.
353 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
354 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
355
356 bool UsesThis;
357
358 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
359
360 // Black-list all explicit and implicit references to 'this'.
361 //
362 // Do we need to worry about external references to 'this' derived
363 // from arbitrary code? If so, then anything which runs arbitrary
364 // external code might potentially access the vtable.
365 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
366 };
367}
368
369static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
370 DynamicThisUseChecker Checker(C);
371 Checker.Visit(const_cast<Expr*>(Init));
372 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000373}
374
Anders Carlsson607d0372009-12-24 22:46:43 +0000375static void EmitBaseInitializer(CodeGenFunction &CGF,
376 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000377 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000378 CXXCtorType CtorType) {
379 assert(BaseInit->isBaseInitializer() &&
380 "Must have base initializer!");
381
382 llvm::Value *ThisPtr = CGF.LoadCXXThis();
383
384 const Type *BaseType = BaseInit->getBaseClass();
385 CXXRecordDecl *BaseClassDecl =
386 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
387
Anders Carlsson80638c52010-04-12 00:51:03 +0000388 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000389
390 // The base constructor doesn't construct virtual bases.
391 if (CtorType == Ctor_Base && isBaseVirtual)
392 return;
393
John McCall7e1dff72010-09-17 02:31:44 +0000394 // If the initializer for the base (other than the constructor
395 // itself) accesses 'this' in any way, we need to initialize the
396 // vtables.
397 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
398 CGF.InitializeVTablePointers(ClassDecl);
399
John McCallbff225e2010-02-16 04:15:37 +0000400 // We can pretend to be a complete class because it only matters for
401 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000402 llvm::Value *V =
403 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000404 BaseClassDecl,
405 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000406
John McCall558d2ab2010-09-15 10:14:12 +0000407 AggValueSlot AggSlot = AggValueSlot::forAddr(V, false, /*Lifetime*/ true);
408
409 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000410
Anders Carlsson7a178512011-02-28 00:33:03 +0000411 if (CGF.CGM.getLangOptions().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000412 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000413 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
414 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000415}
416
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000417static void EmitAggMemberInitializer(CodeGenFunction &CGF,
418 LValue LHS,
419 llvm::Value *ArrayIndexVar,
Sean Huntcbb67482011-01-08 20:30:50 +0000420 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000421 QualType T,
422 unsigned Index) {
423 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000424 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000425
426 llvm::Value *Dest = LHS.getAddress();
427 if (ArrayIndexVar) {
428 // If we have an array index variable, load it and use it as an offset.
429 // Then, increment the value.
430 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
431 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
432 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
433 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
434 CGF.Builder.CreateStore(Next, ArrayIndexVar);
435 }
John McCall558d2ab2010-09-15 10:14:12 +0000436
437 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.isVolatileQualified(),
438 /*Lifetime*/ true);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000439
John McCall558d2ab2010-09-15 10:14:12 +0000440 CGF.EmitAggExpr(MemberInit->getInit(), Slot);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000441
442 return;
443 }
444
445 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
446 assert(Array && "Array initialization without the array type?");
447 llvm::Value *IndexVar
448 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
449 assert(IndexVar && "Array index variable not loaded");
450
451 // Initialize this index variable to zero.
452 llvm::Value* Zero
453 = llvm::Constant::getNullValue(
454 CGF.ConvertType(CGF.getContext().getSizeType()));
455 CGF.Builder.CreateStore(Zero, IndexVar);
456
457 // Start the loop with a block that tests the condition.
458 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
459 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
460
461 CGF.EmitBlock(CondBlock);
462
463 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
464 // Generate: if (loop-index < number-of-elements) fall to the loop body,
465 // otherwise, go to the block after the for-loop.
466 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000467 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000468 llvm::Value *NumElementsPtr =
469 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000470 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
471 "isless");
472
473 // If the condition is true, execute the body.
474 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
475
476 CGF.EmitBlock(ForBody);
477 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
478
479 {
John McCallf1549f62010-07-06 01:34:17 +0000480 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000481
482 // Inside the loop body recurse to emit the inner loop or, eventually, the
483 // constructor call.
484 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
485 Array->getElementType(), Index + 1);
486 }
487
488 CGF.EmitBlock(ContinueBlock);
489
490 // Emit the increment of the loop counter.
491 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
492 Counter = CGF.Builder.CreateLoad(IndexVar);
493 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
494 CGF.Builder.CreateStore(NextVal, IndexVar);
495
496 // Finally, branch back up to the condition for the next iteration.
497 CGF.EmitBranch(CondBlock);
498
499 // Emit the fall-through block.
500 CGF.EmitBlock(AfterFor, true);
501}
John McCall182ab512010-07-21 01:23:41 +0000502
503namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000504 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000505 FieldDecl *Field;
506 CXXDestructorDecl *Dtor;
507
508 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
509 : Field(Field), Dtor(Dtor) {}
510
511 void Emit(CodeGenFunction &CGF, bool IsForEH) {
512 // FIXME: Is this OK for C++0x delegating constructors?
513 llvm::Value *ThisPtr = CGF.LoadCXXThis();
514 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
515
516 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
517 LHS.getAddress());
518 }
519 };
520}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000521
Anders Carlsson607d0372009-12-24 22:46:43 +0000522static void EmitMemberInitializer(CodeGenFunction &CGF,
523 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000524 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000525 const CXXConstructorDecl *Constructor,
526 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000527 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000528 "Must have member initializer!");
529
530 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000531 FieldDecl *Field = MemberInit->getAnyMember();
Anders Carlsson607d0372009-12-24 22:46:43 +0000532 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
533
534 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000535 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000536
Anders Carlsson607d0372009-12-24 22:46:43 +0000537 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000538 if (MemberInit->isIndirectMemberInitializer()) {
539 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
540 MemberInit->getIndirectMember(), 0);
541 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000542 } else {
543 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000544 }
545
Sean Huntcbb67482011-01-08 20:30:50 +0000546 // FIXME: If there's no initializer and the CXXCtorInitializer
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000547 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000548 RValue RHS;
549 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000550 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000551 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000552 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000553 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000554 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000555 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000556 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000557 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
558 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000559 LHS.isVolatileQualified());
560 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000561 llvm::Value *ArrayIndexVar = 0;
562 const ConstantArrayType *Array
563 = CGF.getContext().getAsConstantArrayType(FieldType);
564 if (Array && Constructor->isImplicit() &&
565 Constructor->isCopyConstructor()) {
566 const llvm::Type *SizeTy
567 = CGF.ConvertType(CGF.getContext().getSizeType());
568
569 // The LHS is a pointer to the first object we'll be constructing, as
570 // a flat array.
571 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
572 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
573 BasePtr = llvm::PointerType::getUnqual(BasePtr);
574 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
575 BasePtr);
Daniel Dunbar9f553f52010-08-21 03:08:16 +0000576 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000577
578 // Create an array index that will be used to walk over all of the
579 // objects we're constructing.
580 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
581 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
582 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
583
584 // If we are copying an array of scalars or classes with trivial copy
585 // constructors, perform a single aggregate copy.
586 const RecordType *Record = BaseElementTy->getAs<RecordType>();
587 if (!Record ||
588 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
589 // Find the source pointer. We knows it's the last argument because
590 // we know we're in a copy constructor.
591 unsigned SrcArgIndex = Args.size() - 1;
592 llvm::Value *SrcPtr
John McCalld26bc762011-03-09 04:27:21 +0000593 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000594 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
595
596 // Copy the aggregate.
597 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
598 LHS.isVolatileQualified());
599 return;
600 }
601
602 // Emit the block variables for the array indices, if any.
603 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
John McCallb6bbcc92010-10-15 04:57:14 +0000604 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I));
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000605 }
606
607 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000608
Anders Carlsson7a178512011-02-28 00:33:03 +0000609 if (!CGF.CGM.getLangOptions().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000610 return;
611
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000612 // FIXME: If we have an array of classes w/ non-trivial destructors,
613 // we need to destroy in reverse order of construction along the exception
614 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000615 const RecordType *RT = FieldType->getAs<RecordType>();
616 if (!RT)
617 return;
618
619 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000620 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000621 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
622 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000623 }
624}
625
John McCallc0bf4622010-02-23 00:48:20 +0000626/// Checks whether the given constructor is a valid subject for the
627/// complete-to-base constructor delegation optimization, i.e.
628/// emitting the complete constructor as a simple call to the base
629/// constructor.
630static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
631
632 // Currently we disable the optimization for classes with virtual
633 // bases because (1) the addresses of parameter variables need to be
634 // consistent across all initializers but (2) the delegate function
635 // call necessarily creates a second copy of the parameter variable.
636 //
637 // The limiting example (purely theoretical AFAIK):
638 // struct A { A(int &c) { c++; } };
639 // struct B : virtual A {
640 // B(int count) : A(count) { printf("%d\n", count); }
641 // };
642 // ...although even this example could in principle be emitted as a
643 // delegation since the address of the parameter doesn't escape.
644 if (Ctor->getParent()->getNumVBases()) {
645 // TODO: white-list trivial vbase initializers. This case wouldn't
646 // be subject to the restrictions below.
647
648 // TODO: white-list cases where:
649 // - there are no non-reference parameters to the constructor
650 // - the initializers don't access any non-reference parameters
651 // - the initializers don't take the address of non-reference
652 // parameters
653 // - etc.
654 // If we ever add any of the above cases, remember that:
655 // - function-try-blocks will always blacklist this optimization
656 // - we need to perform the constructor prologue and cleanup in
657 // EmitConstructorBody.
658
659 return false;
660 }
661
662 // We also disable the optimization for variadic functions because
663 // it's impossible to "re-pass" varargs.
664 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
665 return false;
666
667 return true;
668}
669
John McCall9fc6a772010-02-19 09:25:03 +0000670/// EmitConstructorBody - Emits the body of the current constructor.
671void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
672 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
673 CXXCtorType CtorType = CurGD.getCtorType();
674
John McCallc0bf4622010-02-23 00:48:20 +0000675 // Before we go any further, try the complete->base constructor
676 // delegation optimization.
677 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000678 if (CGDebugInfo *DI = getDebugInfo())
679 DI->EmitStopPoint(Builder);
John McCallc0bf4622010-02-23 00:48:20 +0000680 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
681 return;
682 }
683
John McCall9fc6a772010-02-19 09:25:03 +0000684 Stmt *Body = Ctor->getBody();
685
John McCallc0bf4622010-02-23 00:48:20 +0000686 // Enter the function-try-block before the constructor prologue if
687 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000688 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000689 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000690 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000691
John McCallf1549f62010-07-06 01:34:17 +0000692 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000693
John McCallc0bf4622010-02-23 00:48:20 +0000694 // Emit the constructor prologue, i.e. the base and member
695 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000696 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000697
698 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000699 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000700 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
701 else if (Body)
702 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000703
704 // Emit any cleanup blocks associated with the member or base
705 // initializers, which includes (along the exceptional path) the
706 // destructors for those members and bases that were fully
707 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000708 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000709
John McCallc0bf4622010-02-23 00:48:20 +0000710 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000711 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000712}
713
Anders Carlsson607d0372009-12-24 22:46:43 +0000714/// EmitCtorPrologue - This routine generates necessary code to initialize
715/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000716void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000717 CXXCtorType CtorType,
718 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000719 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000720
Sean Huntcbb67482011-01-08 20:30:50 +0000721 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000722
Anders Carlsson607d0372009-12-24 22:46:43 +0000723 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
724 E = CD->init_end();
725 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000726 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000727
Anders Carlsson607d0372009-12-24 22:46:43 +0000728 if (Member->isBaseInitializer())
729 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
730 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000731 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000732 }
733
Anders Carlsson603d6d12010-03-28 21:07:49 +0000734 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000735
John McCallf1549f62010-07-06 01:34:17 +0000736 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000737 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000738}
739
John McCall9fc6a772010-02-19 09:25:03 +0000740/// EmitDestructorBody - Emits the body of the current destructor.
741void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
742 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
743 CXXDtorType DtorType = CurGD.getDtorType();
744
John McCall50da2ca2010-07-21 05:30:47 +0000745 // The call to operator delete in a deleting destructor happens
746 // outside of the function-try-block, which means it's always
747 // possible to delegate the destructor body to the complete
748 // destructor. Do so.
749 if (DtorType == Dtor_Deleting) {
750 EnterDtorCleanups(Dtor, Dtor_Deleting);
751 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
752 LoadCXXThis());
753 PopCleanupBlock();
754 return;
755 }
756
John McCall9fc6a772010-02-19 09:25:03 +0000757 Stmt *Body = Dtor->getBody();
758
759 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000760 // anything else.
761 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000762 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000763 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000764
John McCall50da2ca2010-07-21 05:30:47 +0000765 // Enter the epilogue cleanups.
766 RunCleanupsScope DtorEpilogue(*this);
767
John McCall9fc6a772010-02-19 09:25:03 +0000768 // If this is the complete variant, just invoke the base variant;
769 // the epilogue will destruct the virtual bases. But we can't do
770 // this optimization if the body is a function-try-block, because
771 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000772 switch (DtorType) {
773 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
774
775 case Dtor_Complete:
776 // Enter the cleanup scopes for virtual bases.
777 EnterDtorCleanups(Dtor, Dtor_Complete);
778
779 if (!isTryBody) {
780 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
781 LoadCXXThis());
782 break;
783 }
784 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000785
John McCall50da2ca2010-07-21 05:30:47 +0000786 case Dtor_Base:
787 // Enter the cleanup scopes for fields and non-virtual bases.
788 EnterDtorCleanups(Dtor, Dtor_Base);
789
790 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000791 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000792
793 if (isTryBody)
794 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
795 else if (Body)
796 EmitStmt(Body);
797 else {
798 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
799 // nothing to do besides what's in the epilogue
800 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000801 // -fapple-kext must inline any call to this dtor into
802 // the caller's body.
803 if (getContext().getLangOptions().AppleKext)
804 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000805 break;
John McCall9fc6a772010-02-19 09:25:03 +0000806 }
807
John McCall50da2ca2010-07-21 05:30:47 +0000808 // Jump out through the epilogue cleanups.
809 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000810
811 // Exit the try if applicable.
812 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000813 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000814}
815
John McCall50da2ca2010-07-21 05:30:47 +0000816namespace {
817 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000818 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000819 CallDtorDelete() {}
820
821 void Emit(CodeGenFunction &CGF, bool IsForEH) {
822 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
823 const CXXRecordDecl *ClassDecl = Dtor->getParent();
824 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
825 CGF.getContext().getTagDeclType(ClassDecl));
826 }
827 };
828
John McCall1f0fca52010-07-21 07:22:38 +0000829 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000830 const FieldDecl *Field;
831 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
832
833 void Emit(CodeGenFunction &CGF, bool IsForEH) {
834 QualType FieldType = Field->getType();
835 const ConstantArrayType *Array =
836 CGF.getContext().getAsConstantArrayType(FieldType);
837
838 QualType BaseType =
839 CGF.getContext().getBaseElementType(Array->getElementType());
840 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
841
842 llvm::Value *ThisPtr = CGF.LoadCXXThis();
843 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
844 // FIXME: Qualifiers?
845 /*CVRQualifiers=*/0);
846
847 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
848 llvm::Value *BaseAddrPtr =
849 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
850 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
851 Array, BaseAddrPtr);
852 }
853 };
854
John McCall1f0fca52010-07-21 07:22:38 +0000855 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000856 const FieldDecl *Field;
857 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
858
859 void Emit(CodeGenFunction &CGF, bool IsForEH) {
860 const CXXRecordDecl *FieldClassDecl =
861 Field->getType()->getAsCXXRecordDecl();
862
863 llvm::Value *ThisPtr = CGF.LoadCXXThis();
864 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
865 // FIXME: Qualifiers?
866 /*CVRQualifiers=*/0);
867
868 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
869 Dtor_Complete, /*ForVirtualBase=*/false,
870 LHS.getAddress());
871 }
872 };
873}
874
Anders Carlsson607d0372009-12-24 22:46:43 +0000875/// EmitDtorEpilogue - Emit all code that comes at the end of class's
876/// destructor. This is to call destructors on members and base classes
877/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000878void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
879 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000880 assert(!DD->isTrivial() &&
881 "Should not emit dtor epilogue for trivial dtor!");
882
John McCall50da2ca2010-07-21 05:30:47 +0000883 // The deleting-destructor phase just needs to call the appropriate
884 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000885 if (DtorType == Dtor_Deleting) {
886 assert(DD->getOperatorDelete() &&
887 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000888 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000889 return;
890 }
891
John McCall50da2ca2010-07-21 05:30:47 +0000892 const CXXRecordDecl *ClassDecl = DD->getParent();
893
894 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000895 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000896
897 // We push them in the forward order so that they'll be popped in
898 // the reverse order.
899 for (CXXRecordDecl::base_class_const_iterator I =
900 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000901 I != E; ++I) {
902 const CXXBaseSpecifier &Base = *I;
903 CXXRecordDecl *BaseClassDecl
904 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
905
906 // Ignore trivial destructors.
907 if (BaseClassDecl->hasTrivialDestructor())
908 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000909
John McCall1f0fca52010-07-21 07:22:38 +0000910 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
911 BaseClassDecl,
912 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000913 }
John McCall50da2ca2010-07-21 05:30:47 +0000914
John McCall3b477332010-02-18 19:59:28 +0000915 return;
916 }
917
918 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000919
920 // Destroy non-virtual bases.
921 for (CXXRecordDecl::base_class_const_iterator I =
922 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
923 const CXXBaseSpecifier &Base = *I;
924
925 // Ignore virtual bases.
926 if (Base.isVirtual())
927 continue;
928
929 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
930
931 // Ignore trivial destructors.
932 if (BaseClassDecl->hasTrivialDestructor())
933 continue;
John McCall3b477332010-02-18 19:59:28 +0000934
John McCall1f0fca52010-07-21 07:22:38 +0000935 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
936 BaseClassDecl,
937 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000938 }
939
940 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000941 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
942 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
943 E = ClassDecl->field_end(); I != E; ++I) {
944 const FieldDecl *Field = *I;
945
946 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000947 const ConstantArrayType *Array =
948 getContext().getAsConstantArrayType(FieldType);
949 if (Array)
950 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000951
952 const RecordType *RT = FieldType->getAs<RecordType>();
953 if (!RT)
954 continue;
955
956 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
957 if (FieldClassDecl->hasTrivialDestructor())
958 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000959
Anders Carlsson607d0372009-12-24 22:46:43 +0000960 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000961 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000962 else
John McCall1f0fca52010-07-21 07:22:38 +0000963 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000964 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000965}
966
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000967/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
968/// for-loop to call the default constructor on individual members of the
969/// array.
970/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
971/// array type and 'ArrayPtr' points to the beginning fo the array.
972/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000973///
974/// \param ZeroInitialization True if each element should be zero-initialized
975/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000976void
977CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000978 const ConstantArrayType *ArrayTy,
979 llvm::Value *ArrayPtr,
980 CallExpr::const_arg_iterator ArgBeg,
981 CallExpr::const_arg_iterator ArgEnd,
982 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000983
984 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
985 llvm::Value * NumElements =
986 llvm::ConstantInt::get(SizeTy,
987 getContext().getConstantArrayElementCount(ArrayTy));
988
Douglas Gregor59174c02010-07-21 01:10:17 +0000989 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
990 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000991}
992
993void
994CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
995 llvm::Value *NumElements,
996 llvm::Value *ArrayPtr,
997 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000998 CallExpr::const_arg_iterator ArgEnd,
999 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001000 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
1001
1002 // Create a temporary for the loop index and initialize it with 0.
1003 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
1004 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
1005 Builder.CreateStore(Zero, IndexPtr);
1006
1007 // Start the loop with a block that tests the condition.
1008 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1009 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1010
1011 EmitBlock(CondBlock);
1012
1013 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1014
1015 // Generate: if (loop-index < number-of-elements fall to the loop body,
1016 // otherwise, go to the block after the for-loop.
1017 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1018 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
1019 // If the condition is true, execute the body.
1020 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
1021
1022 EmitBlock(ForBody);
1023
1024 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1025 // Inside the loop body, emit the constructor call on the array element.
1026 Counter = Builder.CreateLoad(IndexPtr);
1027 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
1028 "arrayidx");
1029
Douglas Gregor59174c02010-07-21 01:10:17 +00001030 // Zero initialize the storage, if requested.
1031 if (ZeroInitialization)
1032 EmitNullInitialization(Address,
1033 getContext().getTypeDeclType(D->getParent()));
1034
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001035 // C++ [class.temporary]p4:
1036 // There are two contexts in which temporaries are destroyed at a different
1037 // point than the end of the full-expression. The first context is when a
1038 // default constructor is called to initialize an element of an array.
1039 // If the constructor has one or more default arguments, the destruction of
1040 // every temporary created in a default argument expression is sequenced
1041 // before the construction of the next array element, if any.
1042
1043 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001044 {
John McCallf1549f62010-07-06 01:34:17 +00001045 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001046
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001047 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +00001048 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001049 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001050
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001051 EmitBlock(ContinueBlock);
1052
1053 // Emit the increment of the loop counter.
1054 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1055 Counter = Builder.CreateLoad(IndexPtr);
1056 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1057 Builder.CreateStore(NextVal, IndexPtr);
1058
1059 // Finally, branch back up to the condition for the next iteration.
1060 EmitBranch(CondBlock);
1061
1062 // Emit the fall-through block.
1063 EmitBlock(AfterFor, true);
1064}
1065
1066/// EmitCXXAggrDestructorCall - calls the default destructor on array
1067/// elements in reverse order of construction.
1068void
1069CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1070 const ArrayType *Array,
1071 llvm::Value *This) {
1072 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1073 assert(CA && "Do we support VLA for destruction ?");
1074 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1075
1076 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1077 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1078 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1079}
1080
1081/// EmitCXXAggrDestructorCall - calls the default destructor on array
1082/// elements in reverse order of construction.
1083void
1084CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1085 llvm::Value *UpperCount,
1086 llvm::Value *This) {
1087 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1088 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1089
1090 // Create a temporary for the loop index and initialize it with count of
1091 // array elements.
1092 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1093
1094 // Store the number of elements in the index pointer.
1095 Builder.CreateStore(UpperCount, IndexPtr);
1096
1097 // Start the loop with a block that tests the condition.
1098 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1099 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1100
1101 EmitBlock(CondBlock);
1102
1103 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1104
1105 // Generate: if (loop-index != 0 fall to the loop body,
1106 // otherwise, go to the block after the for-loop.
1107 llvm::Value* zeroConstant =
1108 llvm::Constant::getNullValue(SizeLTy);
1109 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1110 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1111 "isne");
1112 // If the condition is true, execute the body.
1113 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1114
1115 EmitBlock(ForBody);
1116
1117 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1118 // Inside the loop body, emit the constructor call on the array element.
1119 Counter = Builder.CreateLoad(IndexPtr);
1120 Counter = Builder.CreateSub(Counter, One);
1121 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001122 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001123
1124 EmitBlock(ContinueBlock);
1125
1126 // Emit the decrement of the loop counter.
1127 Counter = Builder.CreateLoad(IndexPtr);
1128 Counter = Builder.CreateSub(Counter, One, "dec");
1129 Builder.CreateStore(Counter, IndexPtr);
1130
1131 // Finally, branch back up to the condition for the next iteration.
1132 EmitBranch(CondBlock);
1133
1134 // Emit the fall-through block.
1135 EmitBlock(AfterFor, true);
1136}
1137
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001138void
1139CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001140 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001141 llvm::Value *This,
1142 CallExpr::const_arg_iterator ArgBeg,
1143 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001144
1145 CGDebugInfo *DI = getDebugInfo();
1146 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
1147 // If debug info for this class has been emitted then this is the right time
1148 // to do so.
1149 const CXXRecordDecl *Parent = D->getParent();
1150 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1151 Parent->getLocation());
1152 }
1153
John McCall8b6bbeb2010-02-06 00:25:16 +00001154 if (D->isTrivial()) {
1155 if (ArgBeg == ArgEnd) {
1156 // Trivial default constructor, no codegen required.
1157 assert(D->isDefaultConstructor() &&
1158 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001159 return;
1160 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001161
1162 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1163 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1164
John McCall8b6bbeb2010-02-06 00:25:16 +00001165 const Expr *E = (*ArgBeg);
1166 QualType Ty = E->getType();
1167 llvm::Value *Src = EmitLValue(E).getAddress();
1168 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001169 return;
1170 }
1171
Anders Carlsson314e6222010-05-02 23:33:10 +00001172 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001173 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1174
Anders Carlssonc997d422010-01-02 01:01:18 +00001175 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001176}
1177
John McCallc0bf4622010-02-23 00:48:20 +00001178void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001179CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1180 llvm::Value *This, llvm::Value *Src,
1181 CallExpr::const_arg_iterator ArgBeg,
1182 CallExpr::const_arg_iterator ArgEnd) {
1183 if (D->isTrivial()) {
1184 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1185 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1186 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1187 return;
1188 }
1189 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1190 clang::Ctor_Complete);
1191 assert(D->isInstance() &&
1192 "Trying to emit a member call expr on a static method!");
1193
1194 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1195
1196 CallArgList Args;
1197
1198 // Push the this ptr.
1199 Args.push_back(std::make_pair(RValue::get(This),
1200 D->getThisType(getContext())));
1201
1202
1203 // Push the src ptr.
1204 QualType QT = *(FPT->arg_type_begin());
1205 const llvm::Type *t = CGM.getTypes().ConvertType(QT);
1206 Src = Builder.CreateBitCast(Src, t);
1207 Args.push_back(std::make_pair(RValue::get(Src), QT));
1208
1209 // Skip over first argument (Src).
1210 ++ArgBeg;
1211 CallExpr::const_arg_iterator Arg = ArgBeg;
1212 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1213 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1214 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001215 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001216 }
1217 // Either we've emitted all the call args, or we have a call to a
1218 // variadic function.
1219 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1220 "Extra arguments in non-variadic function!");
1221 // If we still have any arguments, emit them using the type of the argument.
1222 for (; Arg != ArgEnd; ++Arg) {
1223 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001224 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001225 }
1226
1227 QualType ResultType = FPT->getResultType();
1228 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args,
1229 FPT->getExtInfo()),
1230 Callee, ReturnValueSlot(), Args, D);
1231}
1232
1233void
John McCallc0bf4622010-02-23 00:48:20 +00001234CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1235 CXXCtorType CtorType,
1236 const FunctionArgList &Args) {
1237 CallArgList DelegateArgs;
1238
1239 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1240 assert(I != E && "no parameters to constructor");
1241
1242 // this
1243 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
John McCalld26bc762011-03-09 04:27:21 +00001244 (*I)->getType()));
John McCallc0bf4622010-02-23 00:48:20 +00001245 ++I;
1246
1247 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001248 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1249 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001250 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1251 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1252
Anders Carlssonaf440352010-03-23 04:11:45 +00001253 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001254 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001255 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001256 ++I;
1257 }
1258 }
1259
1260 // Explicit arguments.
1261 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001262 const VarDecl *param = *I;
1263 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001264 }
1265
1266 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1267 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1268 ReturnValueSlot(), DelegateArgs, Ctor);
1269}
1270
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001271void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1272 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001273 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001274 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001275 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1276 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001277 llvm::Value *Callee = 0;
1278 if (getContext().getLangOptions().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001279 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1280 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001281
1282 if (!Callee)
1283 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001284
Anders Carlssonc997d422010-01-02 01:01:18 +00001285 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001286}
1287
John McCall291ae942010-07-21 01:41:18 +00001288namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001289 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001290 const CXXDestructorDecl *Dtor;
1291 llvm::Value *Addr;
1292
1293 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1294 : Dtor(D), Addr(Addr) {}
1295
1296 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1297 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1298 /*ForVirtualBase=*/false, Addr);
1299 }
1300 };
1301}
1302
John McCall81407d42010-07-21 06:29:51 +00001303void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1304 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001305 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001306}
1307
John McCallf1549f62010-07-06 01:34:17 +00001308void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1309 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1310 if (!ClassDecl) return;
1311 if (ClassDecl->hasTrivialDestructor()) return;
1312
1313 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001314 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001315}
1316
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001317llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001318CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1319 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001320 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001321 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Anders Carlssonbba16072010-03-11 07:15:17 +00001322 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001323 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001324
1325 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001326 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001327 const llvm::Type *PtrDiffTy =
1328 ConvertType(getContext().getPointerDiffType());
1329
1330 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1331 PtrDiffTy->getPointerTo());
1332
1333 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1334
1335 return VBaseOffset;
1336}
1337
Anders Carlssond103f9f2010-03-28 19:40:00 +00001338void
1339CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001340 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001341 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001342 llvm::Constant *VTable,
1343 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001344 const CXXRecordDecl *RD = Base.getBase();
1345
Anders Carlssond103f9f2010-03-28 19:40:00 +00001346 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001347 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001348
Anders Carlssonc83f1062010-03-29 01:08:49 +00001349 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001350 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001351 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001352 // Get the secondary vpointer index.
1353 uint64_t VirtualPointerIndex =
1354 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1355
1356 /// Load the VTT.
1357 llvm::Value *VTT = LoadCXXVTT();
1358 if (VirtualPointerIndex)
1359 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1360
1361 // And load the address point from the VTT.
1362 VTableAddressPoint = Builder.CreateLoad(VTT);
1363 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001364 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001365 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001366 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001367 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001368
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001369 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001370 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001371 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001372
1373 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1374 // We need to use the virtual base offset offset because the virtual base
1375 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001376 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1377 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001378 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001379 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001380 // We can just use the base offset in the complete class.
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001381 NonVirtualOffset =
1382 CGM.getContext().toCharUnitsFromBits(Base.getBaseOffset());
Anders Carlsson3e79c302010-04-20 18:05:10 +00001383 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001384
1385 // Apply the offsets.
1386 llvm::Value *VTableField = LoadCXXThis();
1387
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001388 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001389 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1390 NonVirtualOffset,
1391 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001392
Anders Carlssond103f9f2010-03-28 19:40:00 +00001393 // Finally, store the address point.
1394 const llvm::Type *AddressPointPtrTy =
1395 VTableAddressPoint->getType()->getPointerTo();
1396 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1397 Builder.CreateStore(VTableAddressPoint, VTableField);
1398}
1399
Anders Carlsson603d6d12010-03-28 21:07:49 +00001400void
1401CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001402 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001403 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001404 bool BaseIsNonVirtualPrimaryBase,
1405 llvm::Constant *VTable,
1406 const CXXRecordDecl *VTableClass,
1407 VisitedVirtualBasesSetTy& VBases) {
1408 // If this base is a non-virtual primary base the address point has already
1409 // been set.
1410 if (!BaseIsNonVirtualPrimaryBase) {
1411 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001412 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1413 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001414 }
1415
1416 const CXXRecordDecl *RD = Base.getBase();
1417
1418 // Traverse bases.
1419 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1420 E = RD->bases_end(); I != E; ++I) {
1421 CXXRecordDecl *BaseDecl
1422 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1423
1424 // Ignore classes without a vtable.
1425 if (!BaseDecl->isDynamicClass())
1426 continue;
1427
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001428 CharUnits BaseOffset;
1429 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001430 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001431
1432 if (I->isVirtual()) {
1433 // Check if we've visited this virtual base before.
1434 if (!VBases.insert(BaseDecl))
1435 continue;
1436
1437 const ASTRecordLayout &Layout =
1438 getContext().getASTRecordLayout(VTableClass);
1439
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001440 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1441 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001442 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001443 } else {
1444 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1445
Anders Carlssona14f5972010-10-31 23:22:37 +00001446 BaseOffset =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001447 getContext().toCharUnitsFromBits(Base.getBaseOffset()) +
1448 Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001449 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001450 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001451 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001452 }
1453
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001454 InitializeVTablePointers(BaseSubobject(BaseDecl,
1455 getContext().toBits(BaseOffset)),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001456 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001457 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001458 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001459 VTable, VTableClass, VBases);
1460 }
1461}
1462
1463void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1464 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001465 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001466 return;
1467
Anders Carlsson07036902010-03-26 04:39:42 +00001468 // Get the VTable.
1469 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001470
Anders Carlsson603d6d12010-03-28 21:07:49 +00001471 // Initialize the vtable pointers for this class and all of its bases.
1472 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001473 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001474 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001475 /*BaseIsNonVirtualPrimaryBase=*/false,
1476 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001477}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001478
1479llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
1480 const llvm::Type *Ty) {
1481 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
1482 return Builder.CreateLoad(VTablePtrSrc, "vtable");
1483}