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