blob: 5bac172b0ee370861ebc5bc1da550d7763045077 [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
14#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000015#include "clang/AST/CXXInheritance.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000016#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000017#include "clang/AST/StmtCXX.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000018
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000019using namespace clang;
20using namespace CodeGen;
21
Anders Carlsson2f1986b2009-10-06 22:43:30 +000022static uint64_t
Anders Carlsson34a2d382010-04-24 21:06:20 +000023ComputeNonVirtualBaseClassOffset(ASTContext &Context,
24 const CXXRecordDecl *DerivedClass,
25 CXXBaseSpecifierArray::iterator Start,
26 CXXBaseSpecifierArray::iterator End) {
27 uint64_t Offset = 0;
28
29 const CXXRecordDecl *RD = DerivedClass;
30
31 for (CXXBaseSpecifierArray::iterator I = Start; I != End; ++I) {
32 const CXXBaseSpecifier *Base = *I;
33 assert(!Base->isVirtual() && "Should not see virtual bases here!");
34
35 // Get the layout.
36 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
37
38 const CXXRecordDecl *BaseDecl =
39 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
40
41 // Add the offset.
42 Offset += Layout.getBaseClassOffset(BaseDecl);
43
44 RD = BaseDecl;
45 }
46
47 // FIXME: We should not use / 8 here.
48 return Offset / 8;
49}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000050
Anders Carlsson84080ec2009-09-29 03:13:20 +000051llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000052CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
53 const CXXBaseSpecifierArray &BasePath) {
54 assert(!BasePath.empty() && "Base path should not be empty!");
55
56 uint64_t Offset =
57 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
58 BasePath.begin(), BasePath.end());
59 if (!Offset)
60 return 0;
61
62 const llvm::Type *PtrDiffTy =
63 Types.ConvertType(getContext().getPointerDiffType());
64
65 return llvm::ConstantInt::get(PtrDiffTy, Offset);
Anders Carlsson84080ec2009-09-29 03:13:20 +000066}
67
Anders Carlsson8561a862010-04-24 23:01:49 +000068/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000069/// This should only be used for (1) non-virtual bases or (2) virtual bases
70/// when the type is known to be complete (e.g. in complete destructors).
71///
72/// The object pointed to by 'This' is assumed to be non-null.
73llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000074CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
75 const CXXRecordDecl *Derived,
76 const CXXRecordDecl *Base,
77 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000078 // 'this' must be a pointer (in some address space) to Derived.
79 assert(This->getType()->isPointerTy() &&
80 cast<llvm::PointerType>(This->getType())->getElementType()
81 == ConvertType(Derived));
82
83 // Compute the offset of the virtual base.
84 uint64_t Offset;
85 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000086 if (BaseIsVirtual)
John McCallbff225e2010-02-16 04:15:37 +000087 Offset = Layout.getVBaseClassOffset(Base);
88 else
89 Offset = Layout.getBaseClassOffset(Base);
90
91 // Shift and cast down to the base type.
92 // TODO: for complete types, this should be possible with a GEP.
93 llvm::Value *V = This;
94 if (Offset) {
95 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext());
96 V = Builder.CreateBitCast(V, Int8PtrTy);
97 V = Builder.CreateConstInBoundsGEP1_64(V, Offset / 8);
98 }
99 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
100
101 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000102}
John McCallbff225e2010-02-16 04:15:37 +0000103
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000104static llvm::Value *
105ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
106 uint64_t NonVirtual, llvm::Value *Virtual) {
107 const llvm::Type *PtrDiffTy =
108 CGF.ConvertType(CGF.getContext().getPointerDiffType());
109
110 llvm::Value *NonVirtualOffset = 0;
111 if (NonVirtual)
112 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, NonVirtual);
113
114 llvm::Value *BaseOffset;
115 if (Virtual) {
116 if (NonVirtualOffset)
117 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
118 else
119 BaseOffset = Virtual;
120 } else
121 BaseOffset = NonVirtualOffset;
122
123 // Apply the base offset.
124 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext());
125 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy);
126 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
127
128 return ThisPtr;
129}
130
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000131llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000132CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000133 const CXXRecordDecl *Derived,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000134 const CXXBaseSpecifierArray &BasePath,
135 bool NullCheckValue) {
136 assert(!BasePath.empty() && "Base path should not be empty!");
137
138 CXXBaseSpecifierArray::iterator Start = BasePath.begin();
139 const CXXRecordDecl *VBase = 0;
140
141 // Get the virtual base.
142 if ((*Start)->isVirtual()) {
143 VBase =
144 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
145 ++Start;
146 }
147
148 uint64_t NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000149 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000150 Start, BasePath.end());
151
152 // Get the base pointer type.
153 const llvm::Type *BasePtrTy =
Anders Carlssonfc89c312010-04-24 21:12:55 +0000154 ConvertType((BasePath.end()[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000155
156 if (!NonVirtualOffset && !VBase) {
157 // Just cast back.
158 return Builder.CreateBitCast(Value, BasePtrTy);
159 }
160
161 llvm::BasicBlock *CastNull = 0;
162 llvm::BasicBlock *CastNotNull = 0;
163 llvm::BasicBlock *CastEnd = 0;
164
165 if (NullCheckValue) {
166 CastNull = createBasicBlock("cast.null");
167 CastNotNull = createBasicBlock("cast.notnull");
168 CastEnd = createBasicBlock("cast.end");
169
170 llvm::Value *IsNull =
171 Builder.CreateICmpEQ(Value,
172 llvm::Constant::getNullValue(Value->getType()));
173 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
174 EmitBlock(CastNotNull);
175 }
176
177 llvm::Value *VirtualOffset = 0;
178
179 if (VBase)
Anders Carlsson8561a862010-04-24 23:01:49 +0000180 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000181
182 // Apply the offsets.
183 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset,
184 VirtualOffset);
185
186 // Cast back.
187 Value = Builder.CreateBitCast(Value, BasePtrTy);
188
189 if (NullCheckValue) {
190 Builder.CreateBr(CastEnd);
191 EmitBlock(CastNull);
192 Builder.CreateBr(CastEnd);
193 EmitBlock(CastEnd);
194
195 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
196 PHI->reserveOperandSpace(2);
197 PHI->addIncoming(Value, CastNotNull);
198 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
199 CastNull);
200 Value = PHI;
201 }
202
203 return Value;
204}
205
206llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000207CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000208 const CXXRecordDecl *Derived,
Anders Carlssona04efdf2010-04-24 21:23:59 +0000209 const CXXBaseSpecifierArray &BasePath,
Anders Carlssona3697c92009-11-23 17:57:54 +0000210 bool NullCheckValue) {
Anders Carlssona04efdf2010-04-24 21:23:59 +0000211 assert(!BasePath.empty() && "Base path should not be empty!");
212
Anders Carlssona3697c92009-11-23 17:57:54 +0000213 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000214 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Anders Carlssona3697c92009-11-23 17:57:54 +0000215 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
216
Anders Carlssona552ea72010-01-31 01:43:37 +0000217 llvm::Value *NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000218 CGM.GetNonVirtualBaseClassOffset(Derived, BasePath);
Anders Carlssona552ea72010-01-31 01:43:37 +0000219
220 if (!NonVirtualOffset) {
221 // No offset, we can just cast back.
222 return Builder.CreateBitCast(Value, DerivedPtrTy);
223 }
224
Anders Carlssona3697c92009-11-23 17:57:54 +0000225 llvm::BasicBlock *CastNull = 0;
226 llvm::BasicBlock *CastNotNull = 0;
227 llvm::BasicBlock *CastEnd = 0;
228
229 if (NullCheckValue) {
230 CastNull = createBasicBlock("cast.null");
231 CastNotNull = createBasicBlock("cast.notnull");
232 CastEnd = createBasicBlock("cast.end");
233
234 llvm::Value *IsNull =
235 Builder.CreateICmpEQ(Value,
236 llvm::Constant::getNullValue(Value->getType()));
237 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
238 EmitBlock(CastNotNull);
239 }
240
Anders Carlssona552ea72010-01-31 01:43:37 +0000241 // Apply the offset.
242 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType());
243 Value = Builder.CreateSub(Value, NonVirtualOffset);
244 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy);
245
246 // Just cast.
247 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000248
249 if (NullCheckValue) {
250 Builder.CreateBr(CastEnd);
251 EmitBlock(CastNull);
252 Builder.CreateBr(CastEnd);
253 EmitBlock(CastEnd);
254
255 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType());
256 PHI->reserveOperandSpace(2);
257 PHI->addIncoming(Value, CastNotNull);
258 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
259 CastNull);
260 Value = PHI;
261 }
262
263 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000264}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000265
Anders Carlssonc997d422010-01-02 01:01:18 +0000266/// GetVTTParameter - Return the VTT parameter that should be passed to a
267/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000268static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
269 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000270 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000271 // This constructor/destructor does not need a VTT parameter.
272 return 0;
273 }
274
275 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
276 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000277
Anders Carlssonc997d422010-01-02 01:01:18 +0000278 llvm::Value *VTT;
279
John McCall3b477332010-02-18 19:59:28 +0000280 uint64_t SubVTTIndex;
281
282 // If the record matches the base, this is the complete ctor/dtor
283 // variant calling the base variant in a class with virtual bases.
284 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000285 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000286 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000287 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000288 SubVTTIndex = 0;
289 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000290 const ASTRecordLayout &Layout =
291 CGF.getContext().getASTRecordLayout(RD);
292 uint64_t BaseOffset = ForVirtualBase ?
293 Layout.getVBaseClassOffset(Base) : Layout.getBaseClassOffset(Base);
294
295 SubVTTIndex =
296 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000297 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
298 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000299
Anders Carlssonaf440352010-03-23 04:11:45 +0000300 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000301 // A VTT parameter was passed to the constructor, use it.
302 VTT = CGF.LoadCXXVTT();
303 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
304 } else {
305 // We're the complete constructor, so get the VTT by name.
Anders Carlssonaf440352010-03-23 04:11:45 +0000306 VTT = CGF.CGM.getVTables().getVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000307 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
308 }
309
310 return VTT;
311}
312
John McCall182ab512010-07-21 01:23:41 +0000313namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000314 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000315 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000316 const CXXRecordDecl *BaseClass;
317 bool BaseIsVirtual;
318 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
319 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000320
321 void Emit(CodeGenFunction &CGF, bool IsForEH) {
John McCall50da2ca2010-07-21 05:30:47 +0000322 const CXXRecordDecl *DerivedClass =
323 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
324
325 const CXXDestructorDecl *D = BaseClass->getDestructor();
326 llvm::Value *Addr =
327 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
328 DerivedClass, BaseClass,
329 BaseIsVirtual);
330 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000331 }
332 };
333}
334
Anders Carlsson607d0372009-12-24 22:46:43 +0000335static void EmitBaseInitializer(CodeGenFunction &CGF,
336 const CXXRecordDecl *ClassDecl,
337 CXXBaseOrMemberInitializer *BaseInit,
338 CXXCtorType CtorType) {
339 assert(BaseInit->isBaseInitializer() &&
340 "Must have base initializer!");
341
342 llvm::Value *ThisPtr = CGF.LoadCXXThis();
343
344 const Type *BaseType = BaseInit->getBaseClass();
345 CXXRecordDecl *BaseClassDecl =
346 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
347
Anders Carlsson80638c52010-04-12 00:51:03 +0000348 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000349
350 // The base constructor doesn't construct virtual bases.
351 if (CtorType == Ctor_Base && isBaseVirtual)
352 return;
353
John McCallbff225e2010-02-16 04:15:37 +0000354 // We can pretend to be a complete class because it only matters for
355 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000356 llvm::Value *V =
357 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000358 BaseClassDecl,
359 isBaseVirtual);
John McCallbff225e2010-02-16 04:15:37 +0000360
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000361 CGF.EmitAggExpr(BaseInit->getInit(), V, false, false, true);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000362
John McCall182ab512010-07-21 01:23:41 +0000363 if (CGF.Exceptions && !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000364 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
365 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000366}
367
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000368static void EmitAggMemberInitializer(CodeGenFunction &CGF,
369 LValue LHS,
370 llvm::Value *ArrayIndexVar,
371 CXXBaseOrMemberInitializer *MemberInit,
372 QualType T,
373 unsigned Index) {
374 if (Index == MemberInit->getNumArrayIndices()) {
John McCallf1549f62010-07-06 01:34:17 +0000375 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000376
377 llvm::Value *Dest = LHS.getAddress();
378 if (ArrayIndexVar) {
379 // If we have an array index variable, load it and use it as an offset.
380 // Then, increment the value.
381 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
382 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
383 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
384 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
385 CGF.Builder.CreateStore(Next, ArrayIndexVar);
386 }
387
388 CGF.EmitAggExpr(MemberInit->getInit(), Dest,
389 LHS.isVolatileQualified(),
390 /*IgnoreResult*/ false,
391 /*IsInitializer*/ true);
392
393 return;
394 }
395
396 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
397 assert(Array && "Array initialization without the array type?");
398 llvm::Value *IndexVar
399 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index));
400 assert(IndexVar && "Array index variable not loaded");
401
402 // Initialize this index variable to zero.
403 llvm::Value* Zero
404 = llvm::Constant::getNullValue(
405 CGF.ConvertType(CGF.getContext().getSizeType()));
406 CGF.Builder.CreateStore(Zero, IndexVar);
407
408 // Start the loop with a block that tests the condition.
409 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
410 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
411
412 CGF.EmitBlock(CondBlock);
413
414 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
415 // Generate: if (loop-index < number-of-elements) fall to the loop body,
416 // otherwise, go to the block after the for-loop.
417 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000418 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000419 llvm::Value *NumElementsPtr =
420 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000421 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
422 "isless");
423
424 // If the condition is true, execute the body.
425 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
426
427 CGF.EmitBlock(ForBody);
428 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
429
430 {
John McCallf1549f62010-07-06 01:34:17 +0000431 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000432
433 // Inside the loop body recurse to emit the inner loop or, eventually, the
434 // constructor call.
435 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit,
436 Array->getElementType(), Index + 1);
437 }
438
439 CGF.EmitBlock(ContinueBlock);
440
441 // Emit the increment of the loop counter.
442 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
443 Counter = CGF.Builder.CreateLoad(IndexVar);
444 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
445 CGF.Builder.CreateStore(NextVal, IndexVar);
446
447 // Finally, branch back up to the condition for the next iteration.
448 CGF.EmitBranch(CondBlock);
449
450 // Emit the fall-through block.
451 CGF.EmitBlock(AfterFor, true);
452}
John McCall182ab512010-07-21 01:23:41 +0000453
454namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000455 struct CallMemberDtor : EHScopeStack::Cleanup {
John McCall182ab512010-07-21 01:23:41 +0000456 FieldDecl *Field;
457 CXXDestructorDecl *Dtor;
458
459 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor)
460 : Field(Field), Dtor(Dtor) {}
461
462 void Emit(CodeGenFunction &CGF, bool IsForEH) {
463 // FIXME: Is this OK for C++0x delegating constructors?
464 llvm::Value *ThisPtr = CGF.LoadCXXThis();
465 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0);
466
467 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
468 LHS.getAddress());
469 }
470 };
471}
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000472
Anders Carlsson607d0372009-12-24 22:46:43 +0000473static void EmitMemberInitializer(CodeGenFunction &CGF,
474 const CXXRecordDecl *ClassDecl,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000475 CXXBaseOrMemberInitializer *MemberInit,
476 const CXXConstructorDecl *Constructor,
477 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000478 assert(MemberInit->isMemberInitializer() &&
479 "Must have member initializer!");
480
481 // non-static data member initializers.
482 FieldDecl *Field = MemberInit->getMember();
483 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType());
484
485 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000486 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000487
Anders Carlsson607d0372009-12-24 22:46:43 +0000488 // If we are initializing an anonymous union field, drill down to the field.
489 if (MemberInit->getAnonUnionMember()) {
490 Field = MemberInit->getAnonUnionMember();
John McCalla9976d32010-05-21 01:18:57 +0000491 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000492 FieldType = Field->getType();
John McCalla9976d32010-05-21 01:18:57 +0000493 } else {
494 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000495 }
496
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000497 // FIXME: If there's no initializer and the CXXBaseOrMemberInitializer
498 // was implicitly generated, we shouldn't be zeroing memory.
Anders Carlsson607d0372009-12-24 22:46:43 +0000499 RValue RHS;
500 if (FieldType->isReferenceType()) {
Anders Carlsson32f36ba2010-06-26 16:35:32 +0000501 RHS = CGF.EmitReferenceBindingToExpr(MemberInit->getInit(), Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000502 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Eli Friedman3bb94122010-01-31 19:07:50 +0000503 } else if (FieldType->isArrayType() && !MemberInit->getInit()) {
Anders Carlsson1884eb02010-05-22 17:35:42 +0000504 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType());
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000505 } else if (!CGF.hasAggregateLLVMType(Field->getType())) {
Eli Friedman0b292272010-06-03 19:58:07 +0000506 RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit()));
Anders Carlsson607d0372009-12-24 22:46:43 +0000507 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType);
Douglas Gregor9db7dbb2010-01-31 09:12:51 +0000508 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) {
509 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(),
Anders Carlsson607d0372009-12-24 22:46:43 +0000510 LHS.isVolatileQualified());
511 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000512 llvm::Value *ArrayIndexVar = 0;
513 const ConstantArrayType *Array
514 = CGF.getContext().getAsConstantArrayType(FieldType);
515 if (Array && Constructor->isImplicit() &&
516 Constructor->isCopyConstructor()) {
517 const llvm::Type *SizeTy
518 = CGF.ConvertType(CGF.getContext().getSizeType());
519
520 // The LHS is a pointer to the first object we'll be constructing, as
521 // a flat array.
522 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
523 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy);
524 BasePtr = llvm::PointerType::getUnqual(BasePtr);
525 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(),
526 BasePtr);
527 LHS = LValue::MakeAddr(BaseAddrPtr, CGF.MakeQualifiers(BaseElementTy));
528
529 // Create an array index that will be used to walk over all of the
530 // objects we're constructing.
531 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index");
532 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
533 CGF.Builder.CreateStore(Zero, ArrayIndexVar);
534
535 // If we are copying an array of scalars or classes with trivial copy
536 // constructors, perform a single aggregate copy.
537 const RecordType *Record = BaseElementTy->getAs<RecordType>();
538 if (!Record ||
539 cast<CXXRecordDecl>(Record->getDecl())->hasTrivialCopyConstructor()) {
540 // Find the source pointer. We knows it's the last argument because
541 // we know we're in a copy constructor.
542 unsigned SrcArgIndex = Args.size() - 1;
543 llvm::Value *SrcPtr
544 = CGF.Builder.CreateLoad(
545 CGF.GetAddrOfLocalVar(Args[SrcArgIndex].first));
546 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
547
548 // Copy the aggregate.
549 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
550 LHS.isVolatileQualified());
551 return;
552 }
553
554 // Emit the block variables for the array indices, if any.
555 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I)
556 CGF.EmitLocalBlockVarDecl(*MemberInit->getArrayIndex(I));
557 }
558
559 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000560
561 if (!CGF.Exceptions)
562 return;
563
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000564 // FIXME: If we have an array of classes w/ non-trivial destructors,
565 // we need to destroy in reverse order of construction along the exception
566 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000567 const RecordType *RT = FieldType->getAs<RecordType>();
568 if (!RT)
569 return;
570
571 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000572 if (!RD->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000573 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field,
574 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000575 }
576}
577
John McCallc0bf4622010-02-23 00:48:20 +0000578/// Checks whether the given constructor is a valid subject for the
579/// complete-to-base constructor delegation optimization, i.e.
580/// emitting the complete constructor as a simple call to the base
581/// constructor.
582static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
583
584 // Currently we disable the optimization for classes with virtual
585 // bases because (1) the addresses of parameter variables need to be
586 // consistent across all initializers but (2) the delegate function
587 // call necessarily creates a second copy of the parameter variable.
588 //
589 // The limiting example (purely theoretical AFAIK):
590 // struct A { A(int &c) { c++; } };
591 // struct B : virtual A {
592 // B(int count) : A(count) { printf("%d\n", count); }
593 // };
594 // ...although even this example could in principle be emitted as a
595 // delegation since the address of the parameter doesn't escape.
596 if (Ctor->getParent()->getNumVBases()) {
597 // TODO: white-list trivial vbase initializers. This case wouldn't
598 // be subject to the restrictions below.
599
600 // TODO: white-list cases where:
601 // - there are no non-reference parameters to the constructor
602 // - the initializers don't access any non-reference parameters
603 // - the initializers don't take the address of non-reference
604 // parameters
605 // - etc.
606 // If we ever add any of the above cases, remember that:
607 // - function-try-blocks will always blacklist this optimization
608 // - we need to perform the constructor prologue and cleanup in
609 // EmitConstructorBody.
610
611 return false;
612 }
613
614 // We also disable the optimization for variadic functions because
615 // it's impossible to "re-pass" varargs.
616 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
617 return false;
618
619 return true;
620}
621
John McCall9fc6a772010-02-19 09:25:03 +0000622/// EmitConstructorBody - Emits the body of the current constructor.
623void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
624 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
625 CXXCtorType CtorType = CurGD.getCtorType();
626
John McCallc0bf4622010-02-23 00:48:20 +0000627 // Before we go any further, try the complete->base constructor
628 // delegation optimization.
629 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
630 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
631 return;
632 }
633
John McCall9fc6a772010-02-19 09:25:03 +0000634 Stmt *Body = Ctor->getBody();
635
John McCallc0bf4622010-02-23 00:48:20 +0000636 // Enter the function-try-block before the constructor prologue if
637 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000638 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000639 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000640 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000641
John McCallf1549f62010-07-06 01:34:17 +0000642 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000643
John McCallc0bf4622010-02-23 00:48:20 +0000644 // Emit the constructor prologue, i.e. the base and member
645 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000646 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000647
648 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000649 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000650 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
651 else if (Body)
652 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000653
654 // Emit any cleanup blocks associated with the member or base
655 // initializers, which includes (along the exceptional path) the
656 // destructors for those members and bases that were fully
657 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000658 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000659
John McCallc0bf4622010-02-23 00:48:20 +0000660 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000661 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000662}
663
Anders Carlsson607d0372009-12-24 22:46:43 +0000664/// EmitCtorPrologue - This routine generates necessary code to initialize
665/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000666void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000667 CXXCtorType CtorType,
668 FunctionArgList &Args) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000669 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000670
671 llvm::SmallVector<CXXBaseOrMemberInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000672
Anders Carlsson607d0372009-12-24 22:46:43 +0000673 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
674 E = CD->init_end();
675 B != E; ++B) {
676 CXXBaseOrMemberInitializer *Member = (*B);
677
Anders Carlsson607d0372009-12-24 22:46:43 +0000678 if (Member->isBaseInitializer())
679 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
680 else
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000681 MemberInitializers.push_back(Member);
Anders Carlsson607d0372009-12-24 22:46:43 +0000682 }
683
Anders Carlsson603d6d12010-03-28 21:07:49 +0000684 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000685
John McCallf1549f62010-07-06 01:34:17 +0000686 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000687 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000688}
689
John McCall9fc6a772010-02-19 09:25:03 +0000690/// EmitDestructorBody - Emits the body of the current destructor.
691void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
692 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
693 CXXDtorType DtorType = CurGD.getDtorType();
694
John McCall50da2ca2010-07-21 05:30:47 +0000695 // The call to operator delete in a deleting destructor happens
696 // outside of the function-try-block, which means it's always
697 // possible to delegate the destructor body to the complete
698 // destructor. Do so.
699 if (DtorType == Dtor_Deleting) {
700 EnterDtorCleanups(Dtor, Dtor_Deleting);
701 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
702 LoadCXXThis());
703 PopCleanupBlock();
704 return;
705 }
706
John McCall9fc6a772010-02-19 09:25:03 +0000707 Stmt *Body = Dtor->getBody();
708
709 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000710 // anything else.
711 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000712 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000713 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000714
John McCall50da2ca2010-07-21 05:30:47 +0000715 // Enter the epilogue cleanups.
716 RunCleanupsScope DtorEpilogue(*this);
717
John McCall9fc6a772010-02-19 09:25:03 +0000718 // If this is the complete variant, just invoke the base variant;
719 // the epilogue will destruct the virtual bases. But we can't do
720 // this optimization if the body is a function-try-block, because
721 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000722 switch (DtorType) {
723 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
724
725 case Dtor_Complete:
726 // Enter the cleanup scopes for virtual bases.
727 EnterDtorCleanups(Dtor, Dtor_Complete);
728
729 if (!isTryBody) {
730 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
731 LoadCXXThis());
732 break;
733 }
734 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000735
John McCall50da2ca2010-07-21 05:30:47 +0000736 case Dtor_Base:
737 // Enter the cleanup scopes for fields and non-virtual bases.
738 EnterDtorCleanups(Dtor, Dtor_Base);
739
740 // Initialize the vtable pointers before entering the body.
Anders Carlsson603d6d12010-03-28 21:07:49 +0000741 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000742
743 if (isTryBody)
744 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
745 else if (Body)
746 EmitStmt(Body);
747 else {
748 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
749 // nothing to do besides what's in the epilogue
750 }
751 break;
John McCall9fc6a772010-02-19 09:25:03 +0000752 }
753
John McCall50da2ca2010-07-21 05:30:47 +0000754 // Jump out through the epilogue cleanups.
755 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000756
757 // Exit the try if applicable.
758 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000759 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000760}
761
John McCall50da2ca2010-07-21 05:30:47 +0000762namespace {
763 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000764 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000765 CallDtorDelete() {}
766
767 void Emit(CodeGenFunction &CGF, bool IsForEH) {
768 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
769 const CXXRecordDecl *ClassDecl = Dtor->getParent();
770 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
771 CGF.getContext().getTagDeclType(ClassDecl));
772 }
773 };
774
John McCall1f0fca52010-07-21 07:22:38 +0000775 struct CallArrayFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000776 const FieldDecl *Field;
777 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {}
778
779 void Emit(CodeGenFunction &CGF, bool IsForEH) {
780 QualType FieldType = Field->getType();
781 const ConstantArrayType *Array =
782 CGF.getContext().getAsConstantArrayType(FieldType);
783
784 QualType BaseType =
785 CGF.getContext().getBaseElementType(Array->getElementType());
786 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl();
787
788 llvm::Value *ThisPtr = CGF.LoadCXXThis();
789 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
790 // FIXME: Qualifiers?
791 /*CVRQualifiers=*/0);
792
793 const llvm::Type *BasePtr = CGF.ConvertType(BaseType)->getPointerTo();
794 llvm::Value *BaseAddrPtr =
795 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr);
796 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(),
797 Array, BaseAddrPtr);
798 }
799 };
800
John McCall1f0fca52010-07-21 07:22:38 +0000801 struct CallFieldDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000802 const FieldDecl *Field;
803 CallFieldDtor(const FieldDecl *Field) : Field(Field) {}
804
805 void Emit(CodeGenFunction &CGF, bool IsForEH) {
806 const CXXRecordDecl *FieldClassDecl =
807 Field->getType()->getAsCXXRecordDecl();
808
809 llvm::Value *ThisPtr = CGF.LoadCXXThis();
810 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field,
811 // FIXME: Qualifiers?
812 /*CVRQualifiers=*/0);
813
814 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(),
815 Dtor_Complete, /*ForVirtualBase=*/false,
816 LHS.getAddress());
817 }
818 };
819}
820
Anders Carlsson607d0372009-12-24 22:46:43 +0000821/// EmitDtorEpilogue - Emit all code that comes at the end of class's
822/// destructor. This is to call destructors on members and base classes
823/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000824void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
825 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000826 assert(!DD->isTrivial() &&
827 "Should not emit dtor epilogue for trivial dtor!");
828
John McCall50da2ca2010-07-21 05:30:47 +0000829 // The deleting-destructor phase just needs to call the appropriate
830 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000831 if (DtorType == Dtor_Deleting) {
832 assert(DD->getOperatorDelete() &&
833 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +0000834 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +0000835 return;
836 }
837
John McCall50da2ca2010-07-21 05:30:47 +0000838 const CXXRecordDecl *ClassDecl = DD->getParent();
839
840 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +0000841 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +0000842
843 // We push them in the forward order so that they'll be popped in
844 // the reverse order.
845 for (CXXRecordDecl::base_class_const_iterator I =
846 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +0000847 I != E; ++I) {
848 const CXXBaseSpecifier &Base = *I;
849 CXXRecordDecl *BaseClassDecl
850 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
851
852 // Ignore trivial destructors.
853 if (BaseClassDecl->hasTrivialDestructor())
854 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000855
John McCall1f0fca52010-07-21 07:22:38 +0000856 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
857 BaseClassDecl,
858 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +0000859 }
John McCall50da2ca2010-07-21 05:30:47 +0000860
John McCall3b477332010-02-18 19:59:28 +0000861 return;
862 }
863
864 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +0000865
866 // Destroy non-virtual bases.
867 for (CXXRecordDecl::base_class_const_iterator I =
868 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
869 const CXXBaseSpecifier &Base = *I;
870
871 // Ignore virtual bases.
872 if (Base.isVirtual())
873 continue;
874
875 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
876
877 // Ignore trivial destructors.
878 if (BaseClassDecl->hasTrivialDestructor())
879 continue;
John McCall3b477332010-02-18 19:59:28 +0000880
John McCall1f0fca52010-07-21 07:22:38 +0000881 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
882 BaseClassDecl,
883 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +0000884 }
885
886 // Destroy direct fields.
Anders Carlsson607d0372009-12-24 22:46:43 +0000887 llvm::SmallVector<const FieldDecl *, 16> FieldDecls;
888 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
889 E = ClassDecl->field_end(); I != E; ++I) {
890 const FieldDecl *Field = *I;
891
892 QualType FieldType = getContext().getCanonicalType(Field->getType());
John McCall50da2ca2010-07-21 05:30:47 +0000893 const ConstantArrayType *Array =
894 getContext().getAsConstantArrayType(FieldType);
895 if (Array)
896 FieldType = getContext().getBaseElementType(Array->getElementType());
Anders Carlsson607d0372009-12-24 22:46:43 +0000897
898 const RecordType *RT = FieldType->getAs<RecordType>();
899 if (!RT)
900 continue;
901
902 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
903 if (FieldClassDecl->hasTrivialDestructor())
904 continue;
John McCall50da2ca2010-07-21 05:30:47 +0000905
Anders Carlsson607d0372009-12-24 22:46:43 +0000906 if (Array)
John McCall1f0fca52010-07-21 07:22:38 +0000907 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field);
John McCall50da2ca2010-07-21 05:30:47 +0000908 else
John McCall1f0fca52010-07-21 07:22:38 +0000909 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field);
Anders Carlsson607d0372009-12-24 22:46:43 +0000910 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000911}
912
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000913/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested)
914/// for-loop to call the default constructor on individual members of the
915/// array.
916/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the
917/// array type and 'ArrayPtr' points to the beginning fo the array.
918/// It is assumed that all relevant checks have been made by the caller.
Douglas Gregor59174c02010-07-21 01:10:17 +0000919///
920/// \param ZeroInitialization True if each element should be zero-initialized
921/// before it is constructed.
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000922void
923CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
Douglas Gregor59174c02010-07-21 01:10:17 +0000924 const ConstantArrayType *ArrayTy,
925 llvm::Value *ArrayPtr,
926 CallExpr::const_arg_iterator ArgBeg,
927 CallExpr::const_arg_iterator ArgEnd,
928 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000929
930 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
931 llvm::Value * NumElements =
932 llvm::ConstantInt::get(SizeTy,
933 getContext().getConstantArrayElementCount(ArrayTy));
934
Douglas Gregor59174c02010-07-21 01:10:17 +0000935 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd,
936 ZeroInitialization);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000937}
938
939void
940CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D,
941 llvm::Value *NumElements,
942 llvm::Value *ArrayPtr,
943 CallExpr::const_arg_iterator ArgBeg,
Douglas Gregor59174c02010-07-21 01:10:17 +0000944 CallExpr::const_arg_iterator ArgEnd,
945 bool ZeroInitialization) {
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000946 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
947
948 // Create a temporary for the loop index and initialize it with 0.
949 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index");
950 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
951 Builder.CreateStore(Zero, IndexPtr);
952
953 // Start the loop with a block that tests the condition.
954 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
955 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
956
957 EmitBlock(CondBlock);
958
959 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
960
961 // Generate: if (loop-index < number-of-elements fall to the loop body,
962 // otherwise, go to the block after the for-loop.
963 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
964 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless");
965 // If the condition is true, execute the body.
966 Builder.CreateCondBr(IsLess, ForBody, AfterFor);
967
968 EmitBlock(ForBody);
969
970 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
971 // Inside the loop body, emit the constructor call on the array element.
972 Counter = Builder.CreateLoad(IndexPtr);
973 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter,
974 "arrayidx");
975
Douglas Gregor59174c02010-07-21 01:10:17 +0000976 // Zero initialize the storage, if requested.
977 if (ZeroInitialization)
978 EmitNullInitialization(Address,
979 getContext().getTypeDeclType(D->getParent()));
980
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000981 // C++ [class.temporary]p4:
982 // There are two contexts in which temporaries are destroyed at a different
983 // point than the end of the full-expression. The first context is when a
984 // default constructor is called to initialize an element of an array.
985 // If the constructor has one or more default arguments, the destruction of
986 // every temporary created in a default argument expression is sequenced
987 // before the construction of the next array element, if any.
988
989 // Keep track of the current number of live temporaries.
Anders Carlsson44ec82b2010-03-30 03:14:41 +0000990 {
John McCallf1549f62010-07-06 01:34:17 +0000991 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000992
Anders Carlsson155ed4a2010-05-02 23:20:53 +0000993 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address,
Anders Carlsson24eb78e2010-05-02 23:01:10 +0000994 ArgBeg, ArgEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +0000995 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000996
Anders Carlsson3b5ad222010-01-01 20:29:01 +0000997 EmitBlock(ContinueBlock);
998
999 // Emit the increment of the loop counter.
1000 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1);
1001 Counter = Builder.CreateLoad(IndexPtr);
1002 NextVal = Builder.CreateAdd(Counter, NextVal, "inc");
1003 Builder.CreateStore(NextVal, IndexPtr);
1004
1005 // Finally, branch back up to the condition for the next iteration.
1006 EmitBranch(CondBlock);
1007
1008 // Emit the fall-through block.
1009 EmitBlock(AfterFor, true);
1010}
1011
1012/// EmitCXXAggrDestructorCall - calls the default destructor on array
1013/// elements in reverse order of construction.
1014void
1015CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1016 const ArrayType *Array,
1017 llvm::Value *This) {
1018 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array);
1019 assert(CA && "Do we support VLA for destruction ?");
1020 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA);
1021
1022 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1023 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount);
1024 EmitCXXAggrDestructorCall(D, ElementCountPtr, This);
1025}
1026
1027/// EmitCXXAggrDestructorCall - calls the default destructor on array
1028/// elements in reverse order of construction.
1029void
1030CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D,
1031 llvm::Value *UpperCount,
1032 llvm::Value *This) {
1033 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType());
1034 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1);
1035
1036 // Create a temporary for the loop index and initialize it with count of
1037 // array elements.
1038 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index");
1039
1040 // Store the number of elements in the index pointer.
1041 Builder.CreateStore(UpperCount, IndexPtr);
1042
1043 // Start the loop with a block that tests the condition.
1044 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond");
1045 llvm::BasicBlock *AfterFor = createBasicBlock("for.end");
1046
1047 EmitBlock(CondBlock);
1048
1049 llvm::BasicBlock *ForBody = createBasicBlock("for.body");
1050
1051 // Generate: if (loop-index != 0 fall to the loop body,
1052 // otherwise, go to the block after the for-loop.
1053 llvm::Value* zeroConstant =
1054 llvm::Constant::getNullValue(SizeLTy);
1055 llvm::Value *Counter = Builder.CreateLoad(IndexPtr);
1056 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant,
1057 "isne");
1058 // If the condition is true, execute the body.
1059 Builder.CreateCondBr(IsNE, ForBody, AfterFor);
1060
1061 EmitBlock(ForBody);
1062
1063 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc");
1064 // Inside the loop body, emit the constructor call on the array element.
1065 Counter = Builder.CreateLoad(IndexPtr);
1066 Counter = Builder.CreateSub(Counter, One);
1067 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx");
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001068 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001069
1070 EmitBlock(ContinueBlock);
1071
1072 // Emit the decrement of the loop counter.
1073 Counter = Builder.CreateLoad(IndexPtr);
1074 Counter = Builder.CreateSub(Counter, One, "dec");
1075 Builder.CreateStore(Counter, IndexPtr);
1076
1077 // Finally, branch back up to the condition for the next iteration.
1078 EmitBranch(CondBlock);
1079
1080 // Emit the fall-through block.
1081 EmitBlock(AfterFor, true);
1082}
1083
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001084void
1085CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001086 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001087 llvm::Value *This,
1088 CallExpr::const_arg_iterator ArgBeg,
1089 CallExpr::const_arg_iterator ArgEnd) {
John McCall8b6bbeb2010-02-06 00:25:16 +00001090 if (D->isTrivial()) {
1091 if (ArgBeg == ArgEnd) {
1092 // Trivial default constructor, no codegen required.
1093 assert(D->isDefaultConstructor() &&
1094 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001095 return;
1096 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001097
1098 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
1099 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor");
1100
John McCall8b6bbeb2010-02-06 00:25:16 +00001101 const Expr *E = (*ArgBeg);
1102 QualType Ty = E->getType();
1103 llvm::Value *Src = EmitLValue(E).getAddress();
1104 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001105 return;
1106 }
1107
Anders Carlsson314e6222010-05-02 23:33:10 +00001108 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001109 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1110
Anders Carlssonc997d422010-01-02 01:01:18 +00001111 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001112}
1113
John McCallc0bf4622010-02-23 00:48:20 +00001114void
1115CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1116 CXXCtorType CtorType,
1117 const FunctionArgList &Args) {
1118 CallArgList DelegateArgs;
1119
1120 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1121 assert(I != E && "no parameters to constructor");
1122
1123 // this
1124 DelegateArgs.push_back(std::make_pair(RValue::get(LoadCXXThis()),
1125 I->second));
1126 ++I;
1127
1128 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001129 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1130 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001131 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
1132 DelegateArgs.push_back(std::make_pair(RValue::get(VTT), VoidPP));
1133
Anders Carlssonaf440352010-03-23 04:11:45 +00001134 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001135 assert(I != E && "cannot skip vtt parameter, already done with args");
1136 assert(I->second == VoidPP && "skipping parameter not of vtt type");
1137 ++I;
1138 }
1139 }
1140
1141 // Explicit arguments.
1142 for (; I != E; ++I) {
John McCallc0bf4622010-02-23 00:48:20 +00001143 const VarDecl *Param = I->first;
1144 QualType ArgType = Param->getType(); // because we're passing it to itself
John McCall27360712010-05-26 22:34:26 +00001145 RValue Arg = EmitDelegateCallArg(Param);
John McCallc0bf4622010-02-23 00:48:20 +00001146
1147 DelegateArgs.push_back(std::make_pair(Arg, ArgType));
1148 }
1149
1150 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType),
1151 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1152 ReturnValueSlot(), DelegateArgs, Ctor);
1153}
1154
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001155void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1156 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001157 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001158 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001159 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1160 ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001161 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
1162
Anders Carlssonc997d422010-01-02 01:01:18 +00001163 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001164}
1165
John McCall291ae942010-07-21 01:41:18 +00001166namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001167 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001168 const CXXDestructorDecl *Dtor;
1169 llvm::Value *Addr;
1170
1171 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1172 : Dtor(D), Addr(Addr) {}
1173
1174 void Emit(CodeGenFunction &CGF, bool IsForEH) {
1175 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1176 /*ForVirtualBase=*/false, Addr);
1177 }
1178 };
1179}
1180
John McCall81407d42010-07-21 06:29:51 +00001181void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1182 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001183 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001184}
1185
John McCallf1549f62010-07-06 01:34:17 +00001186void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1187 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1188 if (!ClassDecl) return;
1189 if (ClassDecl->hasTrivialDestructor()) return;
1190
1191 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall81407d42010-07-21 06:29:51 +00001192 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001193}
1194
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001195llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001196CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1197 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001198 const CXXRecordDecl *BaseClassDecl) {
1199 const llvm::Type *Int8PtrTy =
1200 llvm::Type::getInt8Ty(VMContext)->getPointerTo();
1201
1202 llvm::Value *VTablePtr = Builder.CreateBitCast(This,
1203 Int8PtrTy->getPointerTo());
1204 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable");
1205
Anders Carlssonbba16072010-03-11 07:15:17 +00001206 int64_t VBaseOffsetOffset =
Anders Carlssonaf440352010-03-23 04:11:45 +00001207 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001208
1209 llvm::Value *VBaseOffsetPtr =
Anders Carlssonbba16072010-03-11 07:15:17 +00001210 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset, "vbase.offset.ptr");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001211 const llvm::Type *PtrDiffTy =
1212 ConvertType(getContext().getPointerDiffType());
1213
1214 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1215 PtrDiffTy->getPointerTo());
1216
1217 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1218
1219 return VBaseOffset;
1220}
1221
Anders Carlssond103f9f2010-03-28 19:40:00 +00001222void
1223CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001224 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001225 uint64_t OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001226 llvm::Constant *VTable,
1227 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001228 const CXXRecordDecl *RD = Base.getBase();
1229
Anders Carlssond103f9f2010-03-28 19:40:00 +00001230 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001231 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001232
Anders Carlssonc83f1062010-03-29 01:08:49 +00001233 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001234 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001235 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001236 // Get the secondary vpointer index.
1237 uint64_t VirtualPointerIndex =
1238 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1239
1240 /// Load the VTT.
1241 llvm::Value *VTT = LoadCXXVTT();
1242 if (VirtualPointerIndex)
1243 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1244
1245 // And load the address point from the VTT.
1246 VTableAddressPoint = Builder.CreateLoad(VTT);
1247 } else {
Anders Carlsson64c9eca2010-03-29 02:08:26 +00001248 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001249 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001250 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001251 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001252
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001253 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001254 llvm::Value *VirtualOffset = 0;
1255 uint64_t NonVirtualOffset = 0;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001256
1257 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1258 // We need to use the virtual base offset offset because the virtual base
1259 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001260 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1261 NearestVBase);
1262 NonVirtualOffset = OffsetFromNearestVBase / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001263 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001264 // We can just use the base offset in the complete class.
1265 NonVirtualOffset = Base.getBaseOffset() / 8;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001266 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001267
1268 // Apply the offsets.
1269 llvm::Value *VTableField = LoadCXXThis();
1270
1271 if (NonVirtualOffset || VirtualOffset)
1272 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1273 NonVirtualOffset,
1274 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001275
Anders Carlssond103f9f2010-03-28 19:40:00 +00001276 // Finally, store the address point.
1277 const llvm::Type *AddressPointPtrTy =
1278 VTableAddressPoint->getType()->getPointerTo();
1279 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
1280 Builder.CreateStore(VTableAddressPoint, VTableField);
1281}
1282
Anders Carlsson603d6d12010-03-28 21:07:49 +00001283void
1284CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001285 const CXXRecordDecl *NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001286 uint64_t OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001287 bool BaseIsNonVirtualPrimaryBase,
1288 llvm::Constant *VTable,
1289 const CXXRecordDecl *VTableClass,
1290 VisitedVirtualBasesSetTy& VBases) {
1291 // If this base is a non-virtual primary base the address point has already
1292 // been set.
1293 if (!BaseIsNonVirtualPrimaryBase) {
1294 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001295 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1296 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001297 }
1298
1299 const CXXRecordDecl *RD = Base.getBase();
1300
1301 // Traverse bases.
1302 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1303 E = RD->bases_end(); I != E; ++I) {
1304 CXXRecordDecl *BaseDecl
1305 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1306
1307 // Ignore classes without a vtable.
1308 if (!BaseDecl->isDynamicClass())
1309 continue;
1310
1311 uint64_t BaseOffset;
Anders Carlsson42358402010-05-03 00:07:07 +00001312 uint64_t BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001313 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001314
1315 if (I->isVirtual()) {
1316 // Check if we've visited this virtual base before.
1317 if (!VBases.insert(BaseDecl))
1318 continue;
1319
1320 const ASTRecordLayout &Layout =
1321 getContext().getASTRecordLayout(VTableClass);
1322
Anders Carlsson603d6d12010-03-28 21:07:49 +00001323 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001324 BaseOffsetFromNearestVBase = 0;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001325 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001326 } else {
1327 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1328
1329 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001330 BaseOffsetFromNearestVBase =
Anders Carlsson8246cc72010-05-03 00:29:58 +00001331 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001332 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001333 }
1334
1335 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001336 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001337 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001338 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001339 VTable, VTableClass, VBases);
1340 }
1341}
1342
1343void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1344 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001345 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001346 return;
1347
Anders Carlsson07036902010-03-26 04:39:42 +00001348 // Get the VTable.
1349 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001350
Anders Carlsson603d6d12010-03-28 21:07:49 +00001351 // Initialize the vtable pointers for this class and all of its bases.
1352 VisitedVirtualBasesSetTy VBases;
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001353 InitializeVTablePointers(BaseSubobject(RD, 0), /*NearestVBase=*/0,
Anders Carlsson42358402010-05-03 00:07:07 +00001354 /*OffsetFromNearestVBase=*/0,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001355 /*BaseIsNonVirtualPrimaryBase=*/false,
1356 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001357}