blob: 7a0391b9b9cddbdd8a45ee6e596175e6dbfe84f2 [file] [log] [blame]
Anders Carlsson59486a22009-11-24 05:51:11 +00001//===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===//
Anders Carlsson9a57c5a2009-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 Friedman2495ab02012-02-25 02:48:22 +000014#include "CGBlocks.h"
Devang Pateld76c1db2010-08-11 21:04:37 +000015#include "CGDebugInfo.h"
Lang Hamesbf122742013-02-17 07:22:09 +000016#include "CGRecordLayout.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000017#include "CodeGenFunction.h"
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +000018#include "CGCXXABI.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000019#include "clang/AST/CXXInheritance.h"
Faisal Vali571df122013-09-29 08:45:24 +000020#include "clang/AST/DeclTemplate.h"
John McCall769250e2010-09-17 02:31:44 +000021#include "clang/AST/EvaluatedExprVisitor.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000022#include "clang/AST/RecordLayout.h"
John McCallb81884d2010-02-19 09:25:03 +000023#include "clang/AST/StmtCXX.h"
Lang Hamesbf122742013-02-17 07:22:09 +000024#include "clang/Basic/TargetBuiltins.h"
Mark Laceya8e7df32013-10-30 21:53:58 +000025#include "clang/CodeGen/CGFunctionInfo.h"
Devang Patelb6ed3692011-02-22 20:55:26 +000026#include "clang/Frontend/CodeGenOptions.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000027
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000028using namespace clang;
29using namespace CodeGen;
30
Ken Dycka1a4ae32011-03-22 00:53:26 +000031static CharUnits
Anders Carlssond829a022010-04-24 21:06:20 +000032ComputeNonVirtualBaseClassOffset(ASTContext &Context,
33 const CXXRecordDecl *DerivedClass,
John McCallcf142162010-08-07 06:22:56 +000034 CastExpr::path_const_iterator Start,
35 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +000036 CharUnits Offset = CharUnits::Zero();
Anders Carlssond829a022010-04-24 21:06:20 +000037
38 const CXXRecordDecl *RD = DerivedClass;
39
John McCallcf142162010-08-07 06:22:56 +000040 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +000041 const CXXBaseSpecifier *Base = *I;
42 assert(!Base->isVirtual() && "Should not see virtual bases here!");
43
44 // Get the layout.
45 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
46
47 const CXXRecordDecl *BaseDecl =
48 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
49
50 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +000051 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlssond829a022010-04-24 21:06:20 +000052
53 RD = BaseDecl;
54 }
55
Ken Dycka1a4ae32011-03-22 00:53:26 +000056 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +000057}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000058
Anders Carlsson9150a2a2009-09-29 03:13:20 +000059llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000060CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +000061 CastExpr::path_const_iterator PathBegin,
62 CastExpr::path_const_iterator PathEnd) {
63 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000064
Ken Dycka1a4ae32011-03-22 00:53:26 +000065 CharUnits Offset =
John McCallcf142162010-08-07 06:22:56 +000066 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
67 PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +000068 if (Offset.isZero())
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000069 return 0;
70
Chris Lattner2192fe52011-07-18 04:24:23 +000071 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000072 Types.ConvertType(getContext().getPointerDiffType());
73
Ken Dycka1a4ae32011-03-22 00:53:26 +000074 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +000075}
76
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000077/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +000078/// This should only be used for (1) non-virtual bases or (2) virtual bases
79/// when the type is known to be complete (e.g. in complete destructors).
80///
81/// The object pointed to by 'This' is assumed to be non-null.
82llvm::Value *
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000083CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
84 const CXXRecordDecl *Derived,
85 const CXXRecordDecl *Base,
86 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +000087 // 'this' must be a pointer (in some address space) to Derived.
88 assert(This->getType()->isPointerTy() &&
89 cast<llvm::PointerType>(This->getType())->getElementType()
90 == ConvertType(Derived));
91
92 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +000093 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +000094 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000095 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +000096 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000097 else
Ken Dyck6aa767c2011-03-22 01:21:15 +000098 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000099
100 // Shift and cast down to the base type.
101 // TODO: for complete types, this should be possible with a GEP.
102 llvm::Value *V = This;
Ken Dyck6aa767c2011-03-22 01:21:15 +0000103 if (Offset.isPositive()) {
John McCall6ce74722010-02-16 04:15:37 +0000104 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +0000105 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000106 }
107 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
108
109 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000110}
John McCall6ce74722010-02-16 04:15:37 +0000111
Anders Carlsson53cebd12010-04-20 16:03:35 +0000112static llvm::Value *
John McCall13a39c62012-08-01 05:04:58 +0000113ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
114 CharUnits nonVirtualOffset,
115 llvm::Value *virtualOffset) {
116 // Assert that we have something to do.
117 assert(!nonVirtualOffset.isZero() || virtualOffset != 0);
118
119 // Compute the offset from the static and dynamic components.
120 llvm::Value *baseOffset;
121 if (!nonVirtualOffset.isZero()) {
122 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
123 nonVirtualOffset.getQuantity());
124 if (virtualOffset) {
125 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
126 }
127 } else {
128 baseOffset = virtualOffset;
129 }
Anders Carlsson53cebd12010-04-20 16:03:35 +0000130
131 // Apply the base offset.
John McCall13a39c62012-08-01 05:04:58 +0000132 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
133 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
134 return ptr;
Anders Carlsson53cebd12010-04-20 16:03:35 +0000135}
136
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000137llvm::Value *
Anders Carlssond829a022010-04-24 21:06:20 +0000138CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000139 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000140 CastExpr::path_const_iterator PathBegin,
141 CastExpr::path_const_iterator PathEnd,
Anders Carlssond829a022010-04-24 21:06:20 +0000142 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000143 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000144
John McCallcf142162010-08-07 06:22:56 +0000145 CastExpr::path_const_iterator Start = PathBegin;
Anders Carlssond829a022010-04-24 21:06:20 +0000146 const CXXRecordDecl *VBase = 0;
147
John McCall13a39c62012-08-01 05:04:58 +0000148 // Sema has done some convenient canonicalization here: if the
149 // access path involved any virtual steps, the conversion path will
150 // *start* with a step down to the correct virtual base subobject,
151 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000152 if ((*Start)->isVirtual()) {
153 VBase =
154 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
155 ++Start;
156 }
John McCall13a39c62012-08-01 05:04:58 +0000157
158 // Compute the static offset of the ultimate destination within its
159 // allocating subobject (the virtual base, if there is one, or else
160 // the "complete" object that we see).
Ken Dycka1a4ae32011-03-22 00:53:26 +0000161 CharUnits NonVirtualOffset =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000162 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived,
John McCallcf142162010-08-07 06:22:56 +0000163 Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000164
John McCall13a39c62012-08-01 05:04:58 +0000165 // If there's a virtual step, we can sometimes "devirtualize" it.
166 // For now, that's limited to when the derived type is final.
167 // TODO: "devirtualize" this for accesses to known-complete objects.
168 if (VBase && Derived->hasAttr<FinalAttr>()) {
169 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
170 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
171 NonVirtualOffset += vBaseOffset;
172 VBase = 0; // we no longer have a virtual step
173 }
174
Anders Carlssond829a022010-04-24 21:06:20 +0000175 // Get the base pointer type.
Chris Lattner2192fe52011-07-18 04:24:23 +0000176 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000177 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000178
179 // If the static offset is zero and we don't have a virtual step,
180 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000181 if (NonVirtualOffset.isZero() && !VBase) {
Anders Carlssond829a022010-04-24 21:06:20 +0000182 return Builder.CreateBitCast(Value, BasePtrTy);
183 }
John McCall13a39c62012-08-01 05:04:58 +0000184
185 llvm::BasicBlock *origBB = 0;
186 llvm::BasicBlock *endBB = 0;
Anders Carlssond829a022010-04-24 21:06:20 +0000187
John McCall13a39c62012-08-01 05:04:58 +0000188 // Skip over the offset (and the vtable load) if we're supposed to
189 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000190 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000191 origBB = Builder.GetInsertBlock();
192 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
193 endBB = createBasicBlock("cast.end");
Anders Carlssond829a022010-04-24 21:06:20 +0000194
John McCall13a39c62012-08-01 05:04:58 +0000195 llvm::Value *isNull = Builder.CreateIsNull(Value);
196 Builder.CreateCondBr(isNull, endBB, notNullBB);
197 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000198 }
199
John McCall13a39c62012-08-01 05:04:58 +0000200 // Compute the virtual offset.
Anders Carlssond829a022010-04-24 21:06:20 +0000201 llvm::Value *VirtualOffset = 0;
Anders Carlssona376b532011-01-29 03:18:56 +0000202 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000203 VirtualOffset =
204 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000205 }
Anders Carlssond829a022010-04-24 21:06:20 +0000206
John McCall13a39c62012-08-01 05:04:58 +0000207 // Apply both offsets.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000208 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000209 NonVirtualOffset,
Anders Carlssond829a022010-04-24 21:06:20 +0000210 VirtualOffset);
211
John McCall13a39c62012-08-01 05:04:58 +0000212 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000213 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000214
215 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000216 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000217 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
218 Builder.CreateBr(endBB);
219 EmitBlock(endBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000220
John McCall13a39c62012-08-01 05:04:58 +0000221 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
222 PHI->addIncoming(Value, notNullBB);
223 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000224 Value = PHI;
225 }
226
227 return Value;
228}
229
230llvm::Value *
Anders Carlsson8c793172009-11-23 17:57:54 +0000231CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000232 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000233 CastExpr::path_const_iterator PathBegin,
234 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000235 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000236 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000237
Anders Carlsson8c793172009-11-23 17:57:54 +0000238 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000239 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000240 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000241
Anders Carlsson600f7372010-01-31 01:43:37 +0000242 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000243 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlsson600f7372010-01-31 01:43:37 +0000244
245 if (!NonVirtualOffset) {
246 // No offset, we can just cast back.
247 return Builder.CreateBitCast(Value, DerivedPtrTy);
248 }
249
Anders Carlsson8c793172009-11-23 17:57:54 +0000250 llvm::BasicBlock *CastNull = 0;
251 llvm::BasicBlock *CastNotNull = 0;
252 llvm::BasicBlock *CastEnd = 0;
253
254 if (NullCheckValue) {
255 CastNull = createBasicBlock("cast.null");
256 CastNotNull = createBasicBlock("cast.notnull");
257 CastEnd = createBasicBlock("cast.end");
258
Anders Carlsson98981b12011-04-11 00:30:07 +0000259 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000260 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
261 EmitBlock(CastNotNull);
262 }
263
Anders Carlsson600f7372010-01-31 01:43:37 +0000264 // Apply the offset.
Eli Friedman87549262012-02-28 22:07:56 +0000265 Value = Builder.CreateBitCast(Value, Int8PtrTy);
266 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
267 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000268
269 // Just cast.
270 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000271
272 if (NullCheckValue) {
273 Builder.CreateBr(CastEnd);
274 EmitBlock(CastNull);
275 Builder.CreateBr(CastEnd);
276 EmitBlock(CastEnd);
277
Jay Foad20c0f022011-03-30 11:28:58 +0000278 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000279 PHI->addIncoming(Value, CastNotNull);
280 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
281 CastNull);
282 Value = PHI;
283 }
284
285 return Value;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000286}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000287
288llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
289 bool ForVirtualBase,
290 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000291 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000292 // This constructor/destructor does not need a VTT parameter.
293 return 0;
294 }
295
John McCalldec348f72013-05-03 07:33:41 +0000296 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000297 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000298
Anders Carlssone36a6b32010-01-02 01:01:18 +0000299 llvm::Value *VTT;
300
John McCall5c60a6f2010-02-18 19:59:28 +0000301 uint64_t SubVTTIndex;
302
Douglas Gregor61535002013-01-31 05:50:40 +0000303 if (Delegating) {
304 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000305 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000306 } else if (RD == Base) {
307 // If the record matches the base, this is the complete ctor/dtor
308 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000309 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000310 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000311 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000312 SubVTTIndex = 0;
313 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000314 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck16ffcac2011-03-24 01:21:01 +0000315 CharUnits BaseOffset = ForVirtualBase ?
316 Layout.getVBaseClassOffset(Base) :
317 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000318
319 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000320 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000321 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
322 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000323
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000324 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000325 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000326 VTT = LoadCXXVTT();
327 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000328 } else {
329 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000330 VTT = CGM.getVTables().GetAddrOfVTT(RD);
331 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000332 }
333
334 return VTT;
335}
336
John McCall1d987562010-07-21 01:23:41 +0000337namespace {
John McCallf99a6312010-07-21 05:30:47 +0000338 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000339 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000340 const CXXRecordDecl *BaseClass;
341 bool BaseIsVirtual;
342 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
343 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000344
John McCall30317fd2011-07-12 20:27:29 +0000345 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +0000346 const CXXRecordDecl *DerivedClass =
347 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
348
349 const CXXDestructorDecl *D = BaseClass->getDestructor();
350 llvm::Value *Addr =
351 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
352 DerivedClass, BaseClass,
353 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000354 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
355 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000356 }
357 };
John McCall769250e2010-09-17 02:31:44 +0000358
359 /// A visitor which checks whether an initializer uses 'this' in a
360 /// way which requires the vtable to be properly set.
361 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
362 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
363
364 bool UsesThis;
365
366 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
367
368 // Black-list all explicit and implicit references to 'this'.
369 //
370 // Do we need to worry about external references to 'this' derived
371 // from arbitrary code? If so, then anything which runs arbitrary
372 // external code might potentially access the vtable.
373 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
374 };
375}
376
377static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
378 DynamicThisUseChecker Checker(C);
379 Checker.Visit(const_cast<Expr*>(Init));
380 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000381}
382
Anders Carlssonfb404882009-12-24 22:46:43 +0000383static void EmitBaseInitializer(CodeGenFunction &CGF,
384 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000385 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000386 CXXCtorType CtorType) {
387 assert(BaseInit->isBaseInitializer() &&
388 "Must have base initializer!");
389
390 llvm::Value *ThisPtr = CGF.LoadCXXThis();
391
392 const Type *BaseType = BaseInit->getBaseClass();
393 CXXRecordDecl *BaseClassDecl =
394 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
395
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000396 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000397
398 // The base constructor doesn't construct virtual bases.
399 if (CtorType == Ctor_Base && isBaseVirtual)
400 return;
401
John McCall769250e2010-09-17 02:31:44 +0000402 // If the initializer for the base (other than the constructor
403 // itself) accesses 'this' in any way, we need to initialize the
404 // vtables.
405 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
406 CGF.InitializeVTablePointers(ClassDecl);
407
John McCall6ce74722010-02-16 04:15:37 +0000408 // We can pretend to be a complete class because it only matters for
409 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000410 llvm::Value *V =
411 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000412 BaseClassDecl,
413 isBaseVirtual);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000414 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall8d6fc952011-08-25 20:40:09 +0000415 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000416 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000417 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000418 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000419 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000420
421 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000422
David Blaikiebbafb8a2012-03-11 07:00:24 +0000423 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000424 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000425 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
426 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000427}
428
Douglas Gregor94f9a482010-05-05 05:51:00 +0000429static void EmitAggMemberInitializer(CodeGenFunction &CGF,
430 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000431 Expr *Init,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000432 llvm::Value *ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000433 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000434 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000435 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000436 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000437 LValue LV = LHS;
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000438
Richard Smithcc1b96d2013-06-12 22:31:48 +0000439 if (ArrayIndexVar) {
440 // If we have an array index variable, load it and use it as an offset.
441 // Then, increment the value.
442 llvm::Value *Dest = LHS.getAddress();
443 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
444 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
445 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
446 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
447 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000448
Richard Smithcc1b96d2013-06-12 22:31:48 +0000449 // Update the LValue.
450 LV.setAddress(Dest);
451 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
452 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000453 }
John McCall7a626f62010-09-15 10:14:12 +0000454
Richard Smithcc1b96d2013-06-12 22:31:48 +0000455 switch (CGF.getEvaluationKind(T)) {
456 case TEK_Scalar:
457 CGF.EmitScalarInit(Init, /*decl*/ 0, LV, false);
458 break;
459 case TEK_Complex:
460 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
461 break;
462 case TEK_Aggregate: {
463 AggValueSlot Slot =
464 AggValueSlot::forLValue(LV,
465 AggValueSlot::IsDestructed,
466 AggValueSlot::DoesNotNeedGCBarriers,
467 AggValueSlot::IsNotAliased);
468
469 CGF.EmitAggExpr(Init, Slot);
470 break;
471 }
472 }
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000473
Douglas Gregor94f9a482010-05-05 05:51:00 +0000474 return;
475 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000476
Douglas Gregor94f9a482010-05-05 05:51:00 +0000477 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
478 assert(Array && "Array initialization without the array type?");
479 llvm::Value *IndexVar
Eli Friedman6ae63022012-02-14 02:15:49 +0000480 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000481 assert(IndexVar && "Array index variable not loaded");
482
483 // Initialize this index variable to zero.
484 llvm::Value* Zero
485 = llvm::Constant::getNullValue(
486 CGF.ConvertType(CGF.getContext().getSizeType()));
487 CGF.Builder.CreateStore(Zero, IndexVar);
488
489 // Start the loop with a block that tests the condition.
490 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
491 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
492
493 CGF.EmitBlock(CondBlock);
494
495 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
496 // Generate: if (loop-index < number-of-elements) fall to the loop body,
497 // otherwise, go to the block after the for-loop.
498 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000499 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000500 llvm::Value *NumElementsPtr =
501 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000502 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
503 "isless");
504
505 // If the condition is true, execute the body.
506 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
507
508 CGF.EmitBlock(ForBody);
509 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000510
511 // Inside the loop body recurse to emit the inner loop or, eventually, the
512 // constructor call.
513 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
514 Array->getElementType(), ArrayIndexes, Index + 1);
515
Douglas Gregor94f9a482010-05-05 05:51:00 +0000516 CGF.EmitBlock(ContinueBlock);
517
518 // Emit the increment of the loop counter.
519 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
520 Counter = CGF.Builder.CreateLoad(IndexVar);
521 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
522 CGF.Builder.CreateStore(NextVal, IndexVar);
523
524 // Finally, branch back up to the condition for the next iteration.
525 CGF.EmitBranch(CondBlock);
526
527 // Emit the fall-through block.
528 CGF.EmitBlock(AfterFor, true);
529}
John McCall1d987562010-07-21 01:23:41 +0000530
Anders Carlssonfb404882009-12-24 22:46:43 +0000531static void EmitMemberInitializer(CodeGenFunction &CGF,
532 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000533 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000534 const CXXConstructorDecl *Constructor,
535 FunctionArgList &Args) {
Francois Pichetd583da02010-12-04 09:14:42 +0000536 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000537 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000538 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlssonfb404882009-12-24 22:46:43 +0000539
540 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000541 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000542 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000543
544 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000545 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000546 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000547
Francois Pichetd583da02010-12-04 09:14:42 +0000548 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000549 // If we are initializing an anonymous union field, drill down to
550 // the field.
551 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
552 IndirectFieldDecl::chain_iterator I = IndirectField->chain_begin(),
553 IEnd = IndirectField->chain_end();
554 for ( ; I != IEnd; ++I)
555 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(*I));
Francois Pichetd583da02010-12-04 09:14:42 +0000556 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000557 } else {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000558 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlssonfb404882009-12-24 22:46:43 +0000559 }
560
Eli Friedman6ae63022012-02-14 02:15:49 +0000561 // Special case: if we are in a copy or move constructor, and we are copying
562 // an array of PODs or classes with trivial copy constructors, ignore the
563 // AST and perform the copy we know is equivalent.
564 // FIXME: This is hacky at best... if we had a bit more explicit information
565 // in the AST, we could generalize it more easily.
566 const ConstantArrayType *Array
567 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000568 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000569 Constructor->isCopyOrMoveConstructor()) {
570 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000571 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000572 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith993f25a2012-11-07 23:56:21 +0000573 (CE && CE->getConstructor()->isTrivial())) {
574 // Find the source pointer. We know it's the last argument because
575 // we know we're in an implicit copy constructor.
Eli Friedman6ae63022012-02-14 02:15:49 +0000576 unsigned SrcArgIndex = Args.size() - 1;
577 llvm::Value *SrcPtr
578 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000579 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
580 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman6ae63022012-02-14 02:15:49 +0000581
582 // Copy the aggregate.
583 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000584 LHS.isVolatileQualified());
Eli Friedman6ae63022012-02-14 02:15:49 +0000585 return;
586 }
587 }
588
589 ArrayRef<VarDecl *> ArrayIndexes;
590 if (MemberInit->getNumArrayIndices())
591 ArrayIndexes = MemberInit->getArrayIndexes();
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000592 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000593}
594
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000595void CodeGenFunction::EmitInitializerForField(FieldDecl *Field,
596 LValue LHS, Expr *Init,
597 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000598 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000599 switch (getEvaluationKind(FieldType)) {
600 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000601 if (LHS.isSimple()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000602 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000603 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000604 RValue RHS = RValue::get(EmitScalarExpr(Init));
605 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000606 }
John McCall47fb9502013-03-07 21:37:08 +0000607 break;
608 case TEK_Complex:
609 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
610 break;
611 case TEK_Aggregate: {
Douglas Gregor94f9a482010-05-05 05:51:00 +0000612 llvm::Value *ArrayIndexVar = 0;
Eli Friedman6ae63022012-02-14 02:15:49 +0000613 if (ArrayIndexes.size()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000614 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregor94f9a482010-05-05 05:51:00 +0000615
616 // The LHS is a pointer to the first object we'll be constructing, as
617 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000618 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
619 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000620 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000621 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
622 BasePtr);
623 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000624
625 // Create an array index that will be used to walk over all of the
626 // objects we're constructing.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000627 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregor94f9a482010-05-05 05:51:00 +0000628 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000629 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000630
Douglas Gregor94f9a482010-05-05 05:51:00 +0000631
632 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000633 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000634 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000635 }
636
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000637 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000638 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000639 }
John McCall47fb9502013-03-07 21:37:08 +0000640 }
John McCall12cc42a2013-02-01 05:11:40 +0000641
642 // Ensure that we destroy this object if an exception is thrown
643 // later in the constructor.
644 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
645 if (needsEHCleanup(dtorKind))
646 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000647}
648
John McCallf8ff7b92010-02-23 00:48:20 +0000649/// Checks whether the given constructor is a valid subject for the
650/// complete-to-base constructor delegation optimization, i.e.
651/// emitting the complete constructor as a simple call to the base
652/// constructor.
653static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
654
655 // Currently we disable the optimization for classes with virtual
656 // bases because (1) the addresses of parameter variables need to be
657 // consistent across all initializers but (2) the delegate function
658 // call necessarily creates a second copy of the parameter variable.
659 //
660 // The limiting example (purely theoretical AFAIK):
661 // struct A { A(int &c) { c++; } };
662 // struct B : virtual A {
663 // B(int count) : A(count) { printf("%d\n", count); }
664 // };
665 // ...although even this example could in principle be emitted as a
666 // delegation since the address of the parameter doesn't escape.
667 if (Ctor->getParent()->getNumVBases()) {
668 // TODO: white-list trivial vbase initializers. This case wouldn't
669 // be subject to the restrictions below.
670
671 // TODO: white-list cases where:
672 // - there are no non-reference parameters to the constructor
673 // - the initializers don't access any non-reference parameters
674 // - the initializers don't take the address of non-reference
675 // parameters
676 // - etc.
677 // If we ever add any of the above cases, remember that:
678 // - function-try-blocks will always blacklist this optimization
679 // - we need to perform the constructor prologue and cleanup in
680 // EmitConstructorBody.
681
682 return false;
683 }
684
685 // We also disable the optimization for variadic functions because
686 // it's impossible to "re-pass" varargs.
687 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
688 return false;
689
Alexis Hunt61bc1732011-05-01 07:04:31 +0000690 // FIXME: Decide if we can do a delegation of a delegating constructor.
691 if (Ctor->isDelegatingConstructor())
692 return false;
693
John McCallf8ff7b92010-02-23 00:48:20 +0000694 return true;
695}
696
John McCallb81884d2010-02-19 09:25:03 +0000697/// EmitConstructorBody - Emits the body of the current constructor.
698void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
699 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
700 CXXCtorType CtorType = CurGD.getCtorType();
701
John McCallf8ff7b92010-02-23 00:48:20 +0000702 // Before we go any further, try the complete->base constructor
703 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000704 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000705 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Devang Pateld76c1db2010-08-11 21:04:37 +0000706 if (CGDebugInfo *DI = getDebugInfo())
Eric Christopher7cdf9482011-10-13 21:45:18 +0000707 DI->EmitLocation(Builder, Ctor->getLocEnd());
Nick Lewycky2d84e842013-10-02 02:29:49 +0000708 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000709 return;
710 }
711
John McCallb81884d2010-02-19 09:25:03 +0000712 Stmt *Body = Ctor->getBody();
713
John McCallf8ff7b92010-02-23 00:48:20 +0000714 // Enter the function-try-block before the constructor prologue if
715 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000716 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000717 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000718 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000719
Richard Smithcc1b96d2013-06-12 22:31:48 +0000720 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000721
John McCall88313032012-03-30 04:25:03 +0000722 // TODO: in restricted cases, we can emit the vbase initializers of
723 // a complete ctor and then delegate to the base ctor.
724
John McCallf8ff7b92010-02-23 00:48:20 +0000725 // Emit the constructor prologue, i.e. the base and member
726 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000727 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000728
729 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000730 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000731 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
732 else if (Body)
733 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000734
735 // Emit any cleanup blocks associated with the member or base
736 // initializers, which includes (along the exceptional path) the
737 // destructors for those members and bases that were fully
738 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000739 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000740
John McCallf8ff7b92010-02-23 00:48:20 +0000741 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000742 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000743}
744
Lang Hamesbf122742013-02-17 07:22:09 +0000745namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000746 /// RAII object to indicate that codegen is copying the value representation
747 /// instead of the object representation. Useful when copying a struct or
748 /// class which has uninitialized members and we're only performing
749 /// lvalue-to-rvalue conversion on the object but not its members.
750 class CopyingValueRepresentation {
751 public:
752 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
753 : CGF(CGF), SO(*CGF.SanOpts), OldSanOpts(CGF.SanOpts) {
754 SO.Bool = false;
755 SO.Enum = false;
756 CGF.SanOpts = &SO;
757 }
758 ~CopyingValueRepresentation() {
759 CGF.SanOpts = OldSanOpts;
760 }
761 private:
762 CodeGenFunction &CGF;
763 SanitizerOptions SO;
764 const SanitizerOptions *OldSanOpts;
765 };
766}
767
768namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000769 class FieldMemcpyizer {
770 public:
771 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
772 const VarDecl *SrcRec)
773 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
774 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
775 FirstField(0), LastField(0), FirstFieldOffset(0), LastFieldOffset(0),
776 LastAddedFieldIndex(0) { }
777
778 static bool isMemcpyableField(FieldDecl *F) {
779 Qualifiers Qual = F->getType().getQualifiers();
780 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
781 return false;
782 return true;
783 }
784
785 void addMemcpyableField(FieldDecl *F) {
786 if (FirstField == 0)
787 addInitialField(F);
788 else
789 addNextField(F);
790 }
791
792 CharUnits getMemcpySize() const {
793 unsigned LastFieldSize =
794 LastField->isBitField() ?
795 LastField->getBitWidthValue(CGF.getContext()) :
796 CGF.getContext().getTypeSize(LastField->getType());
797 uint64_t MemcpySizeBits =
798 LastFieldOffset + LastFieldSize - FirstFieldOffset +
799 CGF.getContext().getCharWidth() - 1;
800 CharUnits MemcpySize =
801 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
802 return MemcpySize;
803 }
804
805 void emitMemcpy() {
806 // Give the subclass a chance to bail out if it feels the memcpy isn't
807 // worth it (e.g. Hasn't aggregated enough data).
808 if (FirstField == 0) {
809 return;
810 }
811
Lang Hames1694e0d2013-02-27 04:14:49 +0000812 CharUnits Alignment;
Lang Hamesbf122742013-02-17 07:22:09 +0000813
814 if (FirstField->isBitField()) {
815 const CGRecordLayout &RL =
816 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
817 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames1694e0d2013-02-27 04:14:49 +0000818 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
819 } else {
Lang Hames224ae882013-03-05 20:27:24 +0000820 Alignment = CGF.getContext().getDeclAlign(FirstField);
Lang Hames1694e0d2013-02-27 04:14:49 +0000821 }
Lang Hamesbf122742013-02-17 07:22:09 +0000822
Lang Hames1694e0d2013-02-27 04:14:49 +0000823 assert((CGF.getContext().toCharUnitsFromBits(FirstFieldOffset) %
824 Alignment) == 0 && "Bad field alignment.");
825
Lang Hamesbf122742013-02-17 07:22:09 +0000826 CharUnits MemcpySize = getMemcpySize();
827 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
828 llvm::Value *ThisPtr = CGF.LoadCXXThis();
829 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
830 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
831 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
832 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
833 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
834
835 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
836 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
837 MemcpySize, Alignment);
838 reset();
839 }
840
841 void reset() {
842 FirstField = 0;
843 }
844
845 protected:
846 CodeGenFunction &CGF;
847 const CXXRecordDecl *ClassDecl;
848
849 private:
850
851 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
852 CharUnits Size, CharUnits Alignment) {
853 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
854 llvm::Type *DBP =
855 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
856 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
857
858 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
859 llvm::Type *SBP =
860 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
861 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
862
863 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
864 Alignment.getQuantity());
865 }
866
867 void addInitialField(FieldDecl *F) {
868 FirstField = F;
869 LastField = F;
870 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
871 LastFieldOffset = FirstFieldOffset;
872 LastAddedFieldIndex = F->getFieldIndex();
873 return;
874 }
875
876 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000877 // For the most part, the following invariant will hold:
878 // F->getFieldIndex() == LastAddedFieldIndex + 1
879 // The one exception is that Sema won't add a copy-initializer for an
880 // unnamed bitfield, which will show up here as a gap in the sequence.
881 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
882 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000883 LastAddedFieldIndex = F->getFieldIndex();
884
885 // The 'first' and 'last' fields are chosen by offset, rather than field
886 // index. This allows the code to support bitfields, as well as regular
887 // fields.
888 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
889 if (FOffset < FirstFieldOffset) {
890 FirstField = F;
891 FirstFieldOffset = FOffset;
892 } else if (FOffset > LastFieldOffset) {
893 LastField = F;
894 LastFieldOffset = FOffset;
895 }
896 }
897
898 const VarDecl *SrcRec;
899 const ASTRecordLayout &RecLayout;
900 FieldDecl *FirstField;
901 FieldDecl *LastField;
902 uint64_t FirstFieldOffset, LastFieldOffset;
903 unsigned LastAddedFieldIndex;
904 };
905
906 class ConstructorMemcpyizer : public FieldMemcpyizer {
907 private:
908
909 /// Get source argument for copy constructor. Returns null if not a copy
910 /// constructor.
911 static const VarDecl* getTrivialCopySource(const CXXConstructorDecl *CD,
912 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +0000913 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
Lang Hamesbf122742013-02-17 07:22:09 +0000914 return Args[Args.size() - 1];
915 return 0;
916 }
917
918 // Returns true if a CXXCtorInitializer represents a member initialization
919 // that can be rolled into a memcpy.
920 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
921 if (!MemcpyableCtor)
922 return false;
923 FieldDecl *Field = MemberInit->getMember();
924 assert(Field != 0 && "No field for member init.");
925 QualType FieldType = Field->getType();
926 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
927
928 // Bail out on non-POD, not-trivially-constructable members.
929 if (!(CE && CE->getConstructor()->isTrivial()) &&
930 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
931 FieldType->isReferenceType()))
932 return false;
933
934 // Bail out on volatile fields.
935 if (!isMemcpyableField(Field))
936 return false;
937
938 // Otherwise we're good.
939 return true;
940 }
941
942 public:
943 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
944 FunctionArgList &Args)
945 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CD, Args)),
946 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +0000947 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +0000948 CD->isCopyOrMoveConstructor() &&
949 CGF.getLangOpts().getGC() == LangOptions::NonGC),
950 Args(Args) { }
951
952 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
953 if (isMemberInitMemcpyable(MemberInit)) {
954 AggregatedInits.push_back(MemberInit);
955 addMemcpyableField(MemberInit->getMember());
956 } else {
957 emitAggregatedInits();
958 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
959 ConstructorDecl, Args);
960 }
961 }
962
963 void emitAggregatedInits() {
964 if (AggregatedInits.size() <= 1) {
965 // This memcpy is too small to be worthwhile. Fall back on default
966 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000967 if (!AggregatedInits.empty()) {
968 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +0000969 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000970 AggregatedInits[0], ConstructorDecl, Args);
Lang Hamesbf122742013-02-17 07:22:09 +0000971 }
972 reset();
973 return;
974 }
975
976 pushEHDestructors();
977 emitMemcpy();
978 AggregatedInits.clear();
979 }
980
981 void pushEHDestructors() {
982 llvm::Value *ThisPtr = CGF.LoadCXXThis();
983 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
984 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
985
986 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
987 QualType FieldType = AggregatedInits[i]->getMember()->getType();
988 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
989 if (CGF.needsEHCleanup(dtorKind))
990 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
991 }
992 }
993
994 void finish() {
995 emitAggregatedInits();
996 }
997
998 private:
999 const CXXConstructorDecl *ConstructorDecl;
1000 bool MemcpyableCtor;
1001 FunctionArgList &Args;
1002 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1003 };
1004
1005 class AssignmentMemcpyizer : public FieldMemcpyizer {
1006 private:
1007
1008 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001009 // exists. Otherwise returns null.
1010 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001011 if (!AssignmentsMemcpyable)
1012 return 0;
1013 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1014 // Recognise trivial assignments.
1015 if (BO->getOpcode() != BO_Assign)
1016 return 0;
1017 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1018 if (!ME)
1019 return 0;
1020 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1021 if (!Field || !isMemcpyableField(Field))
1022 return 0;
1023 Stmt *RHS = BO->getRHS();
1024 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1025 RHS = EC->getSubExpr();
1026 if (!RHS)
1027 return 0;
1028 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1029 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
1030 return 0;
1031 return Field;
1032 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1033 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1034 if (!(MD && (MD->isCopyAssignmentOperator() ||
1035 MD->isMoveAssignmentOperator()) &&
1036 MD->isTrivial()))
1037 return 0;
1038 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1039 if (!IOA)
1040 return 0;
1041 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1042 if (!Field || !isMemcpyableField(Field))
1043 return 0;
1044 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1045 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
1046 return 0;
1047 return Field;
1048 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1049 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1050 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
1051 return 0;
1052 Expr *DstPtr = CE->getArg(0);
1053 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1054 DstPtr = DC->getSubExpr();
1055 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1056 if (!DUO || DUO->getOpcode() != UO_AddrOf)
1057 return 0;
1058 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1059 if (!ME)
1060 return 0;
1061 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1062 if (!Field || !isMemcpyableField(Field))
1063 return 0;
1064 Expr *SrcPtr = CE->getArg(1);
1065 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1066 SrcPtr = SC->getSubExpr();
1067 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1068 if (!SUO || SUO->getOpcode() != UO_AddrOf)
1069 return 0;
1070 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1071 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
1072 return 0;
1073 return Field;
1074 }
1075
1076 return 0;
1077 }
1078
1079 bool AssignmentsMemcpyable;
1080 SmallVector<Stmt*, 16> AggregatedStmts;
1081
1082 public:
1083
1084 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1085 FunctionArgList &Args)
1086 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1087 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1088 assert(Args.size() == 2);
1089 }
1090
1091 void emitAssignment(Stmt *S) {
1092 FieldDecl *F = getMemcpyableField(S);
1093 if (F) {
1094 addMemcpyableField(F);
1095 AggregatedStmts.push_back(S);
1096 } else {
1097 emitAggregatedStmts();
1098 CGF.EmitStmt(S);
1099 }
1100 }
1101
1102 void emitAggregatedStmts() {
1103 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001104 if (!AggregatedStmts.empty()) {
1105 CopyingValueRepresentation CVR(CGF);
1106 CGF.EmitStmt(AggregatedStmts[0]);
1107 }
Lang Hamesbf122742013-02-17 07:22:09 +00001108 reset();
1109 }
1110
1111 emitMemcpy();
1112 AggregatedStmts.clear();
1113 }
1114
1115 void finish() {
1116 emitAggregatedStmts();
1117 }
1118 };
1119
1120}
1121
Anders Carlssonfb404882009-12-24 22:46:43 +00001122/// EmitCtorPrologue - This routine generates necessary code to initialize
1123/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001124void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001125 CXXCtorType CtorType,
1126 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001127 if (CD->isDelegatingConstructor())
1128 return EmitDelegatingCXXConstructorCall(CD, Args);
1129
Anders Carlssonfb404882009-12-24 22:46:43 +00001130 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001131
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001132 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1133 E = CD->init_end();
1134
1135 llvm::BasicBlock *BaseCtorContinueBB = 0;
1136 if (ClassDecl->getNumVBases() &&
1137 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1138 // The ABIs that don't have constructor variants need to put a branch
1139 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001140 BaseCtorContinueBB =
1141 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001142 assert(BaseCtorContinueBB);
1143 }
1144
1145 // Virtual base initializers first.
1146 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1147 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1148 }
1149
1150 if (BaseCtorContinueBB) {
1151 // Complete object handler should continue to the remaining initializers.
1152 Builder.CreateBr(BaseCtorContinueBB);
1153 EmitBlock(BaseCtorContinueBB);
1154 }
1155
1156 // Then, non-virtual base initializers.
1157 for (; B != E && (*B)->isBaseInitializer(); B++) {
1158 assert(!(*B)->isBaseVirtual());
1159 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001160 }
1161
Anders Carlssond5895932010-03-28 21:07:49 +00001162 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001163
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001164 // And finally, initialize class members.
Richard Smith852c9db2013-04-20 22:23:05 +00001165 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hamesbf122742013-02-17 07:22:09 +00001166 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001167 for (; B != E; B++) {
1168 CXXCtorInitializer *Member = (*B);
1169 assert(!Member->isBaseInitializer());
1170 assert(Member->isAnyMemberInitializer() &&
1171 "Delegating initializer on non-delegating constructor");
1172 CM.addMemberInitializer(Member);
1173 }
Lang Hamesbf122742013-02-17 07:22:09 +00001174 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001175}
1176
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001177static bool
1178FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1179
1180static bool
1181HasTrivialDestructorBody(ASTContext &Context,
1182 const CXXRecordDecl *BaseClassDecl,
1183 const CXXRecordDecl *MostDerivedClassDecl)
1184{
1185 // If the destructor is trivial we don't have to check anything else.
1186 if (BaseClassDecl->hasTrivialDestructor())
1187 return true;
1188
1189 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1190 return false;
1191
1192 // Check fields.
1193 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(),
1194 E = BaseClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001195 const FieldDecl *Field = *I;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001196
1197 if (!FieldHasTrivialDestructorBody(Context, Field))
1198 return false;
1199 }
1200
1201 // Check non-virtual bases.
1202 for (CXXRecordDecl::base_class_const_iterator I =
1203 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end();
1204 I != E; ++I) {
1205 if (I->isVirtual())
1206 continue;
1207
1208 const CXXRecordDecl *NonVirtualBase =
1209 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1210 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1211 MostDerivedClassDecl))
1212 return false;
1213 }
1214
1215 if (BaseClassDecl == MostDerivedClassDecl) {
1216 // Check virtual bases.
1217 for (CXXRecordDecl::base_class_const_iterator I =
1218 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end();
1219 I != E; ++I) {
1220 const CXXRecordDecl *VirtualBase =
1221 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1222 if (!HasTrivialDestructorBody(Context, VirtualBase,
1223 MostDerivedClassDecl))
1224 return false;
1225 }
1226 }
1227
1228 return true;
1229}
1230
1231static bool
1232FieldHasTrivialDestructorBody(ASTContext &Context,
1233 const FieldDecl *Field)
1234{
1235 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1236
1237 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1238 if (!RT)
1239 return true;
1240
1241 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1242 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1243}
1244
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001245/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1246/// any vtable pointers before calling this destructor.
1247static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +00001248 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001249 if (!Dtor->hasTrivialBody())
1250 return false;
1251
1252 // Check the fields.
1253 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1254 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1255 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001256 const FieldDecl *Field = *I;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001257
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001258 if (!FieldHasTrivialDestructorBody(Context, Field))
1259 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001260 }
1261
1262 return true;
1263}
1264
John McCallb81884d2010-02-19 09:25:03 +00001265/// EmitDestructorBody - Emits the body of the current destructor.
1266void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1267 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1268 CXXDtorType DtorType = CurGD.getDtorType();
1269
John McCallf99a6312010-07-21 05:30:47 +00001270 // The call to operator delete in a deleting destructor happens
1271 // outside of the function-try-block, which means it's always
1272 // possible to delegate the destructor body to the complete
1273 // destructor. Do so.
1274 if (DtorType == Dtor_Deleting) {
1275 EnterDtorCleanups(Dtor, Dtor_Deleting);
1276 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001277 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001278 PopCleanupBlock();
1279 return;
1280 }
1281
John McCallb81884d2010-02-19 09:25:03 +00001282 Stmt *Body = Dtor->getBody();
1283
1284 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001285 // anything else.
1286 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001287 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001288 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001289
John McCallf99a6312010-07-21 05:30:47 +00001290 // Enter the epilogue cleanups.
1291 RunCleanupsScope DtorEpilogue(*this);
1292
John McCallb81884d2010-02-19 09:25:03 +00001293 // If this is the complete variant, just invoke the base variant;
1294 // the epilogue will destruct the virtual bases. But we can't do
1295 // this optimization if the body is a function-try-block, because
Reid Klecknere7de47e2013-07-22 13:51:44 +00001296 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1297 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001298 switch (DtorType) {
1299 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1300
1301 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001302 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1303 "can't emit a dtor without a body for non-Microsoft ABIs");
1304
John McCallf99a6312010-07-21 05:30:47 +00001305 // Enter the cleanup scopes for virtual bases.
1306 EnterDtorCleanups(Dtor, Dtor_Complete);
1307
Reid Klecknere7de47e2013-07-22 13:51:44 +00001308 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001309 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001310 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001311 break;
1312 }
1313 // Fallthrough: act like we're in the base variant.
John McCallb81884d2010-02-19 09:25:03 +00001314
John McCallf99a6312010-07-21 05:30:47 +00001315 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001316 assert(Body);
1317
John McCallf99a6312010-07-21 05:30:47 +00001318 // Enter the cleanup scopes for fields and non-virtual bases.
1319 EnterDtorCleanups(Dtor, Dtor_Base);
1320
1321 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001322 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1323 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +00001324
1325 if (isTryBody)
1326 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1327 else if (Body)
1328 EmitStmt(Body);
1329 else {
1330 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1331 // nothing to do besides what's in the epilogue
1332 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001333 // -fapple-kext must inline any call to this dtor into
1334 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001335 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +00001336 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +00001337 break;
John McCallb81884d2010-02-19 09:25:03 +00001338 }
1339
John McCallf99a6312010-07-21 05:30:47 +00001340 // Jump out through the epilogue cleanups.
1341 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001342
1343 // Exit the try if applicable.
1344 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001345 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001346}
1347
Lang Hamesbf122742013-02-17 07:22:09 +00001348void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1349 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1350 const Stmt *RootS = AssignOp->getBody();
1351 assert(isa<CompoundStmt>(RootS) &&
1352 "Body of an implicit assignment operator should be compound stmt.");
1353 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1354
1355 LexicalScope Scope(*this, RootCS->getSourceRange());
1356
1357 AssignmentMemcpyizer AM(*this, AssignOp, Args);
1358 for (CompoundStmt::const_body_iterator I = RootCS->body_begin(),
1359 E = RootCS->body_end();
1360 I != E; ++I) {
1361 AM.emitAssignment(*I);
1362 }
1363 AM.finish();
1364}
1365
John McCallf99a6312010-07-21 05:30:47 +00001366namespace {
1367 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +00001368 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001369 CallDtorDelete() {}
1370
John McCall30317fd2011-07-12 20:27:29 +00001371 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf99a6312010-07-21 05:30:47 +00001372 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1373 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1374 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1375 CGF.getContext().getTagDeclType(ClassDecl));
1376 }
1377 };
1378
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001379 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1380 llvm::Value *ShouldDeleteCondition;
1381 public:
1382 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1383 : ShouldDeleteCondition(ShouldDeleteCondition) {
1384 assert(ShouldDeleteCondition != NULL);
1385 }
1386
1387 void Emit(CodeGenFunction &CGF, Flags flags) {
1388 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1389 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1390 llvm::Value *ShouldCallDelete
1391 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1392 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1393
1394 CGF.EmitBlock(callDeleteBB);
1395 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1396 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1397 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1398 CGF.getContext().getTagDeclType(ClassDecl));
1399 CGF.Builder.CreateBr(continueBB);
1400
1401 CGF.EmitBlock(continueBB);
1402 }
1403 };
1404
John McCall4bd0fb12011-07-12 16:41:08 +00001405 class DestroyField : public EHScopeStack::Cleanup {
1406 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001407 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001408 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001409
John McCall4bd0fb12011-07-12 16:41:08 +00001410 public:
1411 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1412 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001413 : field(field), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001414 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001415
John McCall30317fd2011-07-12 20:27:29 +00001416 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +00001417 // Find the address of the field.
1418 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001419 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1420 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1421 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001422 assert(LV.isSimple());
1423
1424 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001425 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001426 }
1427 };
1428}
1429
Anders Carlssonfb404882009-12-24 22:46:43 +00001430/// EmitDtorEpilogue - Emit all code that comes at the end of class's
1431/// destructor. This is to call destructors on members and base classes
1432/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001433void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1434 CXXDtorType DtorType) {
Anders Carlssonfb404882009-12-24 22:46:43 +00001435 assert(!DD->isTrivial() &&
1436 "Should not emit dtor epilogue for trivial dtor!");
1437
John McCallf99a6312010-07-21 05:30:47 +00001438 // The deleting-destructor phase just needs to call the appropriate
1439 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001440 if (DtorType == Dtor_Deleting) {
1441 assert(DD->getOperatorDelete() &&
1442 "operator delete missing - EmitDtorEpilogue");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001443 if (CXXStructorImplicitParamValue) {
1444 // If there is an implicit param to the deleting dtor, it's a boolean
1445 // telling whether we should call delete at the end of the dtor.
1446 EHStack.pushCleanup<CallDtorDeleteConditional>(
1447 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1448 } else {
1449 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1450 }
John McCall5c60a6f2010-02-18 19:59:28 +00001451 return;
1452 }
1453
John McCallf99a6312010-07-21 05:30:47 +00001454 const CXXRecordDecl *ClassDecl = DD->getParent();
1455
Richard Smith20104042011-09-18 12:11:43 +00001456 // Unions have no bases and do not call field destructors.
1457 if (ClassDecl->isUnion())
1458 return;
1459
John McCallf99a6312010-07-21 05:30:47 +00001460 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001461 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001462
1463 // We push them in the forward order so that they'll be popped in
1464 // the reverse order.
1465 for (CXXRecordDecl::base_class_const_iterator I =
1466 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end();
John McCall5c60a6f2010-02-18 19:59:28 +00001467 I != E; ++I) {
1468 const CXXBaseSpecifier &Base = *I;
1469 CXXRecordDecl *BaseClassDecl
1470 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1471
1472 // Ignore trivial destructors.
1473 if (BaseClassDecl->hasTrivialDestructor())
1474 continue;
John McCallf99a6312010-07-21 05:30:47 +00001475
John McCallcda666c2010-07-21 07:22:38 +00001476 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1477 BaseClassDecl,
1478 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001479 }
John McCallf99a6312010-07-21 05:30:47 +00001480
John McCall5c60a6f2010-02-18 19:59:28 +00001481 return;
1482 }
1483
1484 assert(DtorType == Dtor_Base);
John McCallf99a6312010-07-21 05:30:47 +00001485
1486 // Destroy non-virtual bases.
1487 for (CXXRecordDecl::base_class_const_iterator I =
1488 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) {
1489 const CXXBaseSpecifier &Base = *I;
1490
1491 // Ignore virtual bases.
1492 if (Base.isVirtual())
1493 continue;
1494
1495 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1496
1497 // Ignore trivial destructors.
1498 if (BaseClassDecl->hasTrivialDestructor())
1499 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001500
John McCallcda666c2010-07-21 07:22:38 +00001501 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1502 BaseClassDecl,
1503 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001504 }
1505
1506 // Destroy direct fields.
Anders Carlssonfb404882009-12-24 22:46:43 +00001507 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(),
1508 E = ClassDecl->field_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001509 const FieldDecl *field = *I;
John McCall4bd0fb12011-07-12 16:41:08 +00001510 QualType type = field->getType();
1511 QualType::DestructionKind dtorKind = type.isDestructedType();
1512 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001513
Richard Smith921bd202012-02-26 09:11:52 +00001514 // Anonymous union members do not have their destructors called.
1515 const RecordType *RT = type->getAsUnionType();
1516 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1517
John McCall4bd0fb12011-07-12 16:41:08 +00001518 CleanupKind cleanupKind = getCleanupKind(dtorKind);
1519 EHStack.pushCleanup<DestroyField>(cleanupKind, field,
1520 getDestroyer(dtorKind),
1521 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001522 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001523}
1524
John McCallf677a8e2011-07-13 06:10:41 +00001525/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1526/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001527///
John McCallf677a8e2011-07-13 06:10:41 +00001528/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001529/// \param arrayType the type of the array to initialize
1530/// \param arrayBegin an arrayType*
1531/// \param zeroInitialize true if each element should be
1532/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001533void
John McCallf677a8e2011-07-13 06:10:41 +00001534CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1535 const ConstantArrayType *arrayType,
1536 llvm::Value *arrayBegin,
1537 CallExpr::const_arg_iterator argBegin,
1538 CallExpr::const_arg_iterator argEnd,
1539 bool zeroInitialize) {
1540 QualType elementType;
1541 llvm::Value *numElements =
1542 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001543
John McCallf677a8e2011-07-13 06:10:41 +00001544 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin,
1545 argBegin, argEnd, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001546}
1547
John McCallf677a8e2011-07-13 06:10:41 +00001548/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1549/// constructor for each of several members of an array.
1550///
1551/// \param ctor the constructor to call for each element
1552/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001553/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001554/// \param arrayBegin a T*, where T is the type constructed by ctor
1555/// \param zeroInitialize true if each element should be
1556/// zero-initialized before it is constructed
Anders Carlsson27da15b2010-01-01 20:29:01 +00001557void
John McCallf677a8e2011-07-13 06:10:41 +00001558CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1559 llvm::Value *numElements,
1560 llvm::Value *arrayBegin,
1561 CallExpr::const_arg_iterator argBegin,
1562 CallExpr::const_arg_iterator argEnd,
1563 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001564
1565 // It's legal for numElements to be zero. This can happen both
1566 // dynamically, because x can be zero in 'new A[x]', and statically,
1567 // because of GCC extensions that permit zero-length arrays. There
1568 // are probably legitimate places where we could assume that this
1569 // doesn't happen, but it's not clear that it's worth it.
1570 llvm::BranchInst *zeroCheckBranch = 0;
1571
1572 // Optimize for a constant count.
1573 llvm::ConstantInt *constantCount
1574 = dyn_cast<llvm::ConstantInt>(numElements);
1575 if (constantCount) {
1576 // Just skip out if the constant count is zero.
1577 if (constantCount->isZero()) return;
1578
1579 // Otherwise, emit the check.
1580 } else {
1581 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1582 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1583 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1584 EmitBlock(loopBB);
1585 }
1586
John McCallf677a8e2011-07-13 06:10:41 +00001587 // Find the end of the array.
1588 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1589 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001590
John McCallf677a8e2011-07-13 06:10:41 +00001591 // Enter the loop, setting up a phi for the current location to initialize.
1592 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1593 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1594 EmitBlock(loopBB);
1595 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1596 "arrayctor.cur");
1597 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001598
Anders Carlsson27da15b2010-01-01 20:29:01 +00001599 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001600
1601 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001602
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001603 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001604 if (zeroInitialize)
1605 EmitNullInitialization(cur, type);
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001606
Anders Carlsson27da15b2010-01-01 20:29:01 +00001607 // C++ [class.temporary]p4:
1608 // There are two contexts in which temporaries are destroyed at a different
1609 // point than the end of the full-expression. The first context is when a
1610 // default constructor is called to initialize an element of an array.
1611 // If the constructor has one or more default arguments, the destruction of
1612 // every temporary created in a default argument expression is sequenced
1613 // before the construction of the next array element, if any.
1614
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001615 {
John McCallbd309292010-07-06 01:34:17 +00001616 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001617
John McCallf677a8e2011-07-13 06:10:41 +00001618 // Evaluate the constructor and its arguments in a regular
1619 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001620 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001621 !ctor->getParent()->hasTrivialDestructor()) {
1622 Destroyer *destroyer = destroyCXXObject;
1623 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1624 }
1625
1626 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001627 /*Delegating=*/false, cur, argBegin, argEnd);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001628 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001629
John McCallf677a8e2011-07-13 06:10:41 +00001630 // Go to the next element.
1631 llvm::Value *next =
1632 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1633 "arrayctor.next");
1634 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001635
John McCallf677a8e2011-07-13 06:10:41 +00001636 // Check whether that's the end of the loop.
1637 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1638 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1639 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001640
John McCall6549b312011-07-13 07:37:11 +00001641 // Patch the earlier check to skip over the loop.
1642 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1643
John McCallf677a8e2011-07-13 06:10:41 +00001644 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001645}
1646
John McCall82fe67b2011-07-09 01:37:26 +00001647void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1648 llvm::Value *addr,
1649 QualType type) {
1650 const RecordType *rtype = type->castAs<RecordType>();
1651 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1652 const CXXDestructorDecl *dtor = record->getDestructor();
1653 assert(!dtor->isTrivial());
1654 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001655 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001656}
1657
Anders Carlsson27da15b2010-01-01 20:29:01 +00001658void
1659CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
Anders Carlssone11f9ce2010-05-02 23:20:53 +00001660 CXXCtorType Type, bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001661 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001662 llvm::Value *This,
1663 CallExpr::const_arg_iterator ArgBeg,
1664 CallExpr::const_arg_iterator ArgEnd) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001665 // If this is a trivial constructor, just emit what's needed.
John McCallca972cd2010-02-06 00:25:16 +00001666 if (D->isTrivial()) {
1667 if (ArgBeg == ArgEnd) {
1668 // Trivial default constructor, no codegen required.
1669 assert(D->isDefaultConstructor() &&
1670 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001671 return;
1672 }
John McCallca972cd2010-02-06 00:25:16 +00001673
1674 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001675 assert(D->isCopyOrMoveConstructor() &&
1676 "trivial 1-arg ctor not a copy/move ctor");
John McCallca972cd2010-02-06 00:25:16 +00001677
John McCallca972cd2010-02-06 00:25:16 +00001678 const Expr *E = (*ArgBeg);
1679 QualType Ty = E->getType();
1680 llvm::Value *Src = EmitLValue(E).getAddress();
1681 EmitAggregateCopy(This, Src, Ty);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001682 return;
1683 }
1684
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001685 // Non-trivial constructors are handled in an ABI-specific manner.
Stephen Lin9dc6eef2013-06-30 20:40:16 +00001686 CGM.getCXXABI().EmitConstructorCall(*this, D, Type, ForVirtualBase,
1687 Delegating, This, ArgBeg, ArgEnd);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001688}
1689
John McCallf8ff7b92010-02-23 00:48:20 +00001690void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001691CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1692 llvm::Value *This, llvm::Value *Src,
1693 CallExpr::const_arg_iterator ArgBeg,
1694 CallExpr::const_arg_iterator ArgEnd) {
1695 if (D->isTrivial()) {
1696 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001697 assert(D->isCopyOrMoveConstructor() &&
1698 "trivial 1-arg ctor not a copy/move ctor");
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001699 EmitAggregateCopy(This, Src, (*ArgBeg)->getType());
1700 return;
1701 }
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001702 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, clang::Ctor_Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001703 assert(D->isInstance() &&
1704 "Trying to emit a member call expr on a static method!");
1705
Reid Kleckner739756c2013-12-04 19:23:12 +00001706 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001707
1708 CallArgList Args;
1709
1710 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001711 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001712
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001713 // Push the src ptr.
1714 QualType QT = *(FPT->arg_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001715 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001716 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001717 Args.add(RValue::get(Src), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00001718
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001719 // Skip over first argument (Src).
Reid Kleckner739756c2013-12-04 19:23:12 +00001720 EmitCallArgs(Args, FPT->isVariadic(), FPT->arg_type_begin() + 1,
1721 FPT->arg_type_end(), ArgBeg + 1, ArgEnd);
1722
John McCall8dda7b22012-07-07 06:41:13 +00001723 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1724 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001725}
1726
1727void
John McCallf8ff7b92010-02-23 00:48:20 +00001728CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1729 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001730 const FunctionArgList &Args,
1731 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00001732 CallArgList DelegateArgs;
1733
1734 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1735 assert(I != E && "no parameters to constructor");
1736
1737 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001738 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001739 ++I;
1740
1741 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001742 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00001743 /*ForVirtualBase=*/false,
1744 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001745 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001746 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001747
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001748 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001749 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001750 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001751 ++I;
1752 }
1753 }
1754
1755 // Explicit arguments.
1756 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001757 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001758 // FIXME: per-argument source location
1759 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00001760 }
1761
Manman Ren01754612013-03-20 16:59:38 +00001762 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(Ctor, CtorType);
John McCalla729c622012-02-17 03:33:10 +00001763 EmitCall(CGM.getTypes().arrangeCXXConstructorDeclaration(Ctor, CtorType),
Manman Ren01754612013-03-20 16:59:38 +00001764 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00001765}
1766
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001767namespace {
1768 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1769 const CXXDestructorDecl *Dtor;
1770 llvm::Value *Addr;
1771 CXXDtorType Type;
1772
1773 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1774 CXXDtorType Type)
1775 : Dtor(D), Addr(Addr), Type(Type) {}
1776
John McCall30317fd2011-07-12 20:27:29 +00001777 void Emit(CodeGenFunction &CGF, Flags flags) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001778 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001779 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001780 }
1781 };
1782}
1783
Alexis Hunt61bc1732011-05-01 07:04:31 +00001784void
1785CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1786 const FunctionArgList &Args) {
1787 assert(Ctor->isDelegatingConstructor());
1788
1789 llvm::Value *ThisPtr = LoadCXXThis();
1790
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001791 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00001792 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00001793 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001794 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001795 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001796 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001797 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001798
1799 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001800
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001801 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001802 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001803 CXXDtorType Type =
1804 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1805
1806 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1807 ClassDecl->getDestructor(),
1808 ThisPtr, Type);
1809 }
1810}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001811
Anders Carlsson27da15b2010-01-01 20:29:01 +00001812void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1813 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001814 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001815 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001816 llvm::Value *This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001817 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1818 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001819}
1820
John McCall53cad2e2010-07-21 01:41:18 +00001821namespace {
John McCallcda666c2010-07-21 07:22:38 +00001822 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001823 const CXXDestructorDecl *Dtor;
1824 llvm::Value *Addr;
1825
1826 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1827 : Dtor(D), Addr(Addr) {}
1828
John McCall30317fd2011-07-12 20:27:29 +00001829 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall53cad2e2010-07-21 01:41:18 +00001830 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001831 /*ForVirtualBase=*/false,
1832 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00001833 }
1834 };
1835}
1836
John McCall8680f872010-07-21 06:29:51 +00001837void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1838 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001839 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001840}
1841
John McCallbd309292010-07-06 01:34:17 +00001842void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1843 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1844 if (!ClassDecl) return;
1845 if (ClassDecl->hasTrivialDestructor()) return;
1846
1847 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001848 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001849 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001850}
1851
Anders Carlssone87fae92010-03-28 19:40:00 +00001852void
1853CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001854 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001855 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001856 const CXXRecordDecl *VTableClass) {
Anders Carlssone87fae92010-03-28 19:40:00 +00001857 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001858 bool NeedsVirtualOffset;
1859 llvm::Value *VTableAddressPoint =
1860 CGM.getCXXABI().getVTableAddressPointInStructor(
1861 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1862 if (!VTableAddressPoint)
1863 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00001864
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001865 // Compute where to store the address point.
Anders Carlssonc58fb552010-05-03 00:29:58 +00001866 llvm::Value *VirtualOffset = 0;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001867 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001868
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001869 if (NeedsVirtualOffset) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00001870 // We need to use the virtual base offset offset because the virtual base
1871 // might have a different offset in the most derived class.
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001872 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1873 LoadCXXThis(),
1874 VTableClass,
1875 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001876 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001877 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001878 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001879 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001880 }
Anders Carlssonc58fb552010-05-03 00:29:58 +00001881
1882 // Apply the offsets.
1883 llvm::Value *VTableField = LoadCXXThis();
1884
Ken Dyckcfc332c2011-03-23 00:45:26 +00001885 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlssonc58fb552010-05-03 00:29:58 +00001886 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1887 NonVirtualOffset,
1888 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001889
Anders Carlssone87fae92010-03-28 19:40:00 +00001890 // Finally, store the address point.
Chris Lattner2192fe52011-07-18 04:24:23 +00001891 llvm::Type *AddressPointPtrTy =
Anders Carlssone87fae92010-03-28 19:40:00 +00001892 VTableAddressPoint->getType()->getPointerTo();
1893 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00001894 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
1895 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00001896}
1897
Anders Carlssond5895932010-03-28 21:07:49 +00001898void
1899CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001900 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001901 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001902 bool BaseIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00001903 const CXXRecordDecl *VTableClass,
1904 VisitedVirtualBasesSetTy& VBases) {
1905 // If this base is a non-virtual primary base the address point has already
1906 // been set.
1907 if (!BaseIsNonVirtualPrimaryBase) {
1908 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001909 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00001910 VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00001911 }
1912
1913 const CXXRecordDecl *RD = Base.getBase();
1914
1915 // Traverse bases.
1916 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1917 E = RD->bases_end(); I != E; ++I) {
1918 CXXRecordDecl *BaseDecl
1919 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1920
1921 // Ignore classes without a vtable.
1922 if (!BaseDecl->isDynamicClass())
1923 continue;
1924
Ken Dyck3fb4c892011-03-23 01:04:18 +00001925 CharUnits BaseOffset;
1926 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00001927 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00001928
1929 if (I->isVirtual()) {
1930 // Check if we've visited this virtual base before.
1931 if (!VBases.insert(BaseDecl))
1932 continue;
1933
1934 const ASTRecordLayout &Layout =
1935 getContext().getASTRecordLayout(VTableClass);
1936
Ken Dyck3fb4c892011-03-23 01:04:18 +00001937 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
1938 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00001939 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00001940 } else {
1941 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
1942
Ken Dyck16ffcac2011-03-24 01:21:01 +00001943 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001944 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00001945 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00001946 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00001947 }
1948
Ken Dyck16ffcac2011-03-24 01:21:01 +00001949 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Anders Carlsson652758c2010-04-20 05:22:15 +00001950 I->isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00001951 BaseOffsetFromNearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00001952 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00001953 VTableClass, VBases);
Anders Carlssond5895932010-03-28 21:07:49 +00001954 }
1955}
1956
1957void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
1958 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00001959 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00001960 return;
1961
Anders Carlssond5895932010-03-28 21:07:49 +00001962 // Initialize the vtable pointers for this class and all of its bases.
1963 VisitedVirtualBasesSetTy VBases;
Ken Dyck16ffcac2011-03-24 01:21:01 +00001964 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
1965 /*NearestVBase=*/0,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001966 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00001967 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00001968
1969 if (RD->getNumVBases())
1970 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001971}
Dan Gohman8fc50c22010-10-26 18:44:08 +00001972
1973llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00001974 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00001975 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany141e46f2012-03-26 17:03:51 +00001976 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
1977 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
1978 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00001979}
Anders Carlssonc36783e2011-05-08 20:32:23 +00001980
Anders Carlssonc36783e2011-05-08 20:32:23 +00001981
1982// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
1983// quite what we want.
1984static const Expr *skipNoOpCastsAndParens(const Expr *E) {
1985 while (true) {
1986 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
1987 E = PE->getSubExpr();
1988 continue;
1989 }
1990
1991 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
1992 if (CE->getCastKind() == CK_NoOp) {
1993 E = CE->getSubExpr();
1994 continue;
1995 }
1996 }
1997 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1998 if (UO->getOpcode() == UO_Extension) {
1999 E = UO->getSubExpr();
2000 continue;
2001 }
2002 }
2003 return E;
2004 }
2005}
2006
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002007bool
2008CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2009 const CXXMethodDecl *MD) {
2010 // When building with -fapple-kext, all calls must go through the vtable since
2011 // the kernel linker can do runtime patching of vtables.
2012 if (getLangOpts().AppleKext)
2013 return false;
2014
Anders Carlssonc36783e2011-05-08 20:32:23 +00002015 // If the most derived class is marked final, we know that no subclass can
2016 // override this member function and so we can devirtualize it. For example:
2017 //
2018 // struct A { virtual void f(); }
2019 // struct B final : A { };
2020 //
2021 // void f(B *b) {
2022 // b->f();
2023 // }
2024 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002025 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002026 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2027 return true;
2028
2029 // If the member function is marked 'final', we know that it can't be
2030 // overridden and can therefore devirtualize it.
2031 if (MD->hasAttr<FinalAttr>())
2032 return true;
2033
2034 // Similarly, if the class itself is marked 'final' it can't be overridden
2035 // and we can therefore devirtualize the member function call.
2036 if (MD->getParent()->hasAttr<FinalAttr>())
2037 return true;
2038
2039 Base = skipNoOpCastsAndParens(Base);
2040 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2041 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2042 // This is a record decl. We know the type and can devirtualize it.
2043 return VD->getType()->isRecordType();
2044 }
2045
2046 return false;
2047 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002048
2049 // We can devirtualize calls on an object accessed by a class member access
2050 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2051 // a derived class object constructed in the same location.
2052 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2053 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2054 return VD->getType()->isRecordType();
2055
Anders Carlssonc36783e2011-05-08 20:32:23 +00002056 // We can always devirtualize calls on temporary object expressions.
2057 if (isa<CXXConstructExpr>(Base))
2058 return true;
2059
2060 // And calls on bound temporaries.
2061 if (isa<CXXBindTemporaryExpr>(Base))
2062 return true;
2063
2064 // Check if this is a call expr that returns a record type.
2065 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
2066 return CE->getCallReturnType()->isRecordType();
2067
2068 // We can't devirtualize the call.
2069 return false;
2070}
2071
Anders Carlssonc36783e2011-05-08 20:32:23 +00002072llvm::Value *
2073CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E,
2074 const CXXMethodDecl *MD,
2075 llvm::Value *This) {
John McCalla729c622012-02-17 03:33:10 +00002076 llvm::FunctionType *fnType =
2077 CGM.getTypes().GetFunctionType(
2078 CGM.getTypes().arrangeCXXMethodDeclaration(MD));
Anders Carlssonc36783e2011-05-08 20:32:23 +00002079
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002080 if (MD->isVirtual() && !CanDevirtualizeMemberFunctionCall(E->getArg(0), MD))
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +00002081 return CGM.getCXXABI().getVirtualFunctionPointer(*this, MD, This, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00002082
John McCalla729c622012-02-17 03:33:10 +00002083 return CGM.GetAddrOfFunction(MD, fnType);
Anders Carlssonc36783e2011-05-08 20:32:23 +00002084}
Eli Friedman5a6d5072012-02-16 01:37:33 +00002085
Faisal Vali571df122013-09-29 08:45:24 +00002086void CodeGenFunction::EmitForwardingCallToLambda(
2087 const CXXMethodDecl *callOperator,
2088 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002089 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002090 const CGFunctionInfo &calleeFnInfo =
2091 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2092 llvm::Value *callee =
2093 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2094 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002095
John McCall8dda7b22012-07-07 06:41:13 +00002096 // Prepare the return slot.
2097 const FunctionProtoType *FPT =
2098 callOperator->getType()->castAs<FunctionProtoType>();
2099 QualType resultType = FPT->getResultType();
2100 ReturnValueSlot returnSlot;
2101 if (!resultType->isVoidType() &&
2102 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002103 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002104 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2105
2106 // We don't need to separately arrange the call arguments because
2107 // the call can't be variadic anyway --- it's impossible to forward
2108 // variadic arguments.
Eli Friedman5b446882012-02-16 03:47:28 +00002109
2110 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002111 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2112 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002113
John McCall8dda7b22012-07-07 06:41:13 +00002114 // If necessary, copy the returned value into the slot.
2115 if (!resultType->isVoidType() && returnSlot.isNull())
2116 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002117 else
2118 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002119}
2120
Eli Friedman2495ab02012-02-25 02:48:22 +00002121void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2122 const BlockDecl *BD = BlockInfo->getBlockDecl();
2123 const VarDecl *variable = BD->capture_begin()->getVariable();
2124 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2125
2126 // Start building arguments for forwarding call
2127 CallArgList CallArgs;
2128
2129 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2130 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2131 CallArgs.add(RValue::get(ThisPtr), ThisType);
2132
2133 // Add the rest of the parameters.
2134 for (BlockDecl::param_const_iterator I = BD->param_begin(),
2135 E = BD->param_end(); I != E; ++I) {
2136 ParmVarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002137 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Eli Friedman2495ab02012-02-25 02:48:22 +00002138 }
Faisal Vali571df122013-09-29 08:45:24 +00002139 assert(!Lambda->isGenericLambda() &&
2140 "generic lambda interconversion to block not implemented");
2141 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002142}
2143
2144void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002145 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002146 // FIXME: Making this work correctly is nasty because it requires either
2147 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002148 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002149 return;
2150 }
2151
Richard Smithb47c36f2013-11-05 09:12:18 +00002152 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002153}
2154
2155void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2156 const CXXRecordDecl *Lambda = MD->getParent();
2157
2158 // Start building arguments for forwarding call
2159 CallArgList CallArgs;
2160
2161 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2162 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2163 CallArgs.add(RValue::get(ThisPtr), ThisType);
2164
2165 // Add the rest of the parameters.
2166 for (FunctionDecl::param_const_iterator I = MD->param_begin(),
2167 E = MD->param_end(); I != E; ++I) {
2168 ParmVarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002169 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Eli Friedman2495ab02012-02-25 02:48:22 +00002170 }
Faisal Vali571df122013-09-29 08:45:24 +00002171 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2172 // For a generic lambda, find the corresponding call operator specialization
2173 // to which the call to the static-invoker shall be forwarded.
2174 if (Lambda->isGenericLambda()) {
2175 assert(MD->isFunctionTemplateSpecialization());
2176 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2177 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
2178 void *InsertPos = 0;
2179 FunctionDecl *CorrespondingCallOpSpecialization =
2180 CallOpTemplate->findSpecialization(TAL->data(), TAL->size(), InsertPos);
2181 assert(CorrespondingCallOpSpecialization);
2182 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2183 }
2184 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002185}
2186
Douglas Gregor355efbb2012-02-17 03:02:34 +00002187void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2188 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002189 // FIXME: Making this work correctly is nasty because it requires either
2190 // cloning the body of the call operator or making the call operator forward.
2191 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002192 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002193 }
2194
Douglas Gregor355efbb2012-02-17 03:02:34 +00002195 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002196}