blob: 254ef8001d384505e72bb948135ac468ca93d19b [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,
John McCall57cd1b82012-03-28 23:30:44 +0000404 AggValueSlot::IsNotAliased,
405 AggValueSlot::IsNotCompleteObject);
John McCall558d2ab2010-09-15 10:14:12 +0000406
407 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson594d5e82010-02-06 20:00:21 +0000408
David Blaikie4e4d0842012-03-11 07:00:24 +0000409 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlssonc1cfdf82011-02-20 00:20:27 +0000410 !BaseClassDecl->hasTrivialDestructor())
John McCall1f0fca52010-07-21 07:22:38 +0000411 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
412 isBaseVirtual);
Anders Carlsson607d0372009-12-24 22:46:43 +0000413}
414
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000415static void EmitAggMemberInitializer(CodeGenFunction &CGF,
416 LValue LHS,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000417 Expr *Init,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000418 llvm::Value *ArrayIndexVar,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000419 QualType T,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000420 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000421 unsigned Index) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000422 if (Index == ArrayIndexes.size()) {
Eli Friedmanf3940782011-12-03 00:54:26 +0000423 LValue LV = LHS;
Sebastian Redl924db712012-02-19 15:41:54 +0000424 { // Scope for Cleanups.
425 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Eli Friedmanf3940782011-12-03 00:54:26 +0000426
Sebastian Redl924db712012-02-19 15:41:54 +0000427 if (ArrayIndexVar) {
428 // If we have an array index variable, load it and use it as an offset.
429 // Then, increment the value.
430 llvm::Value *Dest = LHS.getAddress();
431 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
432 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
433 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
434 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
435 CGF.Builder.CreateStore(Next, ArrayIndexVar);
436
437 // Update the LValue.
438 LV.setAddress(Dest);
439 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
440 LV.setAlignment(std::min(Align, LV.getAlignment()));
441 }
442
443 if (!CGF.hasAggregateLLVMType(T)) {
444 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
445 } else if (T->isAnyComplexType()) {
446 CGF.EmitComplexExprIntoAddr(Init, LV.getAddress(),
447 LV.isVolatileQualified());
448 } else {
449 AggValueSlot Slot =
450 AggValueSlot::forLValue(LV,
451 AggValueSlot::IsDestructed,
452 AggValueSlot::DoesNotNeedGCBarriers,
John McCall57cd1b82012-03-28 23:30:44 +0000453 AggValueSlot::IsNotAliased,
454 AggValueSlot::IsCompleteObject);
Sebastian Redl924db712012-02-19 15:41:54 +0000455
456 CGF.EmitAggExpr(Init, Slot);
457 }
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000458 }
John McCall558d2ab2010-09-15 10:14:12 +0000459
Sebastian Redl924db712012-02-19 15:41:54 +0000460 // Now, outside of the initializer cleanup scope, destroy the backing array
461 // for a std::initializer_list member.
Sebastian Redl972edf02012-02-19 16:03:09 +0000462 CGF.MaybeEmitStdInitializerListCleanup(LV.getAddress(), Init);
Sebastian Redl924db712012-02-19 15:41:54 +0000463
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000464 return;
465 }
466
467 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
468 assert(Array && "Array initialization without the array type?");
469 llvm::Value *IndexVar
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000470 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000471 assert(IndexVar && "Array index variable not loaded");
472
473 // Initialize this index variable to zero.
474 llvm::Value* Zero
475 = llvm::Constant::getNullValue(
476 CGF.ConvertType(CGF.getContext().getSizeType()));
477 CGF.Builder.CreateStore(Zero, IndexVar);
478
479 // Start the loop with a block that tests the condition.
480 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
481 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
482
483 CGF.EmitBlock(CondBlock);
484
485 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
486 // Generate: if (loop-index < number-of-elements) fall to the loop body,
487 // otherwise, go to the block after the for-loop.
488 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000489 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner985f7392010-05-06 06:35:23 +0000490 llvm::Value *NumElementsPtr =
491 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000492 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
493 "isless");
494
495 // If the condition is true, execute the body.
496 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
497
498 CGF.EmitBlock(ForBody);
499 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
500
501 {
John McCallf1549f62010-07-06 01:34:17 +0000502 CodeGenFunction::RunCleanupsScope Cleanups(CGF);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000503
504 // Inside the loop body recurse to emit the inner loop or, eventually, the
505 // constructor call.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000506 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
507 Array->getElementType(), ArrayIndexes, Index + 1);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000508 }
509
510 CGF.EmitBlock(ContinueBlock);
511
512 // Emit the increment of the loop counter.
513 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
514 Counter = CGF.Builder.CreateLoad(IndexVar);
515 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
516 CGF.Builder.CreateStore(NextVal, IndexVar);
517
518 // Finally, branch back up to the condition for the next iteration.
519 CGF.EmitBranch(CondBlock);
520
521 // Emit the fall-through block.
522 CGF.EmitBlock(AfterFor, true);
523}
John McCall182ab512010-07-21 01:23:41 +0000524
525namespace {
John McCall1f0fca52010-07-21 07:22:38 +0000526 struct CallMemberDtor : EHScopeStack::Cleanup {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000527 llvm::Value *V;
John McCall182ab512010-07-21 01:23:41 +0000528 CXXDestructorDecl *Dtor;
529
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000530 CallMemberDtor(llvm::Value *V, CXXDestructorDecl *Dtor)
531 : V(V), Dtor(Dtor) {}
John McCall182ab512010-07-21 01:23:41 +0000532
John McCallad346f42011-07-12 20:27:29 +0000533 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall182ab512010-07-21 01:23:41 +0000534 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000535 V);
John McCall182ab512010-07-21 01:23:41 +0000536 }
537 };
538}
Sebastian Redl85ea7aa2011-08-30 19:58:05 +0000539
540static bool hasTrivialCopyOrMoveConstructor(const CXXRecordDecl *Record,
541 bool Moving) {
542 return Moving ? Record->hasTrivialMoveConstructor() :
543 Record->hasTrivialCopyConstructor();
544}
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000545
Anders Carlsson607d0372009-12-24 22:46:43 +0000546static void EmitMemberInitializer(CodeGenFunction &CGF,
547 const CXXRecordDecl *ClassDecl,
Sean Huntcbb67482011-01-08 20:30:50 +0000548 CXXCtorInitializer *MemberInit,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000549 const CXXConstructorDecl *Constructor,
550 FunctionArgList &Args) {
Francois Pichet00eb3f92010-12-04 09:14:42 +0000551 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlsson607d0372009-12-24 22:46:43 +0000552 "Must have member initializer!");
Richard Smith7a614d82011-06-11 17:19:42 +0000553 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlsson607d0372009-12-24 22:46:43 +0000554
555 // non-static data member initializers.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000556 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000557 QualType FieldType = Field->getType();
Anders Carlsson607d0372009-12-24 22:46:43 +0000558
559 llvm::Value *ThisPtr = CGF.LoadCXXThis();
John McCalla9976d32010-05-21 01:18:57 +0000560 LValue LHS;
Anders Carlsson06a29702010-01-29 05:24:29 +0000561
Anders Carlsson607d0372009-12-24 22:46:43 +0000562 // If we are initializing an anonymous union field, drill down to the field.
Francois Pichet00eb3f92010-12-04 09:14:42 +0000563 if (MemberInit->isIndirectMemberInitializer()) {
564 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr,
565 MemberInit->getIndirectMember(), 0);
566 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCalla9976d32010-05-21 01:18:57 +0000567 } else {
568 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0);
Anders Carlsson607d0372009-12-24 22:46:43 +0000569 }
570
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000571 // Special case: if we are in a copy or move constructor, and we are copying
572 // an array of PODs or classes with trivial copy constructors, ignore the
573 // AST and perform the copy we know is equivalent.
574 // FIXME: This is hacky at best... if we had a bit more explicit information
575 // in the AST, we could generalize it more easily.
576 const ConstantArrayType *Array
577 = CGF.getContext().getAsConstantArrayType(FieldType);
578 if (Array && Constructor->isImplicitlyDefined() &&
579 Constructor->isCopyOrMoveConstructor()) {
580 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
581 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl();
582 if (BaseElementTy.isPODType(CGF.getContext()) ||
583 (Record && hasTrivialCopyOrMoveConstructor(Record,
584 Constructor->isMoveConstructor()))) {
585 // Find the source pointer. We knows it's the last argument because
586 // we know we're in a copy constructor.
587 unsigned SrcArgIndex = Args.size() - 1;
588 llvm::Value *SrcPtr
589 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
590 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0);
591
592 // Copy the aggregate.
593 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
John McCall57cd1b82012-03-28 23:30:44 +0000594 LHS.isVolatileQualified(),
595 /*destIsCompleteObject*/ true);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000596 return;
597 }
598 }
599
600 ArrayRef<VarDecl *> ArrayIndexes;
601 if (MemberInit->getNumArrayIndices())
602 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000603 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000604}
605
Eli Friedmanb74ed082012-02-14 02:31:03 +0000606void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
607 LValue LHS, Expr *Init,
608 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000609 QualType FieldType = Field->getType();
Eli Friedmanb74ed082012-02-14 02:31:03 +0000610 if (!hasAggregateLLVMType(FieldType)) {
John McCallf85e1932011-06-15 23:02:42 +0000611 if (LHS.isSimple()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000612 EmitExprAsInit(Init, Field, LHS, false);
John McCallf85e1932011-06-15 23:02:42 +0000613 } else {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000614 RValue RHS = RValue::get(EmitScalarExpr(Init));
615 EmitStoreThroughLValue(RHS, LHS);
John McCallf85e1932011-06-15 23:02:42 +0000616 }
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000617 } else if (FieldType->isAnyComplexType()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000618 EmitComplexExprIntoAddr(Init, LHS.getAddress(), LHS.isVolatileQualified());
Anders Carlsson607d0372009-12-24 22:46:43 +0000619 } else {
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000620 llvm::Value *ArrayIndexVar = 0;
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000621 if (ArrayIndexes.size()) {
Eli Friedmanb74ed082012-02-14 02:31:03 +0000622 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000623
624 // The LHS is a pointer to the first object we'll be constructing, as
625 // a flat array.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000626 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
627 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000628 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000629 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
630 BasePtr);
631 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000632
633 // Create an array index that will be used to walk over all of the
634 // objects we're constructing.
Eli Friedmanb74ed082012-02-14 02:31:03 +0000635 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000636 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedmanb74ed082012-02-14 02:31:03 +0000637 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000638
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000639
640 // Emit the block variables for the array indices, if any.
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000641 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedmanb74ed082012-02-14 02:31:03 +0000642 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000643 }
644
Eli Friedmanb74ed082012-02-14 02:31:03 +0000645 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman0bdb5aa2012-02-14 02:15:49 +0000646 ArrayIndexes, 0);
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000647
David Blaikie4e4d0842012-03-11 07:00:24 +0000648 if (!CGM.getLangOpts().Exceptions)
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000649 return;
650
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000651 // FIXME: If we have an array of classes w/ non-trivial destructors,
652 // we need to destroy in reverse order of construction along the exception
653 // path.
Anders Carlsson9405dcd2010-02-06 19:50:17 +0000654 const RecordType *RT = FieldType->getAs<RecordType>();
655 if (!RT)
656 return;
657
658 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall182ab512010-07-21 01:23:41 +0000659 if (!RD->hasTrivialDestructor())
Eli Friedmanb74ed082012-02-14 02:31:03 +0000660 EHStack.pushCleanup<CallMemberDtor>(EHCleanup, LHS.getAddress(),
661 RD->getDestructor());
Anders Carlsson607d0372009-12-24 22:46:43 +0000662 }
663}
664
John McCallc0bf4622010-02-23 00:48:20 +0000665/// Checks whether the given constructor is a valid subject for the
666/// complete-to-base constructor delegation optimization, i.e.
667/// emitting the complete constructor as a simple call to the base
668/// constructor.
669static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
670
671 // Currently we disable the optimization for classes with virtual
672 // bases because (1) the addresses of parameter variables need to be
673 // consistent across all initializers but (2) the delegate function
674 // call necessarily creates a second copy of the parameter variable.
675 //
676 // The limiting example (purely theoretical AFAIK):
677 // struct A { A(int &c) { c++; } };
678 // struct B : virtual A {
679 // B(int count) : A(count) { printf("%d\n", count); }
680 // };
681 // ...although even this example could in principle be emitted as a
682 // delegation since the address of the parameter doesn't escape.
683 if (Ctor->getParent()->getNumVBases()) {
684 // TODO: white-list trivial vbase initializers. This case wouldn't
685 // be subject to the restrictions below.
686
687 // TODO: white-list cases where:
688 // - there are no non-reference parameters to the constructor
689 // - the initializers don't access any non-reference parameters
690 // - the initializers don't take the address of non-reference
691 // parameters
692 // - etc.
693 // If we ever add any of the above cases, remember that:
694 // - function-try-blocks will always blacklist this optimization
695 // - we need to perform the constructor prologue and cleanup in
696 // EmitConstructorBody.
697
698 return false;
699 }
700
701 // We also disable the optimization for variadic functions because
702 // it's impossible to "re-pass" varargs.
703 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
704 return false;
705
Sean Hunt059ce0d2011-05-01 07:04:31 +0000706 // FIXME: Decide if we can do a delegation of a delegating constructor.
707 if (Ctor->isDelegatingConstructor())
708 return false;
709
John McCallc0bf4622010-02-23 00:48:20 +0000710 return true;
711}
712
John McCall9fc6a772010-02-19 09:25:03 +0000713/// EmitConstructorBody - Emits the body of the current constructor.
714void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
715 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
716 CXXCtorType CtorType = CurGD.getCtorType();
717
John McCallc0bf4622010-02-23 00:48:20 +0000718 // Before we go any further, try the complete->base constructor
719 // delegation optimization.
720 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) {
Devang Pateld67ef0e2010-08-11 21:04:37 +0000721 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher73fb3502011-10-13 21:45:18 +0000722 DI->EmitLocation(Builder, Ctor->getLocEnd());
John McCallc0bf4622010-02-23 00:48:20 +0000723 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
724 return;
725 }
726
John McCall9fc6a772010-02-19 09:25:03 +0000727 Stmt *Body = Ctor->getBody();
728
John McCallc0bf4622010-02-23 00:48:20 +0000729 // Enter the function-try-block before the constructor prologue if
730 // applicable.
John McCallc0bf4622010-02-23 00:48:20 +0000731 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallc0bf4622010-02-23 00:48:20 +0000732 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000733 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000734
John McCallf1549f62010-07-06 01:34:17 +0000735 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin();
John McCall9fc6a772010-02-19 09:25:03 +0000736
John McCallc0bf4622010-02-23 00:48:20 +0000737 // Emit the constructor prologue, i.e. the base and member
738 // initializers.
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000739 EmitCtorPrologue(Ctor, CtorType, Args);
John McCall9fc6a772010-02-19 09:25:03 +0000740
741 // Emit the body of the statement.
John McCallc0bf4622010-02-23 00:48:20 +0000742 if (IsTryBody)
John McCall9fc6a772010-02-19 09:25:03 +0000743 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
744 else if (Body)
745 EmitStmt(Body);
John McCall9fc6a772010-02-19 09:25:03 +0000746
747 // Emit any cleanup blocks associated with the member or base
748 // initializers, which includes (along the exceptional path) the
749 // destructors for those members and bases that were fully
750 // constructed.
John McCallf1549f62010-07-06 01:34:17 +0000751 PopCleanupBlocks(CleanupDepth);
John McCall9fc6a772010-02-19 09:25:03 +0000752
John McCallc0bf4622010-02-23 00:48:20 +0000753 if (IsTryBody)
John McCall59a70002010-07-07 06:56:46 +0000754 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000755}
756
Anders Carlsson607d0372009-12-24 22:46:43 +0000757/// EmitCtorPrologue - This routine generates necessary code to initialize
758/// base classes and non-static data members belonging to this constructor.
Anders Carlsson607d0372009-12-24 22:46:43 +0000759void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000760 CXXCtorType CtorType,
761 FunctionArgList &Args) {
Sean Hunt059ce0d2011-05-01 07:04:31 +0000762 if (CD->isDelegatingConstructor())
763 return EmitDelegatingCXXConstructorCall(CD, Args);
764
Anders Carlsson607d0372009-12-24 22:46:43 +0000765 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000766
Chris Lattner5f9e2722011-07-23 10:55:15 +0000767 SmallVector<CXXCtorInitializer *, 8> MemberInitializers;
Anders Carlsson607d0372009-12-24 22:46:43 +0000768
Anders Carlsson607d0372009-12-24 22:46:43 +0000769 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
770 E = CD->init_end();
771 B != E; ++B) {
Sean Huntcbb67482011-01-08 20:30:50 +0000772 CXXCtorInitializer *Member = (*B);
Anders Carlsson607d0372009-12-24 22:46:43 +0000773
Sean Huntd49bd552011-05-03 20:19:28 +0000774 if (Member->isBaseInitializer()) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000775 EmitBaseInitializer(*this, ClassDecl, Member, CtorType);
Sean Huntd49bd552011-05-03 20:19:28 +0000776 } else {
777 assert(Member->isAnyMemberInitializer() &&
778 "Delegating initializer on non-delegating constructor");
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000779 MemberInitializers.push_back(Member);
Sean Huntd49bd552011-05-03 20:19:28 +0000780 }
Anders Carlsson607d0372009-12-24 22:46:43 +0000781 }
782
Anders Carlsson603d6d12010-03-28 21:07:49 +0000783 InitializeVTablePointers(ClassDecl);
Anders Carlssona78fa2c2010-02-02 19:58:43 +0000784
John McCallf1549f62010-07-06 01:34:17 +0000785 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I)
Douglas Gregorfb8cc252010-05-05 05:51:00 +0000786 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args);
Anders Carlsson607d0372009-12-24 22:46:43 +0000787}
788
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000789static bool
790FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
791
792static bool
793HasTrivialDestructorBody(ASTContext &Context,
794 const CXXRecordDecl *BaseClassDecl,
795 const CXXRecordDecl *MostDerivedClassDecl)
796{
797 // If the destructor is trivial we don't have to check anything else.
798 if (BaseClassDecl->hasTrivialDestructor())
799 return true;
800
801 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
802 return false;
803
804 // Check fields.
805 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
806 E = BaseClassDecl->field_end(); I != E; ++I) {
807 const FieldDecl *Field = *I;
808
809 if (!FieldHasTrivialDestructorBody(Context, Field))
810 return false;
811 }
812
813 // Check non-virtual bases.
814 for (CXXRecordDecl::base_class_const_iterator I =
815 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
816 I != E; ++I) {
817 if (I->isVirtual())
818 continue;
819
820 const CXXRecordDecl *NonVirtualBase =
821 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
822 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
823 MostDerivedClassDecl))
824 return false;
825 }
826
827 if (BaseClassDecl == MostDerivedClassDecl) {
828 // Check virtual bases.
829 for (CXXRecordDecl::base_class_const_iterator I =
830 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
831 I != E; ++I) {
832 const CXXRecordDecl *VirtualBase =
833 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
834 if (!HasTrivialDestructorBody(Context, VirtualBase,
835 MostDerivedClassDecl))
836 return false;
837 }
838 }
839
840 return true;
841}
842
843static bool
844FieldHasTrivialDestructorBody(ASTContext &Context,
845 const FieldDecl *Field)
846{
847 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
848
849 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
850 if (!RT)
851 return true;
852
853 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
854 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
855}
856
Anders Carlssonffb945f2011-05-14 23:26:09 +0000857/// CanSkipVTablePointerInitialization - Check whether we need to initialize
858/// any vtable pointers before calling this destructor.
859static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssone3d6cf22011-05-16 04:08:36 +0000860 const CXXDestructorDecl *Dtor) {
Anders Carlssonffb945f2011-05-14 23:26:09 +0000861 if (!Dtor->hasTrivialBody())
862 return false;
863
864 // Check the fields.
865 const CXXRecordDecl *ClassDecl = Dtor->getParent();
866 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
867 E = ClassDecl->field_end(); I != E; ++I) {
868 const FieldDecl *Field = *I;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000869
Anders Carlssonadf5dc32011-05-15 17:36:21 +0000870 if (!FieldHasTrivialDestructorBody(Context, Field))
871 return false;
Anders Carlssonffb945f2011-05-14 23:26:09 +0000872 }
873
874 return true;
875}
876
John McCall9fc6a772010-02-19 09:25:03 +0000877/// EmitDestructorBody - Emits the body of the current destructor.
878void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
879 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
880 CXXDtorType DtorType = CurGD.getDtorType();
881
John McCall50da2ca2010-07-21 05:30:47 +0000882 // The call to operator delete in a deleting destructor happens
883 // outside of the function-try-block, which means it's always
884 // possible to delegate the destructor body to the complete
885 // destructor. Do so.
886 if (DtorType == Dtor_Deleting) {
887 EnterDtorCleanups(Dtor, Dtor_Deleting);
888 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
889 LoadCXXThis());
890 PopCleanupBlock();
891 return;
892 }
893
John McCall9fc6a772010-02-19 09:25:03 +0000894 Stmt *Body = Dtor->getBody();
895
896 // If the body is a function-try-block, enter the try before
John McCall50da2ca2010-07-21 05:30:47 +0000897 // anything else.
898 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCall9fc6a772010-02-19 09:25:03 +0000899 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000900 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000901
John McCall50da2ca2010-07-21 05:30:47 +0000902 // Enter the epilogue cleanups.
903 RunCleanupsScope DtorEpilogue(*this);
904
John McCall9fc6a772010-02-19 09:25:03 +0000905 // If this is the complete variant, just invoke the base variant;
906 // the epilogue will destruct the virtual bases. But we can't do
907 // this optimization if the body is a function-try-block, because
908 // we'd introduce *two* handler blocks.
John McCall50da2ca2010-07-21 05:30:47 +0000909 switch (DtorType) {
910 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
911
912 case Dtor_Complete:
913 // Enter the cleanup scopes for virtual bases.
914 EnterDtorCleanups(Dtor, Dtor_Complete);
915
916 if (!isTryBody) {
917 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
918 LoadCXXThis());
919 break;
920 }
921 // Fallthrough: act like we're in the base variant.
John McCall9fc6a772010-02-19 09:25:03 +0000922
John McCall50da2ca2010-07-21 05:30:47 +0000923 case Dtor_Base:
924 // Enter the cleanup scopes for fields and non-virtual bases.
925 EnterDtorCleanups(Dtor, Dtor_Base);
926
927 // Initialize the vtable pointers before entering the body.
Anders Carlssonffb945f2011-05-14 23:26:09 +0000928 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
929 InitializeVTablePointers(Dtor->getParent());
John McCall50da2ca2010-07-21 05:30:47 +0000930
931 if (isTryBody)
932 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
933 else if (Body)
934 EmitStmt(Body);
935 else {
936 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
937 // nothing to do besides what's in the epilogue
938 }
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000939 // -fapple-kext must inline any call to this dtor into
940 // the caller's body.
David Blaikie4e4d0842012-03-11 07:00:24 +0000941 if (getContext().getLangOpts().AppleKext)
Fariborz Jahanian5abec142011-02-02 23:12:46 +0000942 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCall50da2ca2010-07-21 05:30:47 +0000943 break;
John McCall9fc6a772010-02-19 09:25:03 +0000944 }
945
John McCall50da2ca2010-07-21 05:30:47 +0000946 // Jump out through the epilogue cleanups.
947 DtorEpilogue.ForceCleanup();
John McCall9fc6a772010-02-19 09:25:03 +0000948
949 // Exit the try if applicable.
950 if (isTryBody)
John McCall59a70002010-07-07 06:56:46 +0000951 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCall9fc6a772010-02-19 09:25:03 +0000952}
953
John McCall50da2ca2010-07-21 05:30:47 +0000954namespace {
955 /// Call the operator delete associated with the current destructor.
John McCall1f0fca52010-07-21 07:22:38 +0000956 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCall50da2ca2010-07-21 05:30:47 +0000957 CallDtorDelete() {}
958
John McCallad346f42011-07-12 20:27:29 +0000959 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall50da2ca2010-07-21 05:30:47 +0000960 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
961 const CXXRecordDecl *ClassDecl = Dtor->getParent();
962 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
963 CGF.getContext().getTagDeclType(ClassDecl));
964 }
965 };
966
John McCall9928c482011-07-12 16:41:08 +0000967 class DestroyField : public EHScopeStack::Cleanup {
968 const FieldDecl *field;
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000969 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +0000970 bool useEHCleanupForArray;
John McCall50da2ca2010-07-21 05:30:47 +0000971
John McCall9928c482011-07-12 16:41:08 +0000972 public:
973 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
974 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +0000975 : field(field), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +0000976 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall50da2ca2010-07-21 05:30:47 +0000977
John McCallad346f42011-07-12 20:27:29 +0000978 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +0000979 // Find the address of the field.
980 llvm::Value *thisValue = CGF.LoadCXXThis();
981 LValue LV = CGF.EmitLValueForField(thisValue, field, /*CVRQualifiers=*/0);
982 assert(LV.isSimple());
983
984 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +0000985 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall50da2ca2010-07-21 05:30:47 +0000986 }
987 };
988}
989
Anders Carlsson607d0372009-12-24 22:46:43 +0000990/// EmitDtorEpilogue - Emit all code that comes at the end of class's
991/// destructor. This is to call destructors on members and base classes
992/// in reverse order of their construction.
John McCall50da2ca2010-07-21 05:30:47 +0000993void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
994 CXXDtorType DtorType) {
Anders Carlsson607d0372009-12-24 22:46:43 +0000995 assert(!DD->isTrivial() &&
996 "Should not emit dtor epilogue for trivial dtor!");
997
John McCall50da2ca2010-07-21 05:30:47 +0000998 // The deleting-destructor phase just needs to call the appropriate
999 // operator delete that Sema picked up.
John McCall3b477332010-02-18 19:59:28 +00001000 if (DtorType == Dtor_Deleting) {
1001 assert(DD->getOperatorDelete() &&
1002 "operator delete missing - EmitDtorEpilogue");
John McCall1f0fca52010-07-21 07:22:38 +00001003 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
John McCall3b477332010-02-18 19:59:28 +00001004 return;
1005 }
1006
John McCall50da2ca2010-07-21 05:30:47 +00001007 const CXXRecordDecl *ClassDecl = DD->getParent();
1008
Richard Smith416f63e2011-09-18 12:11:43 +00001009 // Unions have no bases and do not call field destructors.
1010 if (ClassDecl->isUnion())
1011 return;
1012
John McCall50da2ca2010-07-21 05:30:47 +00001013 // The complete-destructor phase just destructs all the virtual bases.
John McCall3b477332010-02-18 19:59:28 +00001014 if (DtorType == Dtor_Complete) {
John McCall50da2ca2010-07-21 05:30:47 +00001015
1016 // We push them in the forward order so that they'll be popped in
1017 // the reverse order.
1018 for (CXXRecordDecl::base_class_const_iterator I =
1019 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall3b477332010-02-18 19:59:28 +00001020 I != E; ++I) {
1021 const CXXBaseSpecifier &Base = *I;
1022 CXXRecordDecl *BaseClassDecl
1023 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1024
1025 // Ignore trivial destructors.
1026 if (BaseClassDecl->hasTrivialDestructor())
1027 continue;
John McCall50da2ca2010-07-21 05:30:47 +00001028
John McCall1f0fca52010-07-21 07:22:38 +00001029 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1030 BaseClassDecl,
1031 /*BaseIsVirtual*/ true);
John McCall3b477332010-02-18 19:59:28 +00001032 }
John McCall50da2ca2010-07-21 05:30:47 +00001033
John McCall3b477332010-02-18 19:59:28 +00001034 return;
1035 }
1036
1037 assert(DtorType == Dtor_Base);
John McCall50da2ca2010-07-21 05:30:47 +00001038
1039 // Destroy non-virtual bases.
1040 for (CXXRecordDecl::base_class_const_iterator I =
1041 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1042 const CXXBaseSpecifier &Base = *I;
1043
1044 // Ignore virtual bases.
1045 if (Base.isVirtual())
1046 continue;
1047
1048 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1049
1050 // Ignore trivial destructors.
1051 if (BaseClassDecl->hasTrivialDestructor())
1052 continue;
John McCall3b477332010-02-18 19:59:28 +00001053
John McCall1f0fca52010-07-21 07:22:38 +00001054 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1055 BaseClassDecl,
1056 /*BaseIsVirtual*/ false);
John McCall50da2ca2010-07-21 05:30:47 +00001057 }
1058
1059 // Destroy direct fields.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001060 SmallVector<const FieldDecl *, 16> FieldDecls;
Anders Carlsson607d0372009-12-24 22:46:43 +00001061 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1062 E = ClassDecl->field_end(); I != E; ++I) {
John McCall9928c482011-07-12 16:41:08 +00001063 const FieldDecl *field = *I;
1064 QualType type = field->getType();
1065 QualType::DestructionKind dtorKind = type.isDestructedType();
1066 if (!dtorKind) continue;
John McCall50da2ca2010-07-21 05:30:47 +00001067
Richard Smith9a561d52012-02-26 09:11:52 +00001068 // Anonymous union members do not have their destructors called.
1069 const RecordType *RT = type->getAsUnionType();
1070 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1071
John McCall9928c482011-07-12 16:41:08 +00001072 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1073 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1074 getDestroyer(dtorKind),
1075 cleanupKind & EHCleanup);
Anders Carlsson607d0372009-12-24 22:46:43 +00001076 }
Anders Carlsson607d0372009-12-24 22:46:43 +00001077}
1078
John McCallc3c07662011-07-13 06:10:41 +00001079/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1080/// constructor for each of several members of an array.
Douglas Gregor59174c02010-07-21 01:10:17 +00001081///
John McCallc3c07662011-07-13 06:10:41 +00001082/// \param ctor the constructor to call for each element
1083/// \param argBegin,argEnd the arguments to evaluate and pass to the
1084/// constructor
1085/// \param arrayType the type of the array to initialize
1086/// \param arrayBegin an arrayType*
1087/// \param zeroInitialize true if each element should be
1088/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001089void
John McCallc3c07662011-07-13 06:10:41 +00001090CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1091 const ConstantArrayType *arrayType,
1092 llvm::Value *arrayBegin,
1093 CallExpr::const_arg_iterator argBegin,
1094 CallExpr::const_arg_iterator argEnd,
1095 bool zeroInitialize) {
1096 QualType elementType;
1097 llvm::Value *numElements =
1098 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001099
John McCallc3c07662011-07-13 06:10:41 +00001100 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1101 argBegin, argEnd, zeroInitialize);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001102}
1103
John McCallc3c07662011-07-13 06:10:41 +00001104/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1105/// constructor for each of several members of an array.
1106///
1107/// \param ctor the constructor to call for each element
1108/// \param numElements the number of elements in the array;
John McCalldd376ca2011-07-13 07:37:11 +00001109/// may be zero
John McCallc3c07662011-07-13 06:10:41 +00001110/// \param argBegin,argEnd the arguments to evaluate and pass to the
1111/// constructor
1112/// \param arrayBegin a T*, where T is the type constructed by ctor
1113/// \param zeroInitialize true if each element should be
1114/// zero-initialized before it is constructed
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001115void
John McCallc3c07662011-07-13 06:10:41 +00001116CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1117 llvm::Value *numElements,
1118 llvm::Value *arrayBegin,
1119 CallExpr::const_arg_iterator argBegin,
1120 CallExpr::const_arg_iterator argEnd,
1121 bool zeroInitialize) {
John McCalldd376ca2011-07-13 07:37:11 +00001122
1123 // It's legal for numElements to be zero. This can happen both
1124 // dynamically, because x can be zero in 'new A[x]', and statically,
1125 // because of GCC extensions that permit zero-length arrays. There
1126 // are probably legitimate places where we could assume that this
1127 // doesn't happen, but it's not clear that it's worth it.
1128 llvm::BranchInst *zeroCheckBranch = 0;
1129
1130 // Optimize for a constant count.
1131 llvm::ConstantInt *constantCount
1132 = dyn_cast<llvm::ConstantInt>(numElements);
1133 if (constantCount) {
1134 // Just skip out if the constant count is zero.
1135 if (constantCount->isZero()) return;
1136
1137 // Otherwise, emit the check.
1138 } else {
1139 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1140 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1141 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1142 EmitBlock(loopBB);
1143 }
1144
John McCallc3c07662011-07-13 06:10:41 +00001145 // Find the end of the array.
1146 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1147 "arrayctor.end");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001148
John McCallc3c07662011-07-13 06:10:41 +00001149 // Enter the loop, setting up a phi for the current location to initialize.
1150 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1151 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1152 EmitBlock(loopBB);
1153 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1154 "arrayctor.cur");
1155 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001156
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001157 // Inside the loop body, emit the constructor call on the array element.
John McCallc3c07662011-07-13 06:10:41 +00001158
1159 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001160
Douglas Gregor59174c02010-07-21 01:10:17 +00001161 // Zero initialize the storage, if requested.
John McCallc3c07662011-07-13 06:10:41 +00001162 if (zeroInitialize)
1163 EmitNullInitialization(cur, type);
Douglas Gregor59174c02010-07-21 01:10:17 +00001164
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001165 // C++ [class.temporary]p4:
1166 // There are two contexts in which temporaries are destroyed at a different
1167 // point than the end of the full-expression. The first context is when a
1168 // default constructor is called to initialize an element of an array.
1169 // If the constructor has one or more default arguments, the destruction of
1170 // every temporary created in a default argument expression is sequenced
1171 // before the construction of the next array element, if any.
1172
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001173 {
John McCallf1549f62010-07-06 01:34:17 +00001174 RunCleanupsScope Scope(*this);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001175
John McCallc3c07662011-07-13 06:10:41 +00001176 // Evaluate the constructor and its arguments in a regular
1177 // partial-destroy cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +00001178 if (getLangOpts().Exceptions &&
John McCallc3c07662011-07-13 06:10:41 +00001179 !ctor->getParent()->hasTrivialDestructor()) {
1180 Destroyer *destroyer = destroyCXXObject;
1181 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1182 }
1183
1184 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
1185 cur, argBegin, argEnd);
Anders Carlsson44ec82b2010-03-30 03:14:41 +00001186 }
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001187
John McCallc3c07662011-07-13 06:10:41 +00001188 // Go to the next element.
1189 llvm::Value *next =
1190 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1191 "arrayctor.next");
1192 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001193
John McCallc3c07662011-07-13 06:10:41 +00001194 // Check whether that's the end of the loop.
1195 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1196 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1197 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001198
John McCalldd376ca2011-07-13 07:37:11 +00001199 // Patch the earlier check to skip over the loop.
1200 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1201
John McCallc3c07662011-07-13 06:10:41 +00001202 EmitBlock(contBB);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001203}
1204
John McCallbdc4d802011-07-09 01:37:26 +00001205void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1206 llvm::Value *addr,
1207 QualType type) {
1208 const RecordType *rtype = type->castAs<RecordType>();
1209 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1210 const CXXDestructorDecl *dtor = record->getDestructor();
1211 assert(!dtor->isTrivial());
1212 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
1213 addr);
1214}
1215
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001216void
1217CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlsson155ed4a2010-05-02 23:20:53 +00001218 CXXCtorType Type, bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001219 llvm::Value *This,
1220 CallExpr::const_arg_iterator ArgBeg,
1221 CallExpr::const_arg_iterator ArgEnd) {
Devang Patel3ee36af2011-02-22 20:55:26 +00001222
1223 CGDebugInfo *DI = getDebugInfo();
1224 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) {
Eric Christopheraf790882012-02-01 21:44:56 +00001225 // If debug info for this class has not been emitted then this is the
1226 // right time to do so.
Devang Patel3ee36af2011-02-22 20:55:26 +00001227 const CXXRecordDecl *Parent = D->getParent();
1228 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent),
1229 Parent->getLocation());
1230 }
1231
John McCall8b6bbeb2010-02-06 00:25:16 +00001232 if (D->isTrivial()) {
1233 if (ArgBeg == ArgEnd) {
1234 // Trivial default constructor, no codegen required.
1235 assert(D->isDefaultConstructor() &&
1236 "trivial 0-arg ctor not a default ctor");
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001237 return;
1238 }
John McCall8b6bbeb2010-02-06 00:25:16 +00001239
1240 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001241 assert(D->isCopyOrMoveConstructor() &&
1242 "trivial 1-arg ctor not a copy/move ctor");
John McCall8b6bbeb2010-02-06 00:25:16 +00001243
John McCall8b6bbeb2010-02-06 00:25:16 +00001244 const Expr *E = (*ArgBeg);
1245 QualType Ty = E->getType();
1246 llvm::Value *Src = EmitLValue(E).getAddress();
1247 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001248 return;
1249 }
1250
Anders Carlsson314e6222010-05-02 23:33:10 +00001251 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001252 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type);
1253
Anders Carlssonc997d422010-01-02 01:01:18 +00001254 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001255}
1256
John McCallc0bf4622010-02-23 00:48:20 +00001257void
Fariborz Jahanian34999872010-11-13 21:53:34 +00001258CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1259 llvm::Value *This, llvm::Value *Src,
1260 CallExpr::const_arg_iterator ArgBeg,
1261 CallExpr::const_arg_iterator ArgEnd) {
1262 if (D->isTrivial()) {
1263 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl85ea7aa2011-08-30 19:58:05 +00001264 assert(D->isCopyOrMoveConstructor() &&
1265 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahanian34999872010-11-13 21:53:34 +00001266 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1267 return;
1268 }
1269 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D,
1270 clang::Ctor_Complete);
1271 assert(D->isInstance() &&
1272 "Trying to emit a member call expr on a static method!");
1273
1274 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
1275
1276 CallArgList Args;
1277
1278 // Push the this ptr.
Eli Friedman04c9a492011-05-02 17:57:46 +00001279 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahanian34999872010-11-13 21:53:34 +00001280
1281
1282 // Push the src ptr.
1283 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2acc6e32011-07-18 04:24:23 +00001284 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001285 Src = Builder.CreateBitCast(Src, t);
Eli Friedman04c9a492011-05-02 17:57:46 +00001286 Args.add(RValue::get(Src), QT);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001287
1288 // Skip over first argument (Src).
1289 ++ArgBeg;
1290 CallExpr::const_arg_iterator Arg = ArgBeg;
1291 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1,
1292 E = FPT->arg_type_end(); I != E; ++I, ++Arg) {
1293 assert(Arg != ArgEnd && "Running over edge of argument list!");
John McCall413ebdb2011-03-11 20:59:21 +00001294 EmitCallArg(Args, *Arg, *I);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001295 }
1296 // Either we've emitted all the call args, or we have a call to a
1297 // variadic function.
1298 assert((Arg == ArgEnd || FPT->isVariadic()) &&
1299 "Extra arguments in non-variadic function!");
1300 // If we still have any arguments, emit them using the type of the argument.
1301 for (; Arg != ArgEnd; ++Arg) {
1302 QualType ArgType = Arg->getType();
John McCall413ebdb2011-03-11 20:59:21 +00001303 EmitCallArg(Args, *Arg, ArgType);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001304 }
1305
John McCallde5d3c72012-02-17 03:33:10 +00001306 EmitCall(CGM.getTypes().arrangeFunctionCall(Args, FPT), Callee,
Eli Friedmanc55db3b2011-08-09 17:38:12 +00001307 ReturnValueSlot(), Args, D);
Fariborz Jahanian34999872010-11-13 21:53:34 +00001308}
1309
1310void
John McCallc0bf4622010-02-23 00:48:20 +00001311CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1312 CXXCtorType CtorType,
1313 const FunctionArgList &Args) {
1314 CallArgList DelegateArgs;
1315
1316 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1317 assert(I != E && "no parameters to constructor");
1318
1319 // this
Eli Friedman04c9a492011-05-02 17:57:46 +00001320 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallc0bf4622010-02-23 00:48:20 +00001321 ++I;
1322
1323 // vtt
Anders Carlsson314e6222010-05-02 23:33:10 +00001324 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType),
1325 /*ForVirtualBase=*/false)) {
John McCallc0bf4622010-02-23 00:48:20 +00001326 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman04c9a492011-05-02 17:57:46 +00001327 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallc0bf4622010-02-23 00:48:20 +00001328
Anders Carlssonaf440352010-03-23 04:11:45 +00001329 if (CodeGenVTables::needsVTTParameter(CurGD)) {
John McCallc0bf4622010-02-23 00:48:20 +00001330 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalld26bc762011-03-09 04:27:21 +00001331 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallc0bf4622010-02-23 00:48:20 +00001332 ++I;
1333 }
1334 }
1335
1336 // Explicit arguments.
1337 for (; I != E; ++I) {
John McCall413ebdb2011-03-11 20:59:21 +00001338 const VarDecl *param = *I;
1339 EmitDelegateCallArg(DelegateArgs, param);
John McCallc0bf4622010-02-23 00:48:20 +00001340 }
1341
John McCallde5d3c72012-02-17 03:33:10 +00001342 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
John McCallc0bf4622010-02-23 00:48:20 +00001343 CGM.GetAddrOfCXXConstructor(Ctor, CtorType),
1344 ReturnValueSlot(), DelegateArgs, Ctor);
1345}
1346
Sean Huntb76af9c2011-05-03 23:05:34 +00001347namespace {
1348 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1349 const CXXDestructorDecl *Dtor;
1350 llvm::Value *Addr;
1351 CXXDtorType Type;
1352
1353 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1354 CXXDtorType Type)
1355 : Dtor(D), Addr(Addr), Type(Type) {}
1356
John McCallad346f42011-07-12 20:27:29 +00001357 void Emit(CodeGenFunction &CGF, Flags flags) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001358 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
1359 Addr);
1360 }
1361 };
1362}
1363
Sean Hunt059ce0d2011-05-01 07:04:31 +00001364void
1365CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1366 const FunctionArgList &Args) {
1367 assert(Ctor->isDelegatingConstructor());
1368
1369 llvm::Value *ThisPtr = LoadCXXThis();
1370
Eli Friedmanf3940782011-12-03 00:54:26 +00001371 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedmand7722d92011-12-03 02:13:40 +00001372 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCallf85e1932011-06-15 23:02:42 +00001373 AggValueSlot AggSlot =
Eli Friedmanf3940782011-12-03 00:54:26 +00001374 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall7c2349b2011-08-25 20:40:09 +00001375 AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001376 AggValueSlot::DoesNotNeedGCBarriers,
John McCall57cd1b82012-03-28 23:30:44 +00001377 AggValueSlot::IsNotAliased,
1378 CurGD.getCtorType() == Ctor_Complete
1379 ? AggValueSlot::IsCompleteObject
1380 : AggValueSlot::IsNotCompleteObject);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001381
1382 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Sean Hunt059ce0d2011-05-01 07:04:31 +00001383
Sean Huntb76af9c2011-05-03 23:05:34 +00001384 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikie4e4d0842012-03-11 07:00:24 +00001385 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Sean Huntb76af9c2011-05-03 23:05:34 +00001386 CXXDtorType Type =
1387 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1388
1389 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1390 ClassDecl->getDestructor(),
1391 ThisPtr, Type);
1392 }
1393}
Sean Hunt059ce0d2011-05-01 07:04:31 +00001394
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001395void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1396 CXXDtorType Type,
Anders Carlsson8e6404c2010-05-02 23:29:11 +00001397 bool ForVirtualBase,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001398 llvm::Value *This) {
Anders Carlsson314e6222010-05-02 23:33:10 +00001399 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type),
1400 ForVirtualBase);
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001401 llvm::Value *Callee = 0;
David Blaikie4e4d0842012-03-11 07:00:24 +00001402 if (getContext().getLangOpts().AppleKext)
Fariborz Jahanian771c6782011-02-03 19:27:17 +00001403 Callee = BuildAppleKextVirtualDestructorCall(DD, Type,
1404 DD->getParent());
Fariborz Jahanianccd52592011-02-01 23:22:34 +00001405
1406 if (!Callee)
1407 Callee = CGM.GetAddrOfCXXDestructor(DD, Type);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001408
Anders Carlssonc997d422010-01-02 01:01:18 +00001409 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001410}
1411
John McCall291ae942010-07-21 01:41:18 +00001412namespace {
John McCall1f0fca52010-07-21 07:22:38 +00001413 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall291ae942010-07-21 01:41:18 +00001414 const CXXDestructorDecl *Dtor;
1415 llvm::Value *Addr;
1416
1417 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1418 : Dtor(D), Addr(Addr) {}
1419
John McCallad346f42011-07-12 20:27:29 +00001420 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall291ae942010-07-21 01:41:18 +00001421 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
1422 /*ForVirtualBase=*/false, Addr);
1423 }
1424 };
1425}
1426
John McCall81407d42010-07-21 06:29:51 +00001427void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1428 llvm::Value *Addr) {
John McCall1f0fca52010-07-21 07:22:38 +00001429 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall81407d42010-07-21 06:29:51 +00001430}
1431
John McCallf1549f62010-07-06 01:34:17 +00001432void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1433 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1434 if (!ClassDecl) return;
1435 if (ClassDecl->hasTrivialDestructor()) return;
1436
1437 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCall642a75f2011-04-28 02:15:35 +00001438 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall81407d42010-07-21 06:29:51 +00001439 PushDestructorCleanup(D, Addr);
John McCallf1549f62010-07-06 01:34:17 +00001440}
1441
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001442llvm::Value *
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001443CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This,
1444 const CXXRecordDecl *ClassDecl,
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001445 const CXXRecordDecl *BaseClassDecl) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001446 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy);
Ken Dyck14c65ca2011-04-07 12:37:09 +00001447 CharUnits VBaseOffsetOffset =
Peter Collingbourne1d2b3172011-09-26 01:56:30 +00001448 CGM.getVTableContext().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001449
1450 llvm::Value *VBaseOffsetPtr =
Ken Dyck14c65ca2011-04-07 12:37:09 +00001451 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(),
1452 "vbase.offset.ptr");
Chris Lattner2acc6e32011-07-18 04:24:23 +00001453 llvm::Type *PtrDiffTy =
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001454 ConvertType(getContext().getPointerDiffType());
1455
1456 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr,
1457 PtrDiffTy->getPointerTo());
1458
1459 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset");
1460
1461 return VBaseOffset;
1462}
1463
Anders Carlssond103f9f2010-03-28 19:40:00 +00001464void
1465CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001466 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001467 CharUnits OffsetFromNearestVBase,
Anders Carlssond103f9f2010-03-28 19:40:00 +00001468 llvm::Constant *VTable,
1469 const CXXRecordDecl *VTableClass) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001470 const CXXRecordDecl *RD = Base.getBase();
1471
Anders Carlssond103f9f2010-03-28 19:40:00 +00001472 // Compute the address point.
Anders Carlssonc83f1062010-03-29 01:08:49 +00001473 llvm::Value *VTableAddressPoint;
Anders Carlsson851853d2010-03-29 02:38:51 +00001474
Anders Carlssonc83f1062010-03-29 01:08:49 +00001475 // Check if we need to use a vtable from the VTT.
Anders Carlsson851853d2010-03-29 02:38:51 +00001476 if (CodeGenVTables::needsVTTParameter(CurGD) &&
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001477 (RD->getNumVBases() || NearestVBase)) {
Anders Carlssonc83f1062010-03-29 01:08:49 +00001478 // Get the secondary vpointer index.
1479 uint64_t VirtualPointerIndex =
1480 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base);
1481
1482 /// Load the VTT.
1483 llvm::Value *VTT = LoadCXXVTT();
1484 if (VirtualPointerIndex)
1485 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex);
1486
1487 // And load the address point from the VTT.
1488 VTableAddressPoint = Builder.CreateLoad(VTT);
1489 } else {
Peter Collingbourne84fcc482011-09-26 01:56:41 +00001490 uint64_t AddressPoint =
Peter Collingbournee09cdf42011-09-26 01:56:50 +00001491 CGM.getVTableContext().getVTableLayout(VTableClass).getAddressPoint(Base);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001492 VTableAddressPoint =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001493 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint);
Anders Carlssonc83f1062010-03-29 01:08:49 +00001494 }
Anders Carlssond103f9f2010-03-28 19:40:00 +00001495
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001496 // Compute where to store the address point.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001497 llvm::Value *VirtualOffset = 0;
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001498 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001499
1500 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) {
1501 // We need to use the virtual base offset offset because the virtual base
1502 // might have a different offset in the most derived class.
Anders Carlsson8246cc72010-05-03 00:29:58 +00001503 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass,
1504 NearestVBase);
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001505 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson3e79c302010-04-20 18:05:10 +00001506 } else {
Anders Carlsson8246cc72010-05-03 00:29:58 +00001507 // We can just use the base offset in the complete class.
Ken Dyck4230d522011-03-24 01:21:01 +00001508 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson3e79c302010-04-20 18:05:10 +00001509 }
Anders Carlsson8246cc72010-05-03 00:29:58 +00001510
1511 // Apply the offsets.
1512 llvm::Value *VTableField = LoadCXXThis();
1513
Ken Dyck9a8ad9b2011-03-23 00:45:26 +00001514 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlsson8246cc72010-05-03 00:29:58 +00001515 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1516 NonVirtualOffset,
1517 VirtualOffset);
Anders Carlsson36fd6be2010-04-20 16:22:16 +00001518
Anders Carlssond103f9f2010-03-28 19:40:00 +00001519 // Finally, store the address point.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001520 llvm::Type *AddressPointPtrTy =
Anders Carlssond103f9f2010-03-28 19:40:00 +00001521 VTableAddressPoint->getType()->getPointerTo();
1522 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001523 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1524 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssond103f9f2010-03-28 19:40:00 +00001525}
1526
Anders Carlsson603d6d12010-03-28 21:07:49 +00001527void
1528CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001529 const CXXRecordDecl *NearestVBase,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001530 CharUnits OffsetFromNearestVBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001531 bool BaseIsNonVirtualPrimaryBase,
1532 llvm::Constant *VTable,
1533 const CXXRecordDecl *VTableClass,
1534 VisitedVirtualBasesSetTy& VBases) {
1535 // If this base is a non-virtual primary base the address point has already
1536 // been set.
1537 if (!BaseIsNonVirtualPrimaryBase) {
1538 // Initialize the vtable pointer for this base.
Anders Carlsson42358402010-05-03 00:07:07 +00001539 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
1540 VTable, VTableClass);
Anders Carlsson603d6d12010-03-28 21:07:49 +00001541 }
1542
1543 const CXXRecordDecl *RD = Base.getBase();
1544
1545 // Traverse bases.
1546 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1547 E = RD->bases_end(); I != E; ++I) {
1548 CXXRecordDecl *BaseDecl
1549 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1550
1551 // Ignore classes without a vtable.
1552 if (!BaseDecl->isDynamicClass())
1553 continue;
1554
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001555 CharUnits BaseOffset;
1556 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson14da9de2010-03-29 01:16:41 +00001557 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001558
1559 if (I->isVirtual()) {
1560 // Check if we've visited this virtual base before.
1561 if (!VBases.insert(BaseDecl))
1562 continue;
1563
1564 const ASTRecordLayout &Layout =
1565 getContext().getASTRecordLayout(VTableClass);
1566
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001567 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1568 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson14da9de2010-03-29 01:16:41 +00001569 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001570 } else {
1571 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1572
Ken Dyck4230d522011-03-24 01:21:01 +00001573 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson42358402010-05-03 00:07:07 +00001574 BaseOffsetFromNearestVBase =
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001575 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson14da9de2010-03-29 01:16:41 +00001576 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlsson603d6d12010-03-28 21:07:49 +00001577 }
1578
Ken Dyck4230d522011-03-24 01:21:01 +00001579 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlssonb3b772e2010-04-20 05:22:15 +00001580 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlsson42358402010-05-03 00:07:07 +00001581 BaseOffsetFromNearestVBase,
Anders Carlsson14da9de2010-03-29 01:16:41 +00001582 BaseDeclIsNonVirtualPrimaryBase,
Anders Carlsson603d6d12010-03-28 21:07:49 +00001583 VTable, VTableClass, VBases);
1584 }
1585}
1586
1587void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1588 // Ignore classes without a vtable.
Anders Carlsson07036902010-03-26 04:39:42 +00001589 if (!RD->isDynamicClass())
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001590 return;
1591
Anders Carlsson07036902010-03-26 04:39:42 +00001592 // Get the VTable.
1593 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD);
Anders Carlsson5c6c1d92010-03-24 03:57:14 +00001594
Anders Carlsson603d6d12010-03-28 21:07:49 +00001595 // Initialize the vtable pointers for this class and all of its bases.
1596 VisitedVirtualBasesSetTy VBases;
Ken Dyck4230d522011-03-24 01:21:01 +00001597 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1598 /*NearestVBase=*/0,
Ken Dyckd6fb21f2011-03-23 01:04:18 +00001599 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Anders Carlsson603d6d12010-03-28 21:07:49 +00001600 /*BaseIsNonVirtualPrimaryBase=*/false,
1601 VTable, RD, VBases);
Anders Carlsson3b5ad222010-01-01 20:29:01 +00001602}
Dan Gohman043fb9a2010-10-26 18:44:08 +00001603
1604llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001605 llvm::Type *Ty) {
Dan Gohman043fb9a2010-10-26 18:44:08 +00001606 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany8cb4a072012-03-26 17:03:51 +00001607 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
1608 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
1609 return VTable;
Dan Gohman043fb9a2010-10-26 18:44:08 +00001610}
Anders Carlssona2447e02011-05-08 20:32:23 +00001611
1612static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) {
1613 const Expr *E = Base;
1614
1615 while (true) {
1616 E = E->IgnoreParens();
1617 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1618 if (CE->getCastKind() == CK_DerivedToBase ||
1619 CE->getCastKind() == CK_UncheckedDerivedToBase ||
1620 CE->getCastKind() == CK_NoOp) {
1621 E = CE->getSubExpr();
1622 continue;
1623 }
1624 }
1625
1626 break;
1627 }
1628
1629 QualType DerivedType = E->getType();
1630 if (const PointerType *PTy = DerivedType->getAs<PointerType>())
1631 DerivedType = PTy->getPointeeType();
1632
1633 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl());
1634}
1635
1636// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1637// quite what we want.
1638static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1639 while (true) {
1640 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1641 E = PE->getSubExpr();
1642 continue;
1643 }
1644
1645 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1646 if (CE->getCastKind() == CK_NoOp) {
1647 E = CE->getSubExpr();
1648 continue;
1649 }
1650 }
1651 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1652 if (UO->getOpcode() == UO_Extension) {
1653 E = UO->getSubExpr();
1654 continue;
1655 }
1656 }
1657 return E;
1658 }
1659}
1660
1661/// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member
1662/// function call on the given expr can be devirtualized.
Anders Carlssona2447e02011-05-08 20:32:23 +00001663static bool canDevirtualizeMemberFunctionCall(const Expr *Base,
1664 const CXXMethodDecl *MD) {
1665 // If the most derived class is marked final, we know that no subclass can
1666 // override this member function and so we can devirtualize it. For example:
1667 //
1668 // struct A { virtual void f(); }
1669 // struct B final : A { };
1670 //
1671 // void f(B *b) {
1672 // b->f();
1673 // }
1674 //
1675 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base);
1676 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
1677 return true;
1678
1679 // If the member function is marked 'final', we know that it can't be
1680 // overridden and can therefore devirtualize it.
1681 if (MD->hasAttr<FinalAttr>())
1682 return true;
1683
1684 // Similarly, if the class itself is marked 'final' it can't be overridden
1685 // and we can therefore devirtualize the member function call.
1686 if (MD->getParent()->hasAttr<FinalAttr>())
1687 return true;
1688
1689 Base = skipNoOpCastsAndParens(Base);
1690 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
1691 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
1692 // This is a record decl. We know the type and can devirtualize it.
1693 return VD->getType()->isRecordType();
1694 }
1695
1696 return false;
1697 }
1698
1699 // We can always devirtualize calls on temporary object expressions.
1700 if (isa<CXXConstructExpr>(Base))
1701 return true;
1702
1703 // And calls on bound temporaries.
1704 if (isa<CXXBindTemporaryExpr>(Base))
1705 return true;
1706
1707 // Check if this is a call expr that returns a record type.
1708 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
1709 return CE->getCallReturnType()->isRecordType();
1710
1711 // We can't devirtualize the call.
1712 return false;
1713}
1714
1715static bool UseVirtualCall(ASTContext &Context,
1716 const CXXOperatorCallExpr *CE,
1717 const CXXMethodDecl *MD) {
1718 if (!MD->isVirtual())
1719 return false;
1720
1721 // When building with -fapple-kext, all calls must go through the vtable since
1722 // the kernel linker can do runtime patching of vtables.
David Blaikie4e4d0842012-03-11 07:00:24 +00001723 if (Context.getLangOpts().AppleKext)
Anders Carlssona2447e02011-05-08 20:32:23 +00001724 return true;
1725
1726 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD);
1727}
1728
1729llvm::Value *
1730CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
1731 const CXXMethodDecl *MD,
1732 llvm::Value *This) {
John McCallde5d3c72012-02-17 03:33:10 +00001733 llvm::FunctionType *fnType =
1734 CGM.getTypes().GetFunctionType(
1735 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssona2447e02011-05-08 20:32:23 +00001736
1737 if (UseVirtualCall(getContext(), E, MD))
John McCallde5d3c72012-02-17 03:33:10 +00001738 return BuildVirtualCall(MD, This, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001739
John McCallde5d3c72012-02-17 03:33:10 +00001740 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssona2447e02011-05-08 20:32:23 +00001741}
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001742
Eli Friedman64bee652012-02-25 02:48:22 +00001743void CodeGenFunction::EmitForwardingCallToLambda(const CXXRecordDecl *Lambda,
1744 CallArgList &CallArgs) {
1745 // Lookup the call operator
Eli Friedman21f6ed92012-02-16 03:47:28 +00001746 DeclarationName Name
1747 = getContext().DeclarationNames.getCXXOperatorName(OO_Call);
1748 DeclContext::lookup_const_result Calls = Lambda->lookup(Name);
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001749 CXXMethodDecl *CallOperator = cast<CXXMethodDecl>(*Calls.first++);
Eli Friedman64bee652012-02-25 02:48:22 +00001750 const FunctionProtoType *FPT =
1751 CallOperator->getType()->getAs<FunctionProtoType>();
Eli Friedman21f6ed92012-02-16 03:47:28 +00001752 QualType ResultType = FPT->getResultType();
1753
Eli Friedman21f6ed92012-02-16 03:47:28 +00001754 // Get the address of the call operator.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001755 GlobalDecl GD(CallOperator);
John McCallde5d3c72012-02-17 03:33:10 +00001756 const CGFunctionInfo &CalleeFnInfo =
1757 CGM.getTypes().arrangeFunctionCall(ResultType, CallArgs, FPT->getExtInfo(),
1758 RequiredArgs::forPrototypePlus(FPT, 1));
1759 llvm::Type *Ty = CGM.getTypes().GetFunctionType(CalleeFnInfo);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001760 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty);
1761
1762 // Determine whether we have a return value slot to use.
1763 ReturnValueSlot Slot;
1764 if (!ResultType->isVoidType() &&
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001765 CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect &&
Eli Friedman21f6ed92012-02-16 03:47:28 +00001766 hasAggregateLLVMType(CurFnInfo->getReturnType()))
1767 Slot = ReturnValueSlot(ReturnValue, ResultType.isVolatileQualified());
1768
1769 // Now emit our call.
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001770 RValue RV = EmitCall(CalleeFnInfo, Callee, Slot, CallArgs, CallOperator);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001771
1772 // Forward the returned value
1773 if (!ResultType->isVoidType() && Slot.isNull())
1774 EmitReturnOfRValue(RV, ResultType);
Eli Friedman21f6ed92012-02-16 03:47:28 +00001775}
1776
Eli Friedman64bee652012-02-25 02:48:22 +00001777void CodeGenFunction::EmitLambdaBlockInvokeBody() {
1778 const BlockDecl *BD = BlockInfo->getBlockDecl();
1779 const VarDecl *variable = BD->capture_begin()->getVariable();
1780 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
1781
1782 // Start building arguments for forwarding call
1783 CallArgList CallArgs;
1784
1785 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1786 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
1787 CallArgs.add(RValue::get(ThisPtr), ThisType);
1788
1789 // Add the rest of the parameters.
1790 for (BlockDecl::param_const_iterator I = BD->param_begin(),
1791 E = BD->param_end(); I != E; ++I) {
1792 ParmVarDecl *param = *I;
1793 EmitDelegateCallArg(CallArgs, param);
1794 }
1795
1796 EmitForwardingCallToLambda(Lambda, CallArgs);
1797}
1798
1799void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
1800 if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
1801 // FIXME: Making this work correctly is nasty because it requires either
1802 // cloning the body of the call operator or making the call operator forward.
1803 CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
1804 return;
1805 }
1806
Eli Friedman64bee652012-02-25 02:48:22 +00001807 EmitFunctionBody(Args);
Eli Friedman64bee652012-02-25 02:48:22 +00001808}
1809
1810void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
1811 const CXXRecordDecl *Lambda = MD->getParent();
1812
1813 // Start building arguments for forwarding call
1814 CallArgList CallArgs;
1815
1816 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
1817 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
1818 CallArgs.add(RValue::get(ThisPtr), ThisType);
1819
1820 // Add the rest of the parameters.
1821 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
1822 E = MD->param_end(); I != E; ++I) {
1823 ParmVarDecl *param = *I;
1824 EmitDelegateCallArg(CallArgs, param);
1825 }
1826
1827 EmitForwardingCallToLambda(Lambda, CallArgs);
1828}
1829
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001830void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
1831 if (MD->isVariadic()) {
Eli Friedman21f6ed92012-02-16 03:47:28 +00001832 // FIXME: Making this work correctly is nasty because it requires either
1833 // cloning the body of the call operator or making the call operator forward.
1834 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman64bee652012-02-25 02:48:22 +00001835 return;
Eli Friedman21f6ed92012-02-16 03:47:28 +00001836 }
1837
Douglas Gregor27dd7d92012-02-17 03:02:34 +00001838 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedmanbd89f8c2012-02-16 01:37:33 +00001839}