blob: b452c1b7ab43c14e22531c62672d2bfb26e10cb8 [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
Eli Friedman64bee652012-02-25 02:48:22 +000014#include "CGBlocks.h"
Devang Pateld67ef0e2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000016#include "CodeGenFunction.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000017#include "clang/AST/CXXInheritance.h"
John McCall7e1dff72010-09-17 02:31:44 +000018#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000019#include "clang/AST/RecordLayout.h"
John McCall9fc6a772010-02-19 09:25:03 +000020#include "clang/AST/StmtCXX.h"
Devang Patel3ee36af2011-02-22 20:55:26 +000021#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson2f1986b2009-10-06 22:43:30 +000022
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000023using namespace clang;
24using namespace CodeGen;
25
Ken Dyck55c02582011-03-22 00:53:26 +000026static CharUnits
Anders Carlsson34a2d382010-04-24 21:06:20 +000027ComputeNonVirtualBaseClassOffset(ASTContext &Context,
28 const CXXRecordDecl *DerivedClass,
John McCallf871d0c2010-08-07 06:22:56 +000029 CastExpr::path_const_iterator Start,
30 CastExpr::path_const_iterator End) {
Ken Dyck55c02582011-03-22 00:53:26 +000031 CharUnits Offset = CharUnits::Zero();
Anders Carlsson34a2d382010-04-24 21:06:20 +000032
33 const CXXRecordDecl *RD = DerivedClass;
34
John McCallf871d0c2010-08-07 06:22:56 +000035 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlsson34a2d382010-04-24 21:06:20 +000036 const CXXBaseSpecifier *Base = *I;
37 assert(!Base->isVirtual() && "Should not see virtual bases here!");
38
39 // Get the layout.
40 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
41
42 const CXXRecordDecl *BaseDecl =
43 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
44
45 // Add the offset.
Ken Dyck55c02582011-03-22 00:53:26 +000046 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson34a2d382010-04-24 21:06:20 +000047
48 RD = BaseDecl;
49 }
50
Ken Dyck55c02582011-03-22 00:53:26 +000051 return Offset;
Anders Carlsson34a2d382010-04-24 21:06:20 +000052}
Anders Carlsson5d58a1d2009-09-12 04:27:24 +000053
Anders Carlsson84080ec2009-09-29 03:13:20 +000054llvm::Constant *
Anders Carlssona04efdf2010-04-24 21:23:59 +000055CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +000056 CastExpr::path_const_iterator PathBegin,
57 CastExpr::path_const_iterator PathEnd) {
58 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +000059
Ken Dyck55c02582011-03-22 00:53:26 +000060 CharUnits Offset =
John McCallf871d0c2010-08-07 06:22:56 +000061 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
62 PathBegin, PathEnd);
Ken Dyck55c02582011-03-22 00:53:26 +000063 if (Offset.isZero())
Anders Carlssona04efdf2010-04-24 21:23:59 +000064 return 0;
65
Chris Lattner2acc6e32011-07-18 04:24:23 +000066 llvm::Type *PtrDiffTy =
Anders Carlssona04efdf2010-04-24 21:23:59 +000067 Types.ConvertType(getContext().getPointerDiffType());
68
Ken Dyck55c02582011-03-22 00:53:26 +000069 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson84080ec2009-09-29 03:13:20 +000070}
71
Anders Carlsson8561a862010-04-24 23:01:49 +000072/// Gets the address of a direct base class within a complete object.
John McCallbff225e2010-02-16 04:15:37 +000073/// This should only be used for (1) non-virtual bases or (2) virtual bases
74/// when the type is known to be complete (e.g. in complete destructors).
75///
76/// The object pointed to by 'This' is assumed to be non-null.
77llvm::Value *
Anders Carlsson8561a862010-04-24 23:01:49 +000078CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
79 const CXXRecordDecl *Derived,
80 const CXXRecordDecl *Base,
81 bool BaseIsVirtual) {
John McCallbff225e2010-02-16 04:15:37 +000082 // 'this' must be a pointer (in some address space) to Derived.
83 assert(This->getType()->isPointerTy() &&
84 cast<llvm::PointerType>(This->getType())->getElementType()
85 == ConvertType(Derived));
86
87 // Compute the offset of the virtual base.
Ken Dyck5fff46b2011-03-22 01:21:15 +000088 CharUnits Offset;
John McCallbff225e2010-02-16 04:15:37 +000089 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlsson8561a862010-04-24 23:01:49 +000090 if (BaseIsVirtual)
Ken Dyck5fff46b2011-03-22 01:21:15 +000091 Offset = Layout.getVBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000092 else
Ken Dyck5fff46b2011-03-22 01:21:15 +000093 Offset = Layout.getBaseClassOffset(Base);
John McCallbff225e2010-02-16 04:15:37 +000094
95 // Shift and cast down to the base type.
96 // TODO: for complete types, this should be possible with a GEP.
97 llvm::Value *V = This;
Ken Dyck5fff46b2011-03-22 01:21:15 +000098 if (Offset.isPositive()) {
John McCallbff225e2010-02-16 04:15:37 +000099 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck5fff46b2011-03-22 01:21:15 +0000100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCallbff225e2010-02-16 04:15:37 +0000101 }
102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
103
104 return V;
Anders Carlssond103f9f2010-03-28 19:40:00 +0000105}
John McCallbff225e2010-02-16 04:15:37 +0000106
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000107static llvm::Value *
108ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000109 CharUnits NonVirtual, llvm::Value *Virtual) {
Chris Lattner2acc6e32011-07-18 04:24:23 +0000110 llvm::Type *PtrDiffTy =
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000111 CGF.ConvertType(CGF.getContext().getPointerDiffType());
112
113 llvm::Value *NonVirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000114 if (!NonVirtual.isZero())
115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy,
116 NonVirtual.getQuantity());
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000117
118 llvm::Value *BaseOffset;
119 if (Virtual) {
120 if (NonVirtualOffset)
121 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset);
122 else
123 BaseOffset = Virtual;
124 } else
125 BaseOffset = NonVirtualOffset;
126
127 // Apply the base offset.
Chris Lattner8b418682012-02-07 00:39:47 +0000128 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, CGF.Int8PtrTy);
Anders Carlsson9dc228a2010-04-20 16:03:35 +0000129 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr");
130
131 return ThisPtr;
132}
133
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000134llvm::Value *
Anders Carlsson34a2d382010-04-24 21:06:20 +0000135CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000136 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000137 CastExpr::path_const_iterator PathBegin,
138 CastExpr::path_const_iterator PathEnd,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000139 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000140 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson34a2d382010-04-24 21:06:20 +0000141
John McCallf871d0c2010-08-07 06:22:56 +0000142 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlsson34a2d382010-04-24 21:06:20 +0000143 const CXXRecordDecl *VBase = 0;
144
145 // Get the virtual base.
146 if ((*Start)->isVirtual()) {
147 VBase =
148 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
149 ++Start;
150 }
151
Ken Dyck55c02582011-03-22 00:53:26 +0000152 CharUnits NonVirtualOffset =
Anders Carlsson8561a862010-04-24 23:01:49 +0000153 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000154 Start, PathEnd);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000155
156 // Get the base pointer type.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000157 llvm::Type *BasePtrTy =
John McCallf871d0c2010-08-07 06:22:56 +0000158 ConvertType((PathEnd[-1])->getType())->getPointerTo();
Anders Carlsson34a2d382010-04-24 21:06:20 +0000159
Ken Dyck55c02582011-03-22 00:53:26 +0000160 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlsson34a2d382010-04-24 21:06:20 +0000161 // Just cast back.
162 return Builder.CreateBitCast(Value, BasePtrTy);
163 }
164
165 llvm::BasicBlock *CastNull = 0;
166 llvm::BasicBlock *CastNotNull = 0;
167 llvm::BasicBlock *CastEnd = 0;
168
169 if (NullCheckValue) {
170 CastNull = createBasicBlock("cast.null");
171 CastNotNull = createBasicBlock("cast.notnull");
172 CastEnd = createBasicBlock("cast.end");
173
Anders Carlssonb9241242011-04-11 00:30:07 +0000174 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000175 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
176 EmitBlock(CastNotNull);
177 }
178
179 llvm::Value *VirtualOffset = 0;
180
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000181 if (VBase) {
182 if (Derived->hasAttr<FinalAttr>()) {
183 VirtualOffset = 0;
184
185 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
186
Ken Dyck55c02582011-03-22 00:53:26 +0000187 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase);
188 NonVirtualOffset += VBaseOffset;
Anders Carlsson336a7dc2011-01-29 03:18:56 +0000189 } else
190 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase);
191 }
Anders Carlsson34a2d382010-04-24 21:06:20 +0000192
193 // Apply the offsets.
Ken Dyck55c02582011-03-22 00:53:26 +0000194 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyck9a8ad9b2011-03-23 00:45:26 +0000195 NonVirtualOffset,
Anders Carlsson34a2d382010-04-24 21:06:20 +0000196 VirtualOffset);
197
198 // Cast back.
199 Value = Builder.CreateBitCast(Value, BasePtrTy);
200
201 if (NullCheckValue) {
202 Builder.CreateBr(CastEnd);
203 EmitBlock(CastNull);
204 Builder.CreateBr(CastEnd);
205 EmitBlock(CastEnd);
206
Jay Foadbbf3bac2011-03-30 11:28:58 +0000207 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson34a2d382010-04-24 21:06:20 +0000208 PHI->addIncoming(Value, CastNotNull);
209 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
210 CastNull);
211 Value = PHI;
212 }
213
214 return Value;
215}
216
217llvm::Value *
Anders Carlssona3697c92009-11-23 17:57:54 +0000218CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlsson8561a862010-04-24 23:01:49 +0000219 const CXXRecordDecl *Derived,
John McCallf871d0c2010-08-07 06:22:56 +0000220 CastExpr::path_const_iterator PathBegin,
221 CastExpr::path_const_iterator PathEnd,
Anders Carlssona3697c92009-11-23 17:57:54 +0000222 bool NullCheckValue) {
John McCallf871d0c2010-08-07 06:22:56 +0000223 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssona04efdf2010-04-24 21:23:59 +0000224
Anders Carlssona3697c92009-11-23 17:57:54 +0000225 QualType DerivedTy =
Anders Carlsson8561a862010-04-24 23:01:49 +0000226 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2acc6e32011-07-18 04:24:23 +0000227 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Anders Carlssona3697c92009-11-23 17:57:54 +0000228
Anders Carlssona552ea72010-01-31 01:43:37 +0000229 llvm::Value *NonVirtualOffset =
John McCallf871d0c2010-08-07 06:22:56 +0000230 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlssona552ea72010-01-31 01:43:37 +0000231
232 if (!NonVirtualOffset) {
233 // No offset, we can just cast back.
234 return Builder.CreateBitCast(Value, DerivedPtrTy);
235 }
236
Anders Carlssona3697c92009-11-23 17:57:54 +0000237 llvm::BasicBlock *CastNull = 0;
238 llvm::BasicBlock *CastNotNull = 0;
239 llvm::BasicBlock *CastEnd = 0;
240
241 if (NullCheckValue) {
242 CastNull = createBasicBlock("cast.null");
243 CastNotNull = createBasicBlock("cast.notnull");
244 CastEnd = createBasicBlock("cast.end");
245
Anders Carlssonb9241242011-04-11 00:30:07 +0000246 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlssona3697c92009-11-23 17:57:54 +0000247 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
248 EmitBlock(CastNotNull);
249 }
250
Anders Carlssona552ea72010-01-31 01:43:37 +0000251 // Apply the offset.
Eli Friedmanc5685432012-02-28 22:07:56 +0000252 Value = Builder.CreateBitCast(Value, Int8PtrTy);
253 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
254 "sub.ptr");
Anders Carlssona552ea72010-01-31 01:43:37 +0000255
256 // Just cast.
257 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlssona3697c92009-11-23 17:57:54 +0000258
259 if (NullCheckValue) {
260 Builder.CreateBr(CastEnd);
261 EmitBlock(CastNull);
262 Builder.CreateBr(CastEnd);
263 EmitBlock(CastEnd);
264
Jay Foadbbf3bac2011-03-30 11:28:58 +0000265 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlssona3697c92009-11-23 17:57:54 +0000266 PHI->addIncoming(Value, CastNotNull);
267 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
268 CastNull);
269 Value = PHI;
270 }
271
272 return Value;
Anders Carlsson5d58a1d2009-09-12 04:27:24 +0000273}
Anders Carlsson21c9ad92010-03-30 03:27:09 +0000274
Anders Carlssonc997d422010-01-02 01:01:18 +0000275/// GetVTTParameter - Return the VTT parameter that should be passed to a
276/// base constructor/destructor with virtual bases.
Anders Carlsson314e6222010-05-02 23:33:10 +0000277static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD,
278 bool ForVirtualBase) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000279 if (!CodeGenVTables::needsVTTParameter(GD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000280 // This constructor/destructor does not need a VTT parameter.
281 return 0;
282 }
283
284 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent();
285 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall3b477332010-02-18 19:59:28 +0000286
Anders Carlssonc997d422010-01-02 01:01:18 +0000287 llvm::Value *VTT;
288
John McCall3b477332010-02-18 19:59:28 +0000289 uint64_t SubVTTIndex;
290
291 // If the record matches the base, this is the complete ctor/dtor
292 // variant calling the base variant in a class with virtual bases.
293 if (RD == Base) {
Anders Carlssonaf440352010-03-23 04:11:45 +0000294 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) &&
John McCall3b477332010-02-18 19:59:28 +0000295 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson314e6222010-05-02 23:33:10 +0000296 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall3b477332010-02-18 19:59:28 +0000297 SubVTTIndex = 0;
298 } else {
Anders Carlssonc11bb212010-05-02 23:53:25 +0000299 const ASTRecordLayout &Layout =
300 CGF.getContext().getASTRecordLayout(RD);
Ken Dyck4230d522011-03-24 01:21:01 +0000301 CharUnits BaseOffset = ForVirtualBase ?
302 Layout.getVBaseClassOffset(Base) :
303 Layout.getBaseClassOffset(Base);
Anders Carlssonc11bb212010-05-02 23:53:25 +0000304
305 SubVTTIndex =
306 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall3b477332010-02-18 19:59:28 +0000307 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
308 }
Anders Carlssonc997d422010-01-02 01:01:18 +0000309
Anders Carlssonaf440352010-03-23 04:11:45 +0000310 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) {
Anders Carlssonc997d422010-01-02 01:01:18 +0000311 // A VTT parameter was passed to the constructor, use it.
312 VTT = CGF.LoadCXXVTT();
313 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
314 } else {
315 // We're the complete constructor, so get the VTT by name.
Anders Carlsson1cbce122011-01-29 19:16:51 +0000316 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD);
Anders Carlssonc997d422010-01-02 01:01:18 +0000317 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
318 }
319
320 return VTT;
321}
322
John McCall182ab512010-07-21 01:23:41 +0000323namespace {
John McCall50da2ca2010-07-21 05:30:47 +0000324 /// Call the destructor for a direct base class.
John McCall1f0fca52010-07-21 07:22:38 +0000325 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000326 const CXXRecordDecl *BaseClass;
327 bool BaseIsVirtual;
328 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
329 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall182ab512010-07-21 01:23:41 +0000330
John McCallad346f42011-07-12 20:27:29 +0000331 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000332 const CXXRecordDecl *DerivedClass =
333 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
334
335 const CXXDestructorDecl *D = BaseClass->getDestructor();
336 llvm::Value *Addr =
337 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
338 DerivedClass, BaseClass,
339 BaseIsVirtual);
340 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr);
John McCall182ab512010-07-21 01:23:41 +0000341 }
342 };
John McCall7e1dff72010-09-17 02:31:44 +0000343
344 /// A visitor which checks whether an initializer uses 'this' in a
345 /// way which requires the vtable to be properly set.
346 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
347 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
348
349 bool UsesThis;
350
351 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
352
353 // Black-list all explicit and implicit references to 'this'.
354 //
355 // Do we need to worry about external references to 'this' derived
356 // from arbitrary code? If so, then anything which runs arbitrary
357 // external code might potentially access the vtable.
358 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
359 };
360}
361
362static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
363 DynamicThisUseChecker Checker(C);
364 Checker.Visit(const_cast<Expr*>(Init));
365 return Checker.UsesThis;
John McCall182ab512010-07-21 01:23:41 +0000366}
367
Anders Carlsson607d0372009-12-24 22:46:43 +0000368static void EmitBaseInitializer(CodeGenFunction &CGF,
369 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000370 CXXCtorInitializer *BaseInit,
Anders Carlsson607d0372009-12-24 22:46:43 +0000371 CXXCtorType CtorType) {
372 assert(BaseInit->isBaseInitializer() &&
373 "Must have base initializer!");
374
375 llvm::Value *ThisPtr = CGF.LoadCXXThis();
376
377 const Type *BaseType = BaseInit->getBaseClass();
378 CXXRecordDecl *BaseClassDecl =
379 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
380
Anders Carlsson80638c52010-04-12 00:51:03 +0000381 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlsson607d0372009-12-24 22:46:43 +0000382
383 // The base constructor doesn't construct virtual bases.
384 if (CtorType == Ctor_Base && isBaseVirtual)
385 return;
386
John McCall7e1dff72010-09-17 02:31:44 +0000387 // If the initializer for the base (other than the constructor
388 // itself) accesses 'this' in any way, we need to initialize the
389 // vtables.
390 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
391 CGF.InitializeVTablePointers(ClassDecl);
392
John McCallbff225e2010-02-16 04:15:37 +0000393 // We can pretend to be a complete class because it only matters for
394 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlsson8561a862010-04-24 23:01:49 +0000395 llvm::Value *V =
396 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCall50da2ca2010-07-21 05:30:47 +0000397 BaseClassDecl,
398 isBaseVirtual);
Eli Friedmand7722d92011-12-03 02:13:40 +0000399 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall7c2349b2011-08-25 20:40:09 +0000400 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +0000401 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +0000402 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +0000403 AggValueSlot::DoesNotNeedGCBarriers,
404 AggValueSlot::IsNotAliased);
John McCall558d2ab2010-09-15 10:14:12 +0000405
406 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000407
David Blaikie4e4d0842012-03-11 07:00:24 +0000408 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000409 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000410 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
411 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000412}
413
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000414static void EmitAggMemberInitializer(CodeGenFunction &CGF,
415 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000416 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000417 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000418 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000419 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000420 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000421 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000422 LValue LV = LHS;
Sebastian Redl924db712012-02-19 15:41:54 +0000423 { // Scope for Cleanups.
424 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000425
Sebastian Redl924db712012-02-19 15:41:54 +0000426 if (ArrayIndexVar) {
427 // If we have an array index variable, load it and use it as an offset.
428 // Then, increment the value.
429 llvm::Value *Dest = LHS.getAddress();
430 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
431 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
432 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
433 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
434 CGF.Builder.CreateStore(Next, ArrayIndexVar);
435
436 // Update the LValue.
437 LV.setAddress(Dest);
438 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
439 LV.setAlignment(std::min(Align, LV.getAlignment()));
440 }
441
442 if (!CGF.hasAggregateLLVMType(T)) {
443 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
444 } else if (T->isAnyComplexType()) {
445 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
446 LV.isVolatileQualified());
447 } else {
448 AggValueSlot Slot =
449 AggValueSlot::forLValue(LV,
450 AggValueSlot::IsDestructed,
451 AggValueSlot::DoesNotNeedGCBarriers,
452 AggValueSlot::IsNotAliased);
453
454 CGF.EmitAggExpr(Init, Slot);
455 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000456 }
John McCall558d2ab2010-09-15 10:14:12 +0000457
Sebastian Redl924db712012-02-19 15:41:54 +0000458 // Now, outside of the initializer cleanup scope, destroy the backing array
459 // for a std::initializer_list member.
Sebastian Redl972edf02012-02-19 16:03:09 +0000460 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl924db712012-02-19 15:41:54 +0000461
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000462 return;
463 }
464
465 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
466 assert(Array && "Array initialization without the array type?");
467 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000468 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000469 assert(IndexVar && "Array index variable not loaded");
470
471 // Initialize this index variable to zero.
472 llvm::Value* Zero
473 = llvm::Constant::getNullValue(
474 CGF.ConvertType(CGF.getContext().getSizeType()));
475 CGF.Builder.CreateStore(Zero, IndexVar);
476
477 // Start the loop with a block that tests the condition.
478 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
479 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
480
481 CGF.EmitBlock(CondBlock);
482
483 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
484 // Generate: if (loop-index < number-of-elements) fall to the loop body,
485 // otherwise, go to the block after the for-loop.
486 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000487 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000488 llvm::Value *NumElementsPtr =
489 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000490 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
491 "isless");
492
493 // If the condition is true, execute the body.
494 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
495
496 CGF.EmitBlock(ForBody);
497 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
498
499 {
John McCallf1549f62010-07-06 01:34:17 +0000500 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000501
502 // Inside the loop body recurse to emit the inner loop or, eventually, the
503 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000504 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
505 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000506 }
507
508 CGF.EmitBlock(ContinueBlock);
509
510 // Emit the increment of the loop counter.
511 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
512 Counter = CGF.Builder.CreateLoad(IndexVar);
513 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
514 CGF.Builder.CreateStore(NextVal, IndexVar);
515
516 // Finally, branch back up to the condition for the next iteration.
517 CGF.EmitBranch(CondBlock);
518
519 // Emit the fall-through block.
520 CGF.EmitBlock(AfterFor, true);
521}
John McCall182ab512010-07-21 01:23:41 +0000522
523namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000524 struct CallMemberDtor : EHScopeStack::Cleanup {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000525 llvm::Value *V;
John McCall182ab512010-07-21 01:23:41 +0000526 CXXDestructorDecl *Dtor;
527
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000528 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
529 : V(V), Dtor(Dtor) {}
John McCall182ab512010-07-21 01:23:41 +0000530
John McCallad346f42011-07-12 20:27:29 +0000531 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall182ab512010-07-21 01:23:41 +0000532 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000533 V);
John McCall182ab512010-07-21 01:23:41 +0000534 }
535 };
536}
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000537
538static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
539 bool Moving) {
540 return Moving ? Record->hasTrivialMoveConstructor() :
541 Record->hasTrivialCopyConstructor();
542}
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000543
Anders Carlsson607d0372009-12-24 22:46:43 +0000544static void EmitMemberInitializer(CodeGenFunction &CGF,
545 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000546 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000547 const CXXConstructorDecl *Constructor,
548 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000549 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000550 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000551 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000552
553 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000554 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000555 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000556
557 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000558 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000559
Anders Carlsson607d0372009-12-24 22:46:43 +0000560 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000561 if (MemberInit->isIndirectMemberInitializer()) {
562 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
563 MemberInit->getIndirectMember(), 0);
564 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000565 } else {
566 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000567 }
568
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000569 // Special case: if we are in a copy or move constructor, and we are copying
570 // an array of PODs or classes with trivial copy constructors, ignore the
571 // AST and perform the copy we know is equivalent.
572 // FIXME: This is hacky at best... if we had a bit more explicit information
573 // in the AST, we could generalize it more easily.
574 const ConstantArrayType *Array
575 = CGF.getContext().getAsConstantArrayType(FieldType);
576 if (Array && Constructor->isImplicitlyDefined() &&
577 Constructor->isCopyOrMoveConstructor()) {
578 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
579 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
580 if (BaseElementTy.isPODType(CGF.getContext()) ||
581 (Record && hasTrivialCopyOrMoveConstructor(Record,
582 Constructor->isMoveConstructor()))) {
583 // Find the source pointer. We knows it's the last argument because
584 // we know we're in a copy constructor.
585 unsigned SrcArgIndex = Args.size() - 1;
586 llvm::Value *SrcPtr
587 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
588 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
589
590 // Copy the aggregate.
591 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
592 LHS.isVolatileQualified());
593 return;
594 }
595 }
596
597 ArrayRef<VarDecl *> ArrayIndexes;
598 if (MemberInit->getNumArrayIndices())
599 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000600 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000601}
602
Eli Friedmanb74ed082012-02-14 02:31:03 +0000603void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
604 LValue LHS, Expr *Init,
605 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000606 QualType FieldType = Field->getType();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000607 if (!hasAggregateLLVMType(FieldType)) {
John McCallf85e1932011-06-15 23:02:42 +0000608 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000609 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000610 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000611 RValue RHS = RValue::get(EmitScalarExpr(Init));
612 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000613 }
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000614 } else if (FieldType->isAnyComplexType()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000615 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
Anders Carlsson607d0372009-12-24 22:46:43 +0000616 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000617 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000618 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000619 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000620
621 // The LHS is a pointer to the first object we'll be constructing, as
622 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000623 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
624 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000625 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000626 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
627 BasePtr);
628 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000629
630 // Create an array index that will be used to walk over all of the
631 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000632 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000633 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000634 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000635
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000636
637 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000638 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000639 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000640 }
641
Eli Friedmanb74ed082012-02-14 02:31:03 +0000642 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000643 ArrayIndexes, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000644
David Blaikie4e4d0842012-03-11 07:00:24 +0000645 if (!CGM.getLangOpts().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000646 return;
647
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000648 // FIXME: If we have an array of classes w/ non-trivial destructors,
649 // we need to destroy in reverse order of construction along the exception
650 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000651 const RecordType *RT = FieldType->getAs<RecordType>();
652 if (!RT)
653 return;
654
655 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000656 if (!RD->hasTrivialDestructor())
Eli Friedmanb74ed082012-02-14 02:31:03 +0000657 EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
658 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000659 }
660}
661
John McCallc0bf4622010-02-23 00:48:20 +0000662/// Checks whether the given constructor is a valid subject for the
663/// complete-to-base constructor delegation optimization, i.e.
664/// emitting the complete constructor as a simple call to the base
665/// constructor.
666static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
667
668 // Currently we disable the optimization for classes with virtual
669 // bases because (1) the addresses of parameter variables need to be
670 // consistent across all initializers but (2) the delegate function
671 // call necessarily creates a second copy of the parameter variable.
672 //
673 // The limiting example (purely theoretical AFAIK):
674 // struct A { A(int &c) { c++; } };
675 // struct B : virtual A {
676 // B(int count) : A(count) { printf("%d\n", count); }
677 // };
678 // ...although even this example could in principle be emitted as a
679 // delegation since the address of the parameter doesn't escape.
680 if (Ctor->getParent()->getNumVBases()) {
681 // TODO: white-list trivial vbase initializers. This case wouldn't
682 // be subject to the restrictions below.
683
684 // TODO: white-list cases where:
685 // - there are no non-reference parameters to the constructor
686 // - the initializers don't access any non-reference parameters
687 // - the initializers don't take the address of non-reference
688 // parameters
689 // - etc.
690 // If we ever add any of the above cases, remember that:
691 // - function-try-blocks will always blacklist this optimization
692 // - we need to perform the constructor prologue and cleanup in
693 // EmitConstructorBody.
694
695 return false;
696 }
697
698 // We also disable the optimization for variadic functions because
699 // it's impossible to "re-pass" varargs.
700 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
701 return false;
702
Sean Hunt059ce0d2011-05-01 07:04:31 +0000703 // FIXME: Decide if we can do a delegation of a delegating constructor.
704 if (Ctor->isDelegatingConstructor())
705 return false;
706
John McCallc0bf4622010-02-23 00:48:20 +0000707 return true;
708}
709
John McCall9fc6a772010-02-19 09:25:03 +0000710/// EmitConstructorBody - Emits the body of the current constructor.
711void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
712 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
713 CXXCtorType CtorType = CurGD.getCtorType();
714
John McCallc0bf4622010-02-23 00:48:20 +0000715 // Before we go any further, try the complete->base constructor
716 // delegation optimization.
717 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000718 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000719 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000720 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
721 return;
722 }
723
John McCall9fc6a772010-02-19 09:25:03 +0000724 Stmt *Body = Ctor->getBody();
725
John McCallc0bf4622010-02-23 00:48:20 +0000726 // Enter the function-try-block before the constructor prologue if
727 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000728 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000729 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000730 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000731
John McCallf1549f62010-07-06 01:34:17 +0000732 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000733
John McCallc0bf4622010-02-23 00:48:20 +0000734 // Emit the constructor prologue, i.e. the base and member
735 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000736 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000737
738 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000739 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000740 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
741 else if (Body)
742 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000743
744 // Emit any cleanup blocks associated with the member or base
745 // initializers, which includes (along the exceptional path) the
746 // destructors for those members and bases that were fully
747 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000748 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000749
John McCallc0bf4622010-02-23 00:48:20 +0000750 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000751 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000752}
753
Anders Carlsson607d0372009-12-24 22:46:43 +0000754/// EmitCtorPrologue - This routine generates necessary code to initialize
755/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000756void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000757 CXXCtorType CtorType,
758 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000759 if (CD->isDelegatingConstructor())
760 return EmitDelegatingCXXConstructorCall(CD, Args);
761
Anders Carlsson607d0372009-12-24 22:46:43 +0000762 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000763
Chris Lattner5f9e2722011-07-23 10:55:15 +0000764 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000765
Anders Carlsson607d0372009-12-24 22:46:43 +0000766 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
767 E = CD->init_end();
768 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000769 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000770
Sean Huntd49bd552011-05-03 20:19:28 +0000771 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000772 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000773 } else {
774 assert(Member->isAnyMemberInitializer() &&
775 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000776 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000777 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000778 }
779
Anders Carlsson603d6d12010-03-28 21:07:49 +0000780 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000781
John McCallf1549f62010-07-06 01:34:17 +0000782 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000783 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000784}
785
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000786static bool
787FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
788
789static bool
790HasTrivialDestructorBody(ASTContext &Context,
791 const CXXRecordDecl *BaseClassDecl,
792 const CXXRecordDecl *MostDerivedClassDecl)
793{
794 // If the destructor is trivial we don't have to check anything else.
795 if (BaseClassDecl->hasTrivialDestructor())
796 return true;
797
798 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
799 return false;
800
801 // Check fields.
802 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
803 E = BaseClassDecl->field_end(); I != E; ++I) {
804 const FieldDecl *Field = *I;
805
806 if (!FieldHasTrivialDestructorBody(Context, Field))
807 return false;
808 }
809
810 // Check non-virtual bases.
811 for (CXXRecordDecl::base_class_const_iterator I =
812 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
813 I != E; ++I) {
814 if (I->isVirtual())
815 continue;
816
817 const CXXRecordDecl *NonVirtualBase =
818 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
819 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
820 MostDerivedClassDecl))
821 return false;
822 }
823
824 if (BaseClassDecl == MostDerivedClassDecl) {
825 // Check virtual bases.
826 for (CXXRecordDecl::base_class_const_iterator I =
827 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
828 I != E; ++I) {
829 const CXXRecordDecl *VirtualBase =
830 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
831 if (!HasTrivialDestructorBody(Context, VirtualBase,
832 MostDerivedClassDecl))
833 return false;
834 }
835 }
836
837 return true;
838}
839
840static bool
841FieldHasTrivialDestructorBody(ASTContext &Context,
842 const FieldDecl *Field)
843{
844 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
845
846 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
847 if (!RT)
848 return true;
849
850 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
851 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
852}
853
Anders Carlssonffb945f2011-05-14 23:26:09 +0000854/// CanSkipVTablePointerInitialization - Check whether we need to initialize
855/// any vtable pointers before calling this destructor.
856static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000857 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000858 if (!Dtor->hasTrivialBody())
859 return false;
860
861 // Check the fields.
862 const CXXRecordDecl *ClassDecl = Dtor->getParent();
863 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
864 E = ClassDecl->field_end(); I != E; ++I) {
865 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000866
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000867 if (!FieldHasTrivialDestructorBody(Context, Field))
868 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000869 }
870
871 return true;
872}
873
John McCall9fc6a772010-02-19 09:25:03 +0000874/// EmitDestructorBody - Emits the body of the current destructor.
875void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
876 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
877 CXXDtorType DtorType = CurGD.getDtorType();
878
John McCall50da2ca2010-07-21 05:30:47 +0000879 // The call to operator delete in a deleting destructor happens
880 // outside of the function-try-block, which means it's always
881 // possible to delegate the destructor body to the complete
882 // destructor. Do so.
883 if (DtorType == Dtor_Deleting) {
884 EnterDtorCleanups(Dtor, Dtor_Deleting);
885 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
886 LoadCXXThis());
887 PopCleanupBlock();
888 return;
889 }
890
John McCall9fc6a772010-02-19 09:25:03 +0000891 Stmt *Body = Dtor->getBody();
892
893 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000894 // anything else.
895 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000896 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000897 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000898
John McCall50da2ca2010-07-21 05:30:47 +0000899 // Enter the epilogue cleanups.
900 RunCleanupsScope DtorEpilogue(*this);
901
John McCall9fc6a772010-02-19 09:25:03 +0000902 // If this is the complete variant, just invoke the base variant;
903 // the epilogue will destruct the virtual bases. But we can't do
904 // this optimization if the body is a function-try-block, because
905 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000906 switch (DtorType) {
907 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
908
909 case Dtor_Complete:
910 // Enter the cleanup scopes for virtual bases.
911 EnterDtorCleanups(Dtor, Dtor_Complete);
912
913 if (!isTryBody) {
914 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
915 LoadCXXThis());
916 break;
917 }
918 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000919
John McCall50da2ca2010-07-21 05:30:47 +0000920 case Dtor_Base:
921 // Enter the cleanup scopes for fields and non-virtual bases.
922 EnterDtorCleanups(Dtor, Dtor_Base);
923
924 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000925 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
926 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000927
928 if (isTryBody)
929 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
930 else if (Body)
931 EmitStmt(Body);
932 else {
933 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
934 // nothing to do besides what's in the epilogue
935 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000936 // -fapple-kext must inline any call to this dtor into
937 // the caller's body.
David Blaikie4e4d0842012-03-11 07:00:24 +0000938 if (getContext().getLangOpts().AppleKext)
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000939 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000940 break;
John McCall9fc6a772010-02-19 09:25:03 +0000941 }
942
John McCall50da2ca2010-07-21 05:30:47 +0000943 // Jump out through the epilogue cleanups.
944 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000945
946 // Exit the try if applicable.
947 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000948 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000949}
950
John McCall50da2ca2010-07-21 05:30:47 +0000951namespace {
952 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000953 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000954 CallDtorDelete() {}
955
John McCallad346f42011-07-12 20:27:29 +0000956 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000957 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
958 const CXXRecordDecl *ClassDecl = Dtor->getParent();
959 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
960 CGF.getContext().getTagDeclType(ClassDecl));
961 }
962 };
963
John McCall9928c482011-07-12 16:41:08 +0000964 class DestroyField : public EHScopeStack::Cleanup {
965 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000966 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +0000967 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +0000968
John McCall9928c482011-07-12 16:41:08 +0000969 public:
970 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
971 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000972 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +0000973 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +0000974
John McCallad346f42011-07-12 20:27:29 +0000975 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000976 // Find the address of the field.
977 llvm::Value *thisValue = CGF.LoadCXXThis();
978 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
979 assert(LV.isSimple());
980
981 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000982 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +0000983 }
984 };
985}
986
Anders Carlsson607d0372009-12-24 22:46:43 +0000987/// EmitDtorEpilogue - Emit all code that comes at the end of class's
988/// destructor. This is to call destructors on members and base classes
989/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000990void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
991 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000992 assert(!DD->isTrivial() &&
993 "Should not emit dtor epilogue for trivial dtor!");
994
John McCall50da2ca2010-07-21 05:30:47 +0000995 // The deleting-destructor phase just needs to call the appropriate
996 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +0000997 if (DtorType == Dtor_Deleting) {
998 assert(DD->getOperatorDelete() &&
999 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +00001000 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +00001001 return;
1002 }
1003
John McCall50da2ca2010-07-21 05:30:47 +00001004 const CXXRecordDecl *ClassDecl = DD->getParent();
1005
Richard Smith416f63e2011-09-18 12:11:43 +00001006 // Unions have no bases and do not call field destructors.
1007 if (ClassDecl->isUnion())
1008 return;
1009
John McCall50da2ca2010-07-21 05:30:47 +00001010 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001011 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001012
1013 // We push them in the forward order so that they'll be popped in
1014 // the reverse order.
1015 for (CXXRecordDecl::base_class_const_iterator I =
1016 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001017 I != E; ++I) {
1018 const CXXBaseSpecifier &Base = *I;
1019 CXXRecordDecl *BaseClassDecl
1020 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1021
1022 // Ignore trivial destructors.
1023 if (BaseClassDecl->hasTrivialDestructor())
1024 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001025
John McCall1f0fca52010-07-21 07:22:38 +00001026 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1027 BaseClassDecl,
1028 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001029 }
John McCall50da2ca2010-07-21 05:30:47 +00001030
John McCall3b477332010-02-18 19:59:28 +00001031 return;
1032 }
1033
1034 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001035
1036 // Destroy non-virtual bases.
1037 for (CXXRecordDecl::base_class_const_iterator I =
1038 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1039 const CXXBaseSpecifier &Base = *I;
1040
1041 // Ignore virtual bases.
1042 if (Base.isVirtual())
1043 continue;
1044
1045 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1046
1047 // Ignore trivial destructors.
1048 if (BaseClassDecl->hasTrivialDestructor())
1049 continue;
John McCall3b477332010-02-18 19:59:28 +00001050
John McCall1f0fca52010-07-21 07:22:38 +00001051 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1052 BaseClassDecl,
1053 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001054 }
1055
1056 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001057 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001058 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1059 E = ClassDecl->field_end(); I != E; ++I) {
John McCall9928c482011-07-12 16:41:08 +00001060 const FieldDecl *field = *I;
1061 QualType type = field->getType();
1062 QualType::DestructionKind dtorKind = type.isDestructedType();
1063 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001064
Richard Smith9a561d52012-02-26 09:11:52 +00001065 // Anonymous union members do not have their destructors called.
1066 const RecordType *RT = type->getAsUnionType();
1067 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1068
John McCall9928c482011-07-12 16:41:08 +00001069 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1070 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1071 getDestroyer(dtorKind),
1072 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001073 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001074}
1075
John McCallc3c07662011-07-13 06:10:41 +00001076/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1077/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001078///
John McCallc3c07662011-07-13 06:10:41 +00001079/// \param ctor the constructor to call for each element
1080/// \param argBegin,argEnd the arguments to evaluate and pass to the
1081/// constructor
1082/// \param arrayType the type of the array to initialize
1083/// \param arrayBegin an arrayType*
1084/// \param zeroInitialize true if each element should be
1085/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001086void
John McCallc3c07662011-07-13 06:10:41 +00001087CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1088 const ConstantArrayType *arrayType,
1089 llvm::Value *arrayBegin,
1090 CallExpr::const_arg_iterator argBegin,
1091 CallExpr::const_arg_iterator argEnd,
1092 bool zeroInitialize) {
1093 QualType elementType;
1094 llvm::Value *numElements =
1095 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001096
John McCallc3c07662011-07-13 06:10:41 +00001097 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1098 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001099}
1100
John McCallc3c07662011-07-13 06:10:41 +00001101/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1102/// constructor for each of several members of an array.
1103///
1104/// \param ctor the constructor to call for each element
1105/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001106/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001107/// \param argBegin,argEnd the arguments to evaluate and pass to the
1108/// constructor
1109/// \param arrayBegin a T*, where T is the type constructed by ctor
1110/// \param zeroInitialize true if each element should be
1111/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001112void
John McCallc3c07662011-07-13 06:10:41 +00001113CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1114 llvm::Value *numElements,
1115 llvm::Value *arrayBegin,
1116 CallExpr::const_arg_iterator argBegin,
1117 CallExpr::const_arg_iterator argEnd,
1118 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001119
1120 // It's legal for numElements to be zero. This can happen both
1121 // dynamically, because x can be zero in 'new A[x]', and statically,
1122 // because of GCC extensions that permit zero-length arrays. There
1123 // are probably legitimate places where we could assume that this
1124 // doesn't happen, but it's not clear that it's worth it.
1125 llvm::BranchInst *zeroCheckBranch = 0;
1126
1127 // Optimize for a constant count.
1128 llvm::ConstantInt *constantCount
1129 = dyn_cast<llvm::ConstantInt>(numElements);
1130 if (constantCount) {
1131 // Just skip out if the constant count is zero.
1132 if (constantCount->isZero()) return;
1133
1134 // Otherwise, emit the check.
1135 } else {
1136 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1137 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1138 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1139 EmitBlock(loopBB);
1140 }
1141
John McCallc3c07662011-07-13 06:10:41 +00001142 // Find the end of the array.
1143 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1144 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001145
John McCallc3c07662011-07-13 06:10:41 +00001146 // Enter the loop, setting up a phi for the current location to initialize.
1147 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1148 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1149 EmitBlock(loopBB);
1150 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1151 "arrayctor.cur");
1152 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001153
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001154 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001155
1156 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001157
Douglas Gregor59174c02010-07-21 01:10:17 +00001158 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001159 if (zeroInitialize)
1160 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001161
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001162 // C++ [class.temporary]p4:
1163 // There are two contexts in which temporaries are destroyed at a different
1164 // point than the end of the full-expression. The first context is when a
1165 // default constructor is called to initialize an element of an array.
1166 // If the constructor has one or more default arguments, the destruction of
1167 // every temporary created in a default argument expression is sequenced
1168 // before the construction of the next array element, if any.
1169
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001170 {
John McCallf1549f62010-07-06 01:34:17 +00001171 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001172
John McCallc3c07662011-07-13 06:10:41 +00001173 // Evaluate the constructor and its arguments in a regular
1174 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001175 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001176 !ctor->getParent()->hasTrivialDestructor()) {
1177 Destroyer *destroyer = destroyCXXObject;
1178 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1179 }
1180
1181 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1182 cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001183 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001184
John McCallc3c07662011-07-13 06:10:41 +00001185 // Go to the next element.
1186 llvm::Value *next =
1187 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1188 "arrayctor.next");
1189 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001190
John McCallc3c07662011-07-13 06:10:41 +00001191 // Check whether that's the end of the loop.
1192 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1193 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1194 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001195
John McCalldd376ca2011-07-13 07:37:11 +00001196 // Patch the earlier check to skip over the loop.
1197 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1198
John McCallc3c07662011-07-13 06:10:41 +00001199 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001200}
1201
John McCallbdc4d802011-07-09 01:37:26 +00001202void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1203 llvm::Value *addr,
1204 QualType type) {
1205 const RecordType *rtype = type->castAs<RecordType>();
1206 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1207 const CXXDestructorDecl *dtor = record->getDestructor();
1208 assert(!dtor->isTrivial());
1209 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1210 addr);
1211}
1212
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001213void
1214CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001215 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001216 llvm::Value *This,
1217 CallExpr::const_arg_iterator ArgBeg,
1218 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001219
1220 CGDebugInfo *DI = getDebugInfo();
1221 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001222 // If debug info for this class has not been emitted then this is the
1223 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001224 const CXXRecordDecl *Parent = D->getParent();
1225 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1226 Parent->getLocation());
1227 }
1228
John McCall8b6bbeb2010-02-06 00:25:16 +00001229 if (D->isTrivial()) {
1230 if (ArgBeg == ArgEnd) {
1231 // Trivial default constructor, no codegen required.
1232 assert(D->isDefaultConstructor() &&
1233 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001234 return;
1235 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001236
1237 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001238 assert(D->isCopyOrMoveConstructor() &&
1239 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001240
John McCall8b6bbeb2010-02-06 00:25:16 +00001241 const Expr *E = (*ArgBeg);
1242 QualType Ty = E->getType();
1243 llvm::Value *Src = EmitLValue(E).getAddress();
1244 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001245 return;
1246 }
1247
Anders Carlsson314e6222010-05-02 23:33:10 +00001248 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001249 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1250
Anders Carlssonc997d422010-01-02 01:01:18 +00001251 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001252}
1253
John McCallc0bf4622010-02-23 00:48:20 +00001254void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001255CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1256 llvm::Value *This, llvm::Value *Src,
1257 CallExpr::const_arg_iterator ArgBeg,
1258 CallExpr::const_arg_iterator ArgEnd) {
1259 if (D->isTrivial()) {
1260 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001261 assert(D->isCopyOrMoveConstructor() &&
1262 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001263 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1264 return;
1265 }
1266 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1267 clang::Ctor_Complete);
1268 assert(D->isInstance() &&
1269 "Trying to emit a member call expr on a static method!");
1270
1271 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1272
1273 CallArgList Args;
1274
1275 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001276 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001277
1278
1279 // Push the src ptr.
1280 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001281 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001282 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001283 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001284
1285 // Skip over first argument (Src).
1286 ++ArgBeg;
1287 CallExpr::const_arg_iterator Arg = ArgBeg;
1288 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1289 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1290 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001291 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001292 }
1293 // Either we've emitted all the call args, or we have a call to a
1294 // variadic function.
1295 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1296 "Extra arguments in non-variadic function!");
1297 // If we still have any arguments, emit them using the type of the argument.
1298 for (; Arg != ArgEnd; ++Arg) {
1299 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001300 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001301 }
1302
John McCallde5d3c72012-02-17 03:33:10 +00001303 EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Eli Friedmanc55db3b2011-08-09 17:38:12 +00001304 ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001305}
1306
1307void
John McCallc0bf4622010-02-23 00:48:20 +00001308CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1309 CXXCtorType CtorType,
1310 const FunctionArgList &Args) {
1311 CallArgList DelegateArgs;
1312
1313 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1314 assert(I != E && "no parameters to constructor");
1315
1316 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001317 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001318 ++I;
1319
1320 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001321 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1322 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001323 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001324 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001325
Anders Carlssonaf440352010-03-23 04:11:45 +00001326 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001327 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001328 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001329 ++I;
1330 }
1331 }
1332
1333 // Explicit arguments.
1334 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001335 const VarDecl *param = *I;
1336 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001337 }
1338
John McCallde5d3c72012-02-17 03:33:10 +00001339 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallc0bf4622010-02-23 00:48:20 +00001340 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1341 ReturnValueSlot(), DelegateArgs, Ctor);
1342}
1343
Sean Huntb76af9c2011-05-03 23:05:34 +00001344namespace {
1345 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1346 const CXXDestructorDecl *Dtor;
1347 llvm::Value *Addr;
1348 CXXDtorType Type;
1349
1350 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1351 CXXDtorType Type)
1352 : Dtor(D), Addr(Addr), Type(Type) {}
1353
John McCallad346f42011-07-12 20:27:29 +00001354 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001355 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1356 Addr);
1357 }
1358 };
1359}
1360
Sean Hunt059ce0d2011-05-01 07:04:31 +00001361void
1362CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1363 const FunctionArgList &Args) {
1364 assert(Ctor->isDelegatingConstructor());
1365
1366 llvm::Value *ThisPtr = LoadCXXThis();
1367
Eli Friedmanf3940782011-12-03 00:54:26 +00001368 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001369 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001370 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001371 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001372 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001373 AggValueSlot::DoesNotNeedGCBarriers,
1374 AggValueSlot::IsNotAliased);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001375
1376 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001377
Sean Huntb76af9c2011-05-03 23:05:34 +00001378 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001379 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001380 CXXDtorType Type =
1381 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1382
1383 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1384 ClassDecl->getDestructor(),
1385 ThisPtr, Type);
1386 }
1387}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001388
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001389void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1390 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001391 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001392 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001393 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1394 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001395 llvm::Value *Callee = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00001396 if (getContext().getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001397 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1398 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001399
1400 if (!Callee)
1401 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001402
Anders Carlssonc997d422010-01-02 01:01:18 +00001403 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001404}
1405
John McCall291ae942010-07-21 01:41:18 +00001406namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001407 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001408 const CXXDestructorDecl *Dtor;
1409 llvm::Value *Addr;
1410
1411 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1412 : Dtor(D), Addr(Addr) {}
1413
John McCallad346f42011-07-12 20:27:29 +00001414 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001415 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1416 /*ForVirtualBase=*/false, Addr);
1417 }
1418 };
1419}
1420
John McCall81407d42010-07-21 06:29:51 +00001421void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1422 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001423 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001424}
1425
John McCallf1549f62010-07-06 01:34:17 +00001426void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1427 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1428 if (!ClassDecl) return;
1429 if (ClassDecl->hasTrivialDestructor()) return;
1430
1431 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001432 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001433 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001434}
1435
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001436llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001437CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1438 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001439 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001440 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001441 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001442 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001443
1444 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001445 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1446 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001447 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001448 ConvertType(getContext().getPointerDiffType());
1449
1450 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1451 PtrDiffTy->getPointerTo());
1452
1453 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1454
1455 return VBaseOffset;
1456}
1457
Anders Carlssond103f9f2010-03-28 19:40:00 +00001458void
1459CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001460 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001461 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001462 llvm::Constant *VTable,
1463 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001464 const CXXRecordDecl *RD = Base.getBase();
1465
Anders Carlssond103f9f2010-03-28 19:40:00 +00001466 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001467 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001468
Anders Carlssonc83f1062010-03-29 01:08:49 +00001469 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001470 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001471 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001472 // Get the secondary vpointer index.
1473 uint64_t VirtualPointerIndex =
1474 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1475
1476 /// Load the VTT.
1477 llvm::Value *VTT = LoadCXXVTT();
1478 if (VirtualPointerIndex)
1479 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1480
1481 // And load the address point from the VTT.
1482 VTableAddressPoint = Builder.CreateLoad(VTT);
1483 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001484 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001485 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001486 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001487 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001488 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001489
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001490 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001491 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001492 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001493
1494 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1495 // We need to use the virtual base offset offset because the virtual base
1496 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001497 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1498 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001499 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001500 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001501 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001502 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001503 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001504
1505 // Apply the offsets.
1506 llvm::Value *VTableField = LoadCXXThis();
1507
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001508 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001509 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1510 NonVirtualOffset,
1511 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001512
Anders Carlssond103f9f2010-03-28 19:40:00 +00001513 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001514 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001515 VTableAddressPoint->getType()->getPointerTo();
1516 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001517 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1518 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001519}
1520
Anders Carlsson603d6d12010-03-28 21:07:49 +00001521void
1522CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001523 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001524 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001525 bool BaseIsNonVirtualPrimaryBase,
1526 llvm::Constant *VTable,
1527 const CXXRecordDecl *VTableClass,
1528 VisitedVirtualBasesSetTy& VBases) {
1529 // If this base is a non-virtual primary base the address point has already
1530 // been set.
1531 if (!BaseIsNonVirtualPrimaryBase) {
1532 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001533 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1534 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001535 }
1536
1537 const CXXRecordDecl *RD = Base.getBase();
1538
1539 // Traverse bases.
1540 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1541 E = RD->bases_end(); I != E; ++I) {
1542 CXXRecordDecl *BaseDecl
1543 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1544
1545 // Ignore classes without a vtable.
1546 if (!BaseDecl->isDynamicClass())
1547 continue;
1548
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001549 CharUnits BaseOffset;
1550 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001551 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001552
1553 if (I->isVirtual()) {
1554 // Check if we've visited this virtual base before.
1555 if (!VBases.insert(BaseDecl))
1556 continue;
1557
1558 const ASTRecordLayout &Layout =
1559 getContext().getASTRecordLayout(VTableClass);
1560
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001561 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1562 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001563 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001564 } else {
1565 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1566
Ken Dyck4230d522011-03-24 01:21:01 +00001567 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001568 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001569 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001570 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001571 }
1572
Ken Dyck4230d522011-03-24 01:21:01 +00001573 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001574 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001575 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001576 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001577 VTable, VTableClass, VBases);
1578 }
1579}
1580
1581void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1582 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001583 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001584 return;
1585
Anders Carlsson07036902010-03-26 04:39:42 +00001586 // Get the VTable.
1587 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001588
Anders Carlsson603d6d12010-03-28 21:07:49 +00001589 // Initialize the vtable pointers for this class and all of its bases.
1590 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001591 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1592 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001593 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001594 /*BaseIsNonVirtualPrimaryBase=*/false,
1595 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001596}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001597
1598llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001599 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001600 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001601 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
1602 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
1603 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00001604}
Anders Carlssona2447e02011-05-08 20:32:23 +00001605
1606static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1607 const Expr *E = Base;
1608
1609 while (true) {
1610 E = E->IgnoreParens();
1611 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1612 if (CE->getCastKind() == CK_DerivedToBase ||
1613 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1614 CE->getCastKind() == CK_NoOp) {
1615 E = CE->getSubExpr();
1616 continue;
1617 }
1618 }
1619
1620 break;
1621 }
1622
1623 QualType DerivedType = E->getType();
1624 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1625 DerivedType = PTy->getPointeeType();
1626
1627 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1628}
1629
1630// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1631// quite what we want.
1632static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1633 while (true) {
1634 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1635 E = PE->getSubExpr();
1636 continue;
1637 }
1638
1639 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1640 if (CE->getCastKind() == CK_NoOp) {
1641 E = CE->getSubExpr();
1642 continue;
1643 }
1644 }
1645 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1646 if (UO->getOpcode() == UO_Extension) {
1647 E = UO->getSubExpr();
1648 continue;
1649 }
1650 }
1651 return E;
1652 }
1653}
1654
1655/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1656/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00001657static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1658 const CXXMethodDecl *MD) {
1659 // If the most derived class is marked final, we know that no subclass can
1660 // override this member function and so we can devirtualize it. For example:
1661 //
1662 // struct A { virtual void f(); }
1663 // struct B final : A { };
1664 //
1665 // void f(B *b) {
1666 // b->f();
1667 // }
1668 //
1669 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1670 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1671 return true;
1672
1673 // If the member function is marked 'final', we know that it can't be
1674 // overridden and can therefore devirtualize it.
1675 if (MD->hasAttr<FinalAttr>())
1676 return true;
1677
1678 // Similarly, if the class itself is marked 'final' it can't be overridden
1679 // and we can therefore devirtualize the member function call.
1680 if (MD->getParent()->hasAttr<FinalAttr>())
1681 return true;
1682
1683 Base = skipNoOpCastsAndParens(Base);
1684 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1685 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1686 // This is a record decl. We know the type and can devirtualize it.
1687 return VD->getType()->isRecordType();
1688 }
1689
1690 return false;
1691 }
1692
1693 // We can always devirtualize calls on temporary object expressions.
1694 if (isa<CXXConstructExpr>(Base))
1695 return true;
1696
1697 // And calls on bound temporaries.
1698 if (isa<CXXBindTemporaryExpr>(Base))
1699 return true;
1700
1701 // Check if this is a call expr that returns a record type.
1702 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1703 return CE->getCallReturnType()->isRecordType();
1704
1705 // We can't devirtualize the call.
1706 return false;
1707}
1708
1709static bool UseVirtualCall(ASTContext &Context,
1710 const CXXOperatorCallExpr *CE,
1711 const CXXMethodDecl *MD) {
1712 if (!MD->isVirtual())
1713 return false;
1714
1715 // When building with -fapple-kext, all calls must go through the vtable since
1716 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00001717 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00001718 return true;
1719
1720 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1721}
1722
1723llvm::Value *
1724CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1725 const CXXMethodDecl *MD,
1726 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00001727 llvm::FunctionType *fnType =
1728 CGM.getTypes().GetFunctionType(
1729 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00001730
1731 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00001732 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001733
John McCallde5d3c72012-02-17 03:33:10 +00001734 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001735}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001736
Eli Friedman64bee652012-02-25 02:48:22 +00001737void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *Lambda,
1738 CallArgList &CallArgs) {
1739 // Lookup the call operator
Eli Friedman21f6ed92012-02-16 03:47:28 +00001740 DeclarationName Name
1741 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
1742 DeclContext::lookup_const_result Calls = Lambda->lookup(Name);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001743 CXXMethodDecl *CallOperator = cast<CXXMethodDecl>(*Calls.first++);
Eli Friedman64bee652012-02-25 02:48:22 +00001744 const FunctionProtoType *FPT =
1745 CallOperator->getType()->getAs<FunctionProtoType>();
Eli Friedman21f6ed92012-02-16 03:47:28 +00001746 QualType ResultType = FPT->getResultType();
1747
Eli Friedman21f6ed92012-02-16 03:47:28 +00001748 // Get the address of the call operator.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001749 GlobalDecl GD(CallOperator);
John McCallde5d3c72012-02-17 03:33:10 +00001750 const CGFunctionInfo &CalleeFnInfo =
1751 CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtInfo(),
1752 RequiredArgs::forPrototypePlus(FPT, 1));
1753 llvm::Type *Ty = CGM.getTypes().GetFunctionType(CalleeFnInfo);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001754 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
1755
1756 // Determine whether we have a return value slot to use.
1757 ReturnValueSlot Slot;
1758 if (!ResultType->isVoidType() &&
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001759 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
Eli Friedman21f6ed92012-02-16 03:47:28 +00001760 hasAggregateLLVMType(CurFnInfo->getReturnType()))
1761 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
1762
1763 // Now emit our call.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001764 RValue RV = EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001765
1766 // Forward the returned value
1767 if (!ResultType->isVoidType() && Slot.isNull())
1768 EmitReturnOfRValue(RV, ResultType);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001769}
1770
Eli Friedman64bee652012-02-25 02:48:22 +00001771void CodeGenFunction::EmitLambdaBlockInvokeBody() {
1772 const BlockDecl *BD = BlockInfo->getBlockDecl();
1773 const VarDecl *variable = BD->capture_begin()->getVariable();
1774 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
1775
1776 // Start building arguments for forwarding call
1777 CallArgList CallArgs;
1778
1779 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1780 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
1781 CallArgs.add(RValue::get(ThisPtr), ThisType);
1782
1783 // Add the rest of the parameters.
1784 for (BlockDecl::param_const_iterator I = BD->param_begin(),
1785 E = BD->param_end(); I != E; ++I) {
1786 ParmVarDecl *param = *I;
1787 EmitDelegateCallArg(CallArgs, param);
1788 }
1789
1790 EmitForwardingCallToLambda(Lambda, CallArgs);
1791}
1792
1793void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
1794 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
1795 // FIXME: Making this work correctly is nasty because it requires either
1796 // cloning the body of the call operator or making the call operator forward.
1797 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
1798 return;
1799 }
1800
Eli Friedman64bee652012-02-25 02:48:22 +00001801 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00001802}
1803
1804void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
1805 const CXXRecordDecl *Lambda = MD->getParent();
1806
1807 // Start building arguments for forwarding call
1808 CallArgList CallArgs;
1809
1810 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1811 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
1812 CallArgs.add(RValue::get(ThisPtr), ThisType);
1813
1814 // Add the rest of the parameters.
1815 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
1816 E = MD->param_end(); I != E; ++I) {
1817 ParmVarDecl *param = *I;
1818 EmitDelegateCallArg(CallArgs, param);
1819 }
1820
1821 EmitForwardingCallToLambda(Lambda, CallArgs);
1822}
1823
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001824void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
1825 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00001826 // FIXME: Making this work correctly is nasty because it requires either
1827 // cloning the body of the call operator or making the call operator forward.
1828 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00001829 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00001830 }
1831
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001832 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001833}