blob: e3d4601aaffcf1d827159ba6ad547469eecb33e4 [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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000015#include "CGCXXABI.h"
Devang Pateld76c1db2010-08-11 21:04:37 +000016#include "CGDebugInfo.h"
Lang Hamesbf122742013-02-17 07:22:09 +000017#include "CGRecordLayout.h"
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000018#include "CodeGenFunction.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"
Peter Collingbournea4ccff32015-02-20 20:30:56 +000027#include "llvm/IR/Intrinsics.h"
Anders Carlssonc6d171e2009-10-06 22:43:30 +000028
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000029using namespace clang;
30using namespace CodeGen;
31
Ken Dycka1a4ae32011-03-22 00:53:26 +000032static CharUnits
Anders Carlssond829a022010-04-24 21:06:20 +000033ComputeNonVirtualBaseClassOffset(ASTContext &Context,
34 const CXXRecordDecl *DerivedClass,
John McCallcf142162010-08-07 06:22:56 +000035 CastExpr::path_const_iterator Start,
36 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +000037 CharUnits Offset = CharUnits::Zero();
Anders Carlssond829a022010-04-24 21:06:20 +000038
39 const CXXRecordDecl *RD = DerivedClass;
40
John McCallcf142162010-08-07 06:22:56 +000041 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +000042 const CXXBaseSpecifier *Base = *I;
43 assert(!Base->isVirtual() && "Should not see virtual bases here!");
44
45 // Get the layout.
46 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
47
48 const CXXRecordDecl *BaseDecl =
49 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
50
51 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +000052 Offset += Layout.getBaseClassOffset(BaseDecl);
Anders Carlssond829a022010-04-24 21:06:20 +000053
54 RD = BaseDecl;
55 }
56
Ken Dycka1a4ae32011-03-22 00:53:26 +000057 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +000058}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000059
Anders Carlsson9150a2a2009-09-29 03:13:20 +000060llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000061CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +000062 CastExpr::path_const_iterator PathBegin,
63 CastExpr::path_const_iterator PathEnd) {
64 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000065
Ken Dycka1a4ae32011-03-22 00:53:26 +000066 CharUnits Offset =
John McCallcf142162010-08-07 06:22:56 +000067 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl,
68 PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +000069 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +000070 return nullptr;
71
Chris Lattner2192fe52011-07-18 04:24:23 +000072 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000073 Types.ConvertType(getContext().getPointerDiffType());
74
Ken Dycka1a4ae32011-03-22 00:53:26 +000075 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +000076}
77
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000078/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +000079/// This should only be used for (1) non-virtual bases or (2) virtual bases
80/// when the type is known to be complete (e.g. in complete destructors).
81///
82/// The object pointed to by 'This' is assumed to be non-null.
83llvm::Value *
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000084CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
85 const CXXRecordDecl *Derived,
86 const CXXRecordDecl *Base,
87 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +000088 // 'this' must be a pointer (in some address space) to Derived.
89 assert(This->getType()->isPointerTy() &&
90 cast<llvm::PointerType>(This->getType())->getElementType()
91 == ConvertType(Derived));
92
93 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +000094 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +000095 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000096 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +000097 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000098 else
Ken Dyck6aa767c2011-03-22 01:21:15 +000099 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +0000100
101 // Shift and cast down to the base type.
102 // TODO: for complete types, this should be possible with a GEP.
103 llvm::Value *V = This;
Ken Dyck6aa767c2011-03-22 01:21:15 +0000104 if (Offset.isPositive()) {
John McCall6ce74722010-02-16 04:15:37 +0000105 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +0000106 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000107 }
108 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
109
110 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000111}
John McCall6ce74722010-02-16 04:15:37 +0000112
Anders Carlsson53cebd12010-04-20 16:03:35 +0000113static llvm::Value *
John McCall13a39c62012-08-01 05:04:58 +0000114ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
115 CharUnits nonVirtualOffset,
116 llvm::Value *virtualOffset) {
117 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000118 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000119
120 // Compute the offset from the static and dynamic components.
121 llvm::Value *baseOffset;
122 if (!nonVirtualOffset.isZero()) {
123 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
124 nonVirtualOffset.getQuantity());
125 if (virtualOffset) {
126 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
127 }
128 } else {
129 baseOffset = virtualOffset;
130 }
Anders Carlsson53cebd12010-04-20 16:03:35 +0000131
132 // Apply the base offset.
John McCall13a39c62012-08-01 05:04:58 +0000133 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
134 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
135 return ptr;
Anders Carlsson53cebd12010-04-20 16:03:35 +0000136}
137
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000138llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
139 llvm::Value *Value, const CXXRecordDecl *Derived,
140 CastExpr::path_const_iterator PathBegin,
141 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
142 SourceLocation Loc) {
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;
Craig Topper8a13c412014-05-21 05:09:00 +0000146 const CXXRecordDecl *VBase = nullptr;
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;
Craig Topper8a13c412014-05-21 05:09:00 +0000172 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000173 }
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
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000179 QualType DerivedTy = getContext().getRecordType(Derived);
180 CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
181
John McCall13a39c62012-08-01 05:04:58 +0000182 // If the static offset is zero and we don't have a virtual step,
183 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000184 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000185 if (sanitizePerformTypeCheck()) {
186 EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
187 !NullCheckValue);
188 }
Anders Carlssond829a022010-04-24 21:06:20 +0000189 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000190 }
John McCall13a39c62012-08-01 05:04:58 +0000191
Craig Topper8a13c412014-05-21 05:09:00 +0000192 llvm::BasicBlock *origBB = nullptr;
193 llvm::BasicBlock *endBB = nullptr;
194
John McCall13a39c62012-08-01 05:04:58 +0000195 // Skip over the offset (and the vtable load) if we're supposed to
196 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000197 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000198 origBB = Builder.GetInsertBlock();
199 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
200 endBB = createBasicBlock("cast.end");
Anders Carlssond829a022010-04-24 21:06:20 +0000201
John McCall13a39c62012-08-01 05:04:58 +0000202 llvm::Value *isNull = Builder.CreateIsNull(Value);
203 Builder.CreateCondBr(isNull, endBB, notNullBB);
204 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000205 }
206
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000207 if (sanitizePerformTypeCheck()) {
208 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
209 DerivedTy, DerivedAlign, true);
210 }
211
John McCall13a39c62012-08-01 05:04:58 +0000212 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000213 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000214 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000215 VirtualOffset =
216 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000217 }
Anders Carlssond829a022010-04-24 21:06:20 +0000218
John McCall13a39c62012-08-01 05:04:58 +0000219 // Apply both offsets.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000220 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000221 NonVirtualOffset,
Anders Carlssond829a022010-04-24 21:06:20 +0000222 VirtualOffset);
223
John McCall13a39c62012-08-01 05:04:58 +0000224 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000225 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000226
227 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000228 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000229 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
230 Builder.CreateBr(endBB);
231 EmitBlock(endBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000232
John McCall13a39c62012-08-01 05:04:58 +0000233 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
234 PHI->addIncoming(Value, notNullBB);
235 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000236 Value = PHI;
237 }
238
239 return Value;
240}
241
242llvm::Value *
Anders Carlsson8c793172009-11-23 17:57:54 +0000243CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000244 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000245 CastExpr::path_const_iterator PathBegin,
246 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000247 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000248 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000249
Anders Carlsson8c793172009-11-23 17:57:54 +0000250 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000251 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000252 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000253
Anders Carlsson600f7372010-01-31 01:43:37 +0000254 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000255 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Anders Carlsson600f7372010-01-31 01:43:37 +0000256
257 if (!NonVirtualOffset) {
258 // No offset, we can just cast back.
259 return Builder.CreateBitCast(Value, DerivedPtrTy);
260 }
Craig Topper8a13c412014-05-21 05:09:00 +0000261
262 llvm::BasicBlock *CastNull = nullptr;
263 llvm::BasicBlock *CastNotNull = nullptr;
264 llvm::BasicBlock *CastEnd = nullptr;
265
Anders Carlsson8c793172009-11-23 17:57:54 +0000266 if (NullCheckValue) {
267 CastNull = createBasicBlock("cast.null");
268 CastNotNull = createBasicBlock("cast.notnull");
269 CastEnd = createBasicBlock("cast.end");
270
Anders Carlsson98981b12011-04-11 00:30:07 +0000271 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000272 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
273 EmitBlock(CastNotNull);
274 }
275
Anders Carlsson600f7372010-01-31 01:43:37 +0000276 // Apply the offset.
Eli Friedman87549262012-02-28 22:07:56 +0000277 Value = Builder.CreateBitCast(Value, Int8PtrTy);
278 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
279 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000280
281 // Just cast.
282 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000283
284 if (NullCheckValue) {
285 Builder.CreateBr(CastEnd);
286 EmitBlock(CastNull);
287 Builder.CreateBr(CastEnd);
288 EmitBlock(CastEnd);
289
Jay Foad20c0f022011-03-30 11:28:58 +0000290 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000291 PHI->addIncoming(Value, CastNotNull);
292 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
293 CastNull);
294 Value = PHI;
295 }
296
297 return Value;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000298}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000299
300llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
301 bool ForVirtualBase,
302 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000303 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000304 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000305 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000306 }
307
John McCalldec348f72013-05-03 07:33:41 +0000308 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000309 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000310
Anders Carlssone36a6b32010-01-02 01:01:18 +0000311 llvm::Value *VTT;
312
John McCall5c60a6f2010-02-18 19:59:28 +0000313 uint64_t SubVTTIndex;
314
Douglas Gregor61535002013-01-31 05:50:40 +0000315 if (Delegating) {
316 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000317 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000318 } else if (RD == Base) {
319 // If the record matches the base, this is the complete ctor/dtor
320 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000321 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000322 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000323 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000324 SubVTTIndex = 0;
325 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000326 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Ken Dyck16ffcac2011-03-24 01:21:01 +0000327 CharUnits BaseOffset = ForVirtualBase ?
328 Layout.getVBaseClassOffset(Base) :
329 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000330
331 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000332 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000333 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
334 }
Anders Carlssone36a6b32010-01-02 01:01:18 +0000335
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000336 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000337 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000338 VTT = LoadCXXVTT();
339 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000340 } else {
341 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000342 VTT = CGM.getVTables().GetAddrOfVTT(RD);
343 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000344 }
345
346 return VTT;
347}
348
John McCall1d987562010-07-21 01:23:41 +0000349namespace {
John McCallf99a6312010-07-21 05:30:47 +0000350 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000351 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000352 const CXXRecordDecl *BaseClass;
353 bool BaseIsVirtual;
354 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
355 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000356
Craig Topper4f12f102014-03-12 06:41:41 +0000357 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000358 const CXXRecordDecl *DerivedClass =
359 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
360
361 const CXXDestructorDecl *D = BaseClass->getDestructor();
362 llvm::Value *Addr =
363 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
364 DerivedClass, BaseClass,
365 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000366 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
367 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000368 }
369 };
John McCall769250e2010-09-17 02:31:44 +0000370
371 /// A visitor which checks whether an initializer uses 'this' in a
372 /// way which requires the vtable to be properly set.
373 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> {
374 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super;
375
376 bool UsesThis;
377
378 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {}
379
380 // Black-list all explicit and implicit references to 'this'.
381 //
382 // Do we need to worry about external references to 'this' derived
383 // from arbitrary code? If so, then anything which runs arbitrary
384 // external code might potentially access the vtable.
385 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; }
386 };
387}
388
389static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
390 DynamicThisUseChecker Checker(C);
391 Checker.Visit(const_cast<Expr*>(Init));
392 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000393}
394
Anders Carlssonfb404882009-12-24 22:46:43 +0000395static void EmitBaseInitializer(CodeGenFunction &CGF,
396 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000397 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000398 CXXCtorType CtorType) {
399 assert(BaseInit->isBaseInitializer() &&
400 "Must have base initializer!");
401
402 llvm::Value *ThisPtr = CGF.LoadCXXThis();
403
404 const Type *BaseType = BaseInit->getBaseClass();
405 CXXRecordDecl *BaseClassDecl =
406 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
407
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000408 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000409
410 // The base constructor doesn't construct virtual bases.
411 if (CtorType == Ctor_Base && isBaseVirtual)
412 return;
413
John McCall769250e2010-09-17 02:31:44 +0000414 // If the initializer for the base (other than the constructor
415 // itself) accesses 'this' in any way, we need to initialize the
416 // vtables.
417 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
418 CGF.InitializeVTablePointers(ClassDecl);
419
John McCall6ce74722010-02-16 04:15:37 +0000420 // We can pretend to be a complete class because it only matters for
421 // virtual bases, and we only do virtual bases for complete ctors.
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000422 llvm::Value *V =
423 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000424 BaseClassDecl,
425 isBaseVirtual);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000426 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall8d6fc952011-08-25 20:40:09 +0000427 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000428 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000429 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000430 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000431 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000432
433 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Anders Carlsson5ade5d32010-02-06 20:00:21 +0000434
David Blaikiebbafb8a2012-03-11 07:00:24 +0000435 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000436 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000437 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
438 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000439}
440
Douglas Gregor94f9a482010-05-05 05:51:00 +0000441static void EmitAggMemberInitializer(CodeGenFunction &CGF,
442 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000443 Expr *Init,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000444 llvm::Value *ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000445 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000446 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000447 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000448 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000449 LValue LV = LHS;
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000450
Richard Smithcc1b96d2013-06-12 22:31:48 +0000451 if (ArrayIndexVar) {
452 // If we have an array index variable, load it and use it as an offset.
453 // Then, increment the value.
454 llvm::Value *Dest = LHS.getAddress();
455 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
456 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
457 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
458 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
459 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000460
Richard Smithcc1b96d2013-06-12 22:31:48 +0000461 // Update the LValue.
462 LV.setAddress(Dest);
463 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
464 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000465 }
John McCall7a626f62010-09-15 10:14:12 +0000466
Richard Smithcc1b96d2013-06-12 22:31:48 +0000467 switch (CGF.getEvaluationKind(T)) {
468 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000469 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000470 break;
471 case TEK_Complex:
472 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
473 break;
474 case TEK_Aggregate: {
475 AggValueSlot Slot =
476 AggValueSlot::forLValue(LV,
477 AggValueSlot::IsDestructed,
478 AggValueSlot::DoesNotNeedGCBarriers,
479 AggValueSlot::IsNotAliased);
480
481 CGF.EmitAggExpr(Init, Slot);
482 break;
483 }
484 }
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000485
Douglas Gregor94f9a482010-05-05 05:51:00 +0000486 return;
487 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000488
Douglas Gregor94f9a482010-05-05 05:51:00 +0000489 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
490 assert(Array && "Array initialization without the array type?");
491 llvm::Value *IndexVar
Eli Friedman6ae63022012-02-14 02:15:49 +0000492 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000493 assert(IndexVar && "Array index variable not loaded");
494
495 // Initialize this index variable to zero.
496 llvm::Value* Zero
497 = llvm::Constant::getNullValue(
498 CGF.ConvertType(CGF.getContext().getSizeType()));
499 CGF.Builder.CreateStore(Zero, IndexVar);
500
501 // Start the loop with a block that tests the condition.
502 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
503 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
504
505 CGF.EmitBlock(CondBlock);
506
507 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
508 // Generate: if (loop-index < number-of-elements) fall to the loop body,
509 // otherwise, go to the block after the for-loop.
510 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000511 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000512 llvm::Value *NumElementsPtr =
513 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000514 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
515 "isless");
516
517 // If the condition is true, execute the body.
518 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
519
520 CGF.EmitBlock(ForBody);
521 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000522
523 // Inside the loop body recurse to emit the inner loop or, eventually, the
524 // constructor call.
525 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
526 Array->getElementType(), ArrayIndexes, Index + 1);
527
Douglas Gregor94f9a482010-05-05 05:51:00 +0000528 CGF.EmitBlock(ContinueBlock);
529
530 // Emit the increment of the loop counter.
531 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
532 Counter = CGF.Builder.CreateLoad(IndexVar);
533 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
534 CGF.Builder.CreateStore(NextVal, IndexVar);
535
536 // Finally, branch back up to the condition for the next iteration.
537 CGF.EmitBranch(CondBlock);
538
539 // Emit the fall-through block.
540 CGF.EmitBlock(AfterFor, true);
541}
John McCall1d987562010-07-21 01:23:41 +0000542
Anders Carlssonfb404882009-12-24 22:46:43 +0000543static void EmitMemberInitializer(CodeGenFunction &CGF,
544 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000545 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000546 const CXXConstructorDecl *Constructor,
547 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000548 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000549 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000550 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000551 assert(MemberInit->getInit() && "Must have initializer!");
Anders Carlssonfb404882009-12-24 22:46:43 +0000552
553 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000554 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000555 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000556
557 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000558 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000559 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000560
Francois Pichetd583da02010-12-04 09:14:42 +0000561 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000562 // If we are initializing an anonymous union field, drill down to
563 // the field.
564 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
Aaron Ballman29c94602014-03-07 18:36:15 +0000565 for (const auto *I : IndirectField->chain())
Aaron Ballman13916082014-03-07 18:11:58 +0000566 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
Francois Pichetd583da02010-12-04 09:14:42 +0000567 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000568 } else {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000569 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlssonfb404882009-12-24 22:46:43 +0000570 }
571
Eli Friedman6ae63022012-02-14 02:15:49 +0000572 // Special case: if we are in a copy or move constructor, and we are copying
573 // an array of PODs or classes with trivial copy constructors, ignore the
574 // AST and perform the copy we know is equivalent.
575 // FIXME: This is hacky at best... if we had a bit more explicit information
576 // in the AST, we could generalize it more easily.
577 const ConstantArrayType *Array
578 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000579 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000580 Constructor->isCopyOrMoveConstructor()) {
581 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000582 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000583 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith993f25a2012-11-07 23:56:21 +0000584 (CE && CE->getConstructor()->isTrivial())) {
David Majnemer1573d732014-10-15 04:54:54 +0000585 unsigned SrcArgIndex =
586 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000587 llvm::Value *SrcPtr
588 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000589 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
590 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Eli Friedman6ae63022012-02-14 02:15:49 +0000591
592 // Copy the aggregate.
593 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000594 LHS.isVolatileQualified());
Eli Friedman6ae63022012-02-14 02:15:49 +0000595 return;
596 }
597 }
598
599 ArrayRef<VarDecl *> ArrayIndexes;
600 if (MemberInit->getNumArrayIndices())
601 ArrayIndexes = MemberInit->getArrayIndexes();
David Blaikie66e41972015-01-14 07:38:27 +0000602 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000603}
604
David Blaikie66e41972015-01-14 07:38:27 +0000605void CodeGenFunction::EmitInitializerForField(
606 FieldDecl *Field, LValue LHS, Expr *Init,
607 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000608 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000609 switch (getEvaluationKind(FieldType)) {
610 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000611 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000612 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000613 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000614 RValue RHS = RValue::get(EmitScalarExpr(Init));
615 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000616 }
John McCall47fb9502013-03-07 21:37:08 +0000617 break;
618 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000619 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000620 break;
621 case TEK_Aggregate: {
Craig Topper8a13c412014-05-21 05:09:00 +0000622 llvm::Value *ArrayIndexVar = nullptr;
Eli Friedman6ae63022012-02-14 02:15:49 +0000623 if (ArrayIndexes.size()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000624 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Douglas Gregor94f9a482010-05-05 05:51:00 +0000625
626 // The LHS is a pointer to the first object we'll be constructing, as
627 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000628 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
629 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000630 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000631 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
632 BasePtr);
633 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000634
635 // Create an array index that will be used to walk over all of the
636 // objects we're constructing.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000637 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregor94f9a482010-05-05 05:51:00 +0000638 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000639 Builder.CreateStore(Zero, ArrayIndexVar);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000640
Douglas Gregor94f9a482010-05-05 05:51:00 +0000641
642 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000643 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000644 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000645 }
646
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000647 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000648 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000649 }
John McCall47fb9502013-03-07 21:37:08 +0000650 }
John McCall12cc42a2013-02-01 05:11:40 +0000651
652 // Ensure that we destroy this object if an exception is thrown
653 // later in the constructor.
654 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
655 if (needsEHCleanup(dtorKind))
656 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000657}
658
John McCallf8ff7b92010-02-23 00:48:20 +0000659/// Checks whether the given constructor is a valid subject for the
660/// complete-to-base constructor delegation optimization, i.e.
661/// emitting the complete constructor as a simple call to the base
662/// constructor.
663static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
664
665 // Currently we disable the optimization for classes with virtual
666 // bases because (1) the addresses of parameter variables need to be
667 // consistent across all initializers but (2) the delegate function
668 // call necessarily creates a second copy of the parameter variable.
669 //
670 // The limiting example (purely theoretical AFAIK):
671 // struct A { A(int &c) { c++; } };
672 // struct B : virtual A {
673 // B(int count) : A(count) { printf("%d\n", count); }
674 // };
675 // ...although even this example could in principle be emitted as a
676 // delegation since the address of the parameter doesn't escape.
677 if (Ctor->getParent()->getNumVBases()) {
678 // TODO: white-list trivial vbase initializers. This case wouldn't
679 // be subject to the restrictions below.
680
681 // TODO: white-list cases where:
682 // - there are no non-reference parameters to the constructor
683 // - the initializers don't access any non-reference parameters
684 // - the initializers don't take the address of non-reference
685 // parameters
686 // - etc.
687 // If we ever add any of the above cases, remember that:
688 // - function-try-blocks will always blacklist this optimization
689 // - we need to perform the constructor prologue and cleanup in
690 // EmitConstructorBody.
691
692 return false;
693 }
694
695 // We also disable the optimization for variadic functions because
696 // it's impossible to "re-pass" varargs.
697 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
698 return false;
699
Alexis Hunt61bc1732011-05-01 07:04:31 +0000700 // FIXME: Decide if we can do a delegation of a delegating constructor.
701 if (Ctor->isDelegatingConstructor())
702 return false;
703
John McCallf8ff7b92010-02-23 00:48:20 +0000704 return true;
705}
706
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000707// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
708// to poison the extra field paddings inserted under
709// -fsanitize-address-field-padding=1|2.
710void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
711 ASTContext &Context = getContext();
712 const CXXRecordDecl *ClassDecl =
713 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
714 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
715 if (!ClassDecl->mayInsertExtraPadding()) return;
716
717 struct SizeAndOffset {
718 uint64_t Size;
719 uint64_t Offset;
720 };
721
722 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
723 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
724
725 // Populate sizes and offsets of fields.
726 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
727 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
728 SSV[i].Offset =
729 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
730
731 size_t NumFields = 0;
732 for (const auto *Field : ClassDecl->fields()) {
733 const FieldDecl *D = Field;
734 std::pair<CharUnits, CharUnits> FieldInfo =
735 Context.getTypeInfoInChars(D->getType());
736 CharUnits FieldSize = FieldInfo.first;
737 assert(NumFields < SSV.size());
738 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
739 NumFields++;
740 }
741 assert(NumFields == SSV.size());
742 if (SSV.size() <= 1) return;
743
744 // We will insert calls to __asan_* run-time functions.
745 // LLVM AddressSanitizer pass may decide to inline them later.
746 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
747 llvm::FunctionType *FTy =
748 llvm::FunctionType::get(CGM.VoidTy, Args, false);
749 llvm::Constant *F = CGM.CreateRuntimeFunction(
750 FTy, Prologue ? "__asan_poison_intra_object_redzone"
751 : "__asan_unpoison_intra_object_redzone");
752
753 llvm::Value *ThisPtr = LoadCXXThis();
754 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000755 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000756 // For each field check if it has sufficient padding,
757 // if so (un)poison it with a call.
758 for (size_t i = 0; i < SSV.size(); i++) {
759 uint64_t AsanAlignment = 8;
760 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
761 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
762 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
763 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
764 (NextField % AsanAlignment) != 0)
765 continue;
766 Builder.CreateCall2(
767 F, Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
768 Builder.getIntN(PtrSize, PoisonSize));
769 }
770}
771
John McCallb81884d2010-02-19 09:25:03 +0000772/// EmitConstructorBody - Emits the body of the current constructor.
773void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000774 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000775 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
776 CXXCtorType CtorType = CurGD.getCtorType();
777
Reid Kleckner340ad862014-01-13 22:57:31 +0000778 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
779 CtorType == Ctor_Complete) &&
780 "can only generate complete ctor for this ABI");
781
John McCallf8ff7b92010-02-23 00:48:20 +0000782 // Before we go any further, try the complete->base constructor
783 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000784 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000785 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000786 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000787 return;
788 }
789
Richard Smith46bb5812014-08-01 01:56:39 +0000790 const FunctionDecl *Definition = 0;
791 Stmt *Body = Ctor->getBody(Definition);
792 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000793
John McCallf8ff7b92010-02-23 00:48:20 +0000794 // Enter the function-try-block before the constructor prologue if
795 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000796 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000797 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000798 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000799
Justin Bogner66242d62015-04-23 23:06:47 +0000800 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000801
Richard Smithcc1b96d2013-06-12 22:31:48 +0000802 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000803
John McCall88313032012-03-30 04:25:03 +0000804 // TODO: in restricted cases, we can emit the vbase initializers of
805 // a complete ctor and then delegate to the base ctor.
806
John McCallf8ff7b92010-02-23 00:48:20 +0000807 // Emit the constructor prologue, i.e. the base and member
808 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000809 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000810
811 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000812 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000813 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
814 else if (Body)
815 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000816
817 // Emit any cleanup blocks associated with the member or base
818 // initializers, which includes (along the exceptional path) the
819 // destructors for those members and bases that were fully
820 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000821 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000822
John McCallf8ff7b92010-02-23 00:48:20 +0000823 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000824 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000825}
826
Lang Hamesbf122742013-02-17 07:22:09 +0000827namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000828 /// RAII object to indicate that codegen is copying the value representation
829 /// instead of the object representation. Useful when copying a struct or
830 /// class which has uninitialized members and we're only performing
831 /// lvalue-to-rvalue conversion on the object but not its members.
832 class CopyingValueRepresentation {
833 public:
834 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000835 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000836 CGF.SanOpts.set(SanitizerKind::Bool, false);
837 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000838 }
839 ~CopyingValueRepresentation() {
840 CGF.SanOpts = OldSanOpts;
841 }
842 private:
843 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000844 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000845 };
846}
847
848namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000849 class FieldMemcpyizer {
850 public:
851 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
852 const VarDecl *SrcRec)
853 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
854 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000855 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
856 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000857
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000858 bool isMemcpyableField(FieldDecl *F) const {
859 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000860 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000861 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000862 Qualifiers Qual = F->getType().getQualifiers();
863 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
864 return false;
865 return true;
866 }
867
868 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000869 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000870 addInitialField(F);
871 else
872 addNextField(F);
873 }
874
David Majnemera586eb22014-10-10 18:57:10 +0000875 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000876 unsigned LastFieldSize =
877 LastField->isBitField() ?
878 LastField->getBitWidthValue(CGF.getContext()) :
879 CGF.getContext().getTypeSize(LastField->getType());
880 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000881 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000882 CGF.getContext().getCharWidth() - 1;
883 CharUnits MemcpySize =
884 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
885 return MemcpySize;
886 }
887
888 void emitMemcpy() {
889 // Give the subclass a chance to bail out if it feels the memcpy isn't
890 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000891 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000892 return;
893 }
894
Lang Hames1694e0d2013-02-27 04:14:49 +0000895 CharUnits Alignment;
Lang Hamesbf122742013-02-17 07:22:09 +0000896
David Majnemera586eb22014-10-10 18:57:10 +0000897 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000898 if (FirstField->isBitField()) {
899 const CGRecordLayout &RL =
900 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
901 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames1694e0d2013-02-27 04:14:49 +0000902 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
David Majnemera586eb22014-10-10 18:57:10 +0000903 // FirstFieldOffset is not appropriate for bitfields,
904 // it won't tell us what the storage offset should be and thus might not
905 // be properly aligned.
906 //
907 // Instead calculate the storage offset using the offset of the field in
908 // the struct type.
909 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
910 FirstByteOffset =
911 DL.getStructLayout(RL.getLLVMType())
912 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
Lang Hames1694e0d2013-02-27 04:14:49 +0000913 } else {
Lang Hames224ae882013-03-05 20:27:24 +0000914 Alignment = CGF.getContext().getDeclAlign(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000915 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000916 }
Lang Hamesbf122742013-02-17 07:22:09 +0000917
David Majnemera586eb22014-10-10 18:57:10 +0000918 assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
Lang Hames1694e0d2013-02-27 04:14:49 +0000919 Alignment) == 0 && "Bad field alignment.");
920
David Majnemera586eb22014-10-10 18:57:10 +0000921 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000922 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
923 llvm::Value *ThisPtr = CGF.LoadCXXThis();
924 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
925 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
926 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
927 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
928 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
929
930 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
931 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
932 MemcpySize, Alignment);
933 reset();
934 }
935
936 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000937 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000938 }
939
940 protected:
941 CodeGenFunction &CGF;
942 const CXXRecordDecl *ClassDecl;
943
944 private:
945
946 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
947 CharUnits Size, CharUnits Alignment) {
948 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
949 llvm::Type *DBP =
950 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
951 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
952
953 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
954 llvm::Type *SBP =
955 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
956 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
957
958 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
959 Alignment.getQuantity());
960 }
961
962 void addInitialField(FieldDecl *F) {
963 FirstField = F;
964 LastField = F;
965 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
966 LastFieldOffset = FirstFieldOffset;
967 LastAddedFieldIndex = F->getFieldIndex();
968 return;
969 }
970
971 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000972 // For the most part, the following invariant will hold:
973 // F->getFieldIndex() == LastAddedFieldIndex + 1
974 // The one exception is that Sema won't add a copy-initializer for an
975 // unnamed bitfield, which will show up here as a gap in the sequence.
976 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
977 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000978 LastAddedFieldIndex = F->getFieldIndex();
979
980 // The 'first' and 'last' fields are chosen by offset, rather than field
981 // index. This allows the code to support bitfields, as well as regular
982 // fields.
983 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
984 if (FOffset < FirstFieldOffset) {
985 FirstField = F;
986 FirstFieldOffset = FOffset;
987 } else if (FOffset > LastFieldOffset) {
988 LastField = F;
989 LastFieldOffset = FOffset;
990 }
991 }
992
993 const VarDecl *SrcRec;
994 const ASTRecordLayout &RecLayout;
995 FieldDecl *FirstField;
996 FieldDecl *LastField;
997 uint64_t FirstFieldOffset, LastFieldOffset;
998 unsigned LastAddedFieldIndex;
999 };
1000
1001 class ConstructorMemcpyizer : public FieldMemcpyizer {
1002 private:
1003
1004 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001005 /// constructor.
1006 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1007 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001008 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001009 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001010 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001011 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001012 }
1013
1014 // Returns true if a CXXCtorInitializer represents a member initialization
1015 // that can be rolled into a memcpy.
1016 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1017 if (!MemcpyableCtor)
1018 return false;
1019 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001020 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001021 QualType FieldType = Field->getType();
1022 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1023
1024 // Bail out on non-POD, not-trivially-constructable members.
1025 if (!(CE && CE->getConstructor()->isTrivial()) &&
1026 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1027 FieldType->isReferenceType()))
1028 return false;
1029
1030 // Bail out on volatile fields.
1031 if (!isMemcpyableField(Field))
1032 return false;
1033
1034 // Otherwise we're good.
1035 return true;
1036 }
1037
1038 public:
1039 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1040 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001041 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001042 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001043 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001044 CD->isCopyOrMoveConstructor() &&
1045 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1046 Args(Args) { }
1047
1048 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1049 if (isMemberInitMemcpyable(MemberInit)) {
1050 AggregatedInits.push_back(MemberInit);
1051 addMemcpyableField(MemberInit->getMember());
1052 } else {
1053 emitAggregatedInits();
1054 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1055 ConstructorDecl, Args);
1056 }
1057 }
1058
1059 void emitAggregatedInits() {
1060 if (AggregatedInits.size() <= 1) {
1061 // This memcpy is too small to be worthwhile. Fall back on default
1062 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001063 if (!AggregatedInits.empty()) {
1064 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001065 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001066 AggregatedInits[0], ConstructorDecl, Args);
Lang Hamesbf122742013-02-17 07:22:09 +00001067 }
1068 reset();
1069 return;
1070 }
1071
1072 pushEHDestructors();
1073 emitMemcpy();
1074 AggregatedInits.clear();
1075 }
1076
1077 void pushEHDestructors() {
1078 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1079 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1080 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1081
1082 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1083 QualType FieldType = AggregatedInits[i]->getMember()->getType();
1084 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1085 if (CGF.needsEHCleanup(dtorKind))
1086 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1087 }
1088 }
1089
1090 void finish() {
1091 emitAggregatedInits();
1092 }
1093
1094 private:
1095 const CXXConstructorDecl *ConstructorDecl;
1096 bool MemcpyableCtor;
1097 FunctionArgList &Args;
1098 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1099 };
1100
1101 class AssignmentMemcpyizer : public FieldMemcpyizer {
1102 private:
1103
1104 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001105 // exists. Otherwise returns null.
1106 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001107 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001108 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001109 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1110 // Recognise trivial assignments.
1111 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001112 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001113 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1114 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001115 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001116 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1117 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001118 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001119 Stmt *RHS = BO->getRHS();
1120 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1121 RHS = EC->getSubExpr();
1122 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001123 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001124 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1125 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
Craig Topper8a13c412014-05-21 05:09:00 +00001126 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001127 return Field;
1128 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1129 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
1130 if (!(MD && (MD->isCopyAssignmentOperator() ||
1131 MD->isMoveAssignmentOperator()) &&
1132 MD->isTrivial()))
Craig Topper8a13c412014-05-21 05:09:00 +00001133 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001134 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1135 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001136 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001137 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1138 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001139 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001140 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1141 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001142 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001143 return Field;
1144 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1145 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1146 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001147 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001148 Expr *DstPtr = CE->getArg(0);
1149 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1150 DstPtr = DC->getSubExpr();
1151 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1152 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001153 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001154 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1155 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001156 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001157 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1158 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001159 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001160 Expr *SrcPtr = CE->getArg(1);
1161 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1162 SrcPtr = SC->getSubExpr();
1163 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1164 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001165 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001166 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1167 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001168 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001169 return Field;
1170 }
1171
Craig Topper8a13c412014-05-21 05:09:00 +00001172 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001173 }
1174
1175 bool AssignmentsMemcpyable;
1176 SmallVector<Stmt*, 16> AggregatedStmts;
1177
1178 public:
1179
1180 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1181 FunctionArgList &Args)
1182 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1183 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1184 assert(Args.size() == 2);
1185 }
1186
1187 void emitAssignment(Stmt *S) {
1188 FieldDecl *F = getMemcpyableField(S);
1189 if (F) {
1190 addMemcpyableField(F);
1191 AggregatedStmts.push_back(S);
1192 } else {
1193 emitAggregatedStmts();
1194 CGF.EmitStmt(S);
1195 }
1196 }
1197
1198 void emitAggregatedStmts() {
1199 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001200 if (!AggregatedStmts.empty()) {
1201 CopyingValueRepresentation CVR(CGF);
1202 CGF.EmitStmt(AggregatedStmts[0]);
1203 }
Lang Hamesbf122742013-02-17 07:22:09 +00001204 reset();
1205 }
1206
1207 emitMemcpy();
1208 AggregatedStmts.clear();
1209 }
1210
1211 void finish() {
1212 emitAggregatedStmts();
1213 }
1214 };
1215
1216}
1217
Anders Carlssonfb404882009-12-24 22:46:43 +00001218/// EmitCtorPrologue - This routine generates necessary code to initialize
1219/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001220void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001221 CXXCtorType CtorType,
1222 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001223 if (CD->isDelegatingConstructor())
1224 return EmitDelegatingCXXConstructorCall(CD, Args);
1225
Anders Carlssonfb404882009-12-24 22:46:43 +00001226 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001227
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001228 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1229 E = CD->init_end();
1230
Craig Topper8a13c412014-05-21 05:09:00 +00001231 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001232 if (ClassDecl->getNumVBases() &&
1233 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1234 // The ABIs that don't have constructor variants need to put a branch
1235 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001236 BaseCtorContinueBB =
1237 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001238 assert(BaseCtorContinueBB);
1239 }
1240
1241 // Virtual base initializers first.
1242 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1243 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1244 }
1245
1246 if (BaseCtorContinueBB) {
1247 // Complete object handler should continue to the remaining initializers.
1248 Builder.CreateBr(BaseCtorContinueBB);
1249 EmitBlock(BaseCtorContinueBB);
1250 }
1251
1252 // Then, non-virtual base initializers.
1253 for (; B != E && (*B)->isBaseInitializer(); B++) {
1254 assert(!(*B)->isBaseVirtual());
1255 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001256 }
1257
Anders Carlssond5895932010-03-28 21:07:49 +00001258 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001259
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001260 // And finally, initialize class members.
Richard Smith852c9db2013-04-20 22:23:05 +00001261 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hamesbf122742013-02-17 07:22:09 +00001262 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001263 for (; B != E; B++) {
1264 CXXCtorInitializer *Member = (*B);
1265 assert(!Member->isBaseInitializer());
1266 assert(Member->isAnyMemberInitializer() &&
1267 "Delegating initializer on non-delegating constructor");
1268 CM.addMemberInitializer(Member);
1269 }
Lang Hamesbf122742013-02-17 07:22:09 +00001270 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001271}
1272
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001273static bool
1274FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1275
1276static bool
1277HasTrivialDestructorBody(ASTContext &Context,
1278 const CXXRecordDecl *BaseClassDecl,
1279 const CXXRecordDecl *MostDerivedClassDecl)
1280{
1281 // If the destructor is trivial we don't have to check anything else.
1282 if (BaseClassDecl->hasTrivialDestructor())
1283 return true;
1284
1285 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1286 return false;
1287
1288 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001289 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001290 if (!FieldHasTrivialDestructorBody(Context, Field))
1291 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001292
1293 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001294 for (const auto &I : BaseClassDecl->bases()) {
1295 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001296 continue;
1297
1298 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001299 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001300 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1301 MostDerivedClassDecl))
1302 return false;
1303 }
1304
1305 if (BaseClassDecl == MostDerivedClassDecl) {
1306 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001307 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001308 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001309 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001310 if (!HasTrivialDestructorBody(Context, VirtualBase,
1311 MostDerivedClassDecl))
1312 return false;
1313 }
1314 }
1315
1316 return true;
1317}
1318
1319static bool
1320FieldHasTrivialDestructorBody(ASTContext &Context,
1321 const FieldDecl *Field)
1322{
1323 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1324
1325 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1326 if (!RT)
1327 return true;
1328
1329 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
1330 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1331}
1332
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001333/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1334/// any vtable pointers before calling this destructor.
1335static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +00001336 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001337 if (!Dtor->hasTrivialBody())
1338 return false;
1339
1340 // Check the fields.
1341 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001342 for (const auto *Field : ClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001343 if (!FieldHasTrivialDestructorBody(Context, Field))
1344 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001345
1346 return true;
1347}
1348
John McCallb81884d2010-02-19 09:25:03 +00001349/// EmitDestructorBody - Emits the body of the current destructor.
1350void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1351 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1352 CXXDtorType DtorType = CurGD.getDtorType();
1353
John McCallf99a6312010-07-21 05:30:47 +00001354 // The call to operator delete in a deleting destructor happens
1355 // outside of the function-try-block, which means it's always
1356 // possible to delegate the destructor body to the complete
1357 // destructor. Do so.
1358 if (DtorType == Dtor_Deleting) {
1359 EnterDtorCleanups(Dtor, Dtor_Deleting);
1360 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001361 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001362 PopCleanupBlock();
1363 return;
1364 }
1365
John McCallb81884d2010-02-19 09:25:03 +00001366 Stmt *Body = Dtor->getBody();
1367
1368 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001369 // anything else.
1370 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001371 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001372 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001373 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001374
John McCallf99a6312010-07-21 05:30:47 +00001375 // Enter the epilogue cleanups.
1376 RunCleanupsScope DtorEpilogue(*this);
1377
John McCallb81884d2010-02-19 09:25:03 +00001378 // If this is the complete variant, just invoke the base variant;
1379 // the epilogue will destruct the virtual bases. But we can't do
1380 // this optimization if the body is a function-try-block, because
Reid Klecknere7de47e2013-07-22 13:51:44 +00001381 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
1382 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001383 switch (DtorType) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00001384 case Dtor_Comdat:
1385 llvm_unreachable("not expecting a COMDAT");
1386
John McCallf99a6312010-07-21 05:30:47 +00001387 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1388
1389 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001390 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1391 "can't emit a dtor without a body for non-Microsoft ABIs");
1392
John McCallf99a6312010-07-21 05:30:47 +00001393 // Enter the cleanup scopes for virtual bases.
1394 EnterDtorCleanups(Dtor, Dtor_Complete);
1395
Reid Klecknere7de47e2013-07-22 13:51:44 +00001396 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001397 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001398 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001399 break;
1400 }
1401 // Fallthrough: act like we're in the base variant.
John McCallb81884d2010-02-19 09:25:03 +00001402
John McCallf99a6312010-07-21 05:30:47 +00001403 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001404 assert(Body);
1405
Justin Bogner66242d62015-04-23 23:06:47 +00001406 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +00001407
John McCallf99a6312010-07-21 05:30:47 +00001408 // Enter the cleanup scopes for fields and non-virtual bases.
1409 EnterDtorCleanups(Dtor, Dtor_Base);
1410
1411 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001412 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1413 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +00001414
1415 if (isTryBody)
1416 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1417 else if (Body)
1418 EmitStmt(Body);
1419 else {
1420 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1421 // nothing to do besides what's in the epilogue
1422 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001423 // -fapple-kext must inline any call to this dtor into
1424 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001425 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +00001426 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +00001427 break;
John McCallb81884d2010-02-19 09:25:03 +00001428 }
1429
John McCallf99a6312010-07-21 05:30:47 +00001430 // Jump out through the epilogue cleanups.
1431 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001432
1433 // Exit the try if applicable.
1434 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001435 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001436}
1437
Lang Hamesbf122742013-02-17 07:22:09 +00001438void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1439 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1440 const Stmt *RootS = AssignOp->getBody();
1441 assert(isa<CompoundStmt>(RootS) &&
1442 "Body of an implicit assignment operator should be compound stmt.");
1443 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1444
1445 LexicalScope Scope(*this, RootCS->getSourceRange());
1446
1447 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001448 for (auto *I : RootCS->body())
1449 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001450 AM.finish();
1451}
1452
John McCallf99a6312010-07-21 05:30:47 +00001453namespace {
1454 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +00001455 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001456 CallDtorDelete() {}
1457
Craig Topper4f12f102014-03-12 06:41:41 +00001458 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001459 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1460 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1461 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1462 CGF.getContext().getTagDeclType(ClassDecl));
1463 }
1464 };
1465
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001466 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1467 llvm::Value *ShouldDeleteCondition;
1468 public:
1469 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1470 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001471 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001472 }
1473
Craig Topper4f12f102014-03-12 06:41:41 +00001474 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001475 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1476 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1477 llvm::Value *ShouldCallDelete
1478 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1479 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1480
1481 CGF.EmitBlock(callDeleteBB);
1482 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1483 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1484 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1485 CGF.getContext().getTagDeclType(ClassDecl));
1486 CGF.Builder.CreateBr(continueBB);
1487
1488 CGF.EmitBlock(continueBB);
1489 }
1490 };
1491
John McCall4bd0fb12011-07-12 16:41:08 +00001492 class DestroyField : public EHScopeStack::Cleanup {
1493 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001494 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001495 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001496
John McCall4bd0fb12011-07-12 16:41:08 +00001497 public:
1498 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1499 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001500 : field(field), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001501 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001502
Craig Topper4f12f102014-03-12 06:41:41 +00001503 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001504 // Find the address of the field.
1505 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001506 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1507 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1508 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001509 assert(LV.isSimple());
1510
1511 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001512 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001513 }
1514 };
1515}
1516
Hans Wennborgdeff7032013-12-18 01:39:59 +00001517/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001518/// destructor. This is to call destructors on members and base classes
1519/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001520void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1521 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001522 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1523 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001524
John McCallf99a6312010-07-21 05:30:47 +00001525 // The deleting-destructor phase just needs to call the appropriate
1526 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001527 if (DtorType == Dtor_Deleting) {
1528 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001529 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001530 if (CXXStructorImplicitParamValue) {
1531 // If there is an implicit param to the deleting dtor, it's a boolean
1532 // telling whether we should call delete at the end of the dtor.
1533 EHStack.pushCleanup<CallDtorDeleteConditional>(
1534 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1535 } else {
1536 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1537 }
John McCall5c60a6f2010-02-18 19:59:28 +00001538 return;
1539 }
1540
John McCallf99a6312010-07-21 05:30:47 +00001541 const CXXRecordDecl *ClassDecl = DD->getParent();
1542
Richard Smith20104042011-09-18 12:11:43 +00001543 // Unions have no bases and do not call field destructors.
1544 if (ClassDecl->isUnion())
1545 return;
1546
John McCallf99a6312010-07-21 05:30:47 +00001547 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001548 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001549
1550 // We push them in the forward order so that they'll be popped in
1551 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001552 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001553 CXXRecordDecl *BaseClassDecl
1554 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
1555
1556 // Ignore trivial destructors.
1557 if (BaseClassDecl->hasTrivialDestructor())
1558 continue;
John McCallf99a6312010-07-21 05:30:47 +00001559
John McCallcda666c2010-07-21 07:22:38 +00001560 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1561 BaseClassDecl,
1562 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001563 }
John McCallf99a6312010-07-21 05:30:47 +00001564
John McCall5c60a6f2010-02-18 19:59:28 +00001565 return;
1566 }
1567
1568 assert(DtorType == Dtor_Base);
John McCallf99a6312010-07-21 05:30:47 +00001569
1570 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001571 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001572 // Ignore virtual bases.
1573 if (Base.isVirtual())
1574 continue;
1575
1576 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
1577
1578 // Ignore trivial destructors.
1579 if (BaseClassDecl->hasTrivialDestructor())
1580 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001581
John McCallcda666c2010-07-21 07:22:38 +00001582 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1583 BaseClassDecl,
1584 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001585 }
1586
1587 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001588 for (const auto *Field : ClassDecl->fields()) {
1589 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001590 QualType::DestructionKind dtorKind = type.isDestructedType();
1591 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001592
Richard Smith921bd202012-02-26 09:11:52 +00001593 // Anonymous union members do not have their destructors called.
1594 const RecordType *RT = type->getAsUnionType();
1595 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1596
John McCall4bd0fb12011-07-12 16:41:08 +00001597 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001598 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001599 getDestroyer(dtorKind),
1600 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001601 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001602}
1603
John McCallf677a8e2011-07-13 06:10:41 +00001604/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1605/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001606///
John McCallf677a8e2011-07-13 06:10:41 +00001607/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001608/// \param arrayType the type of the array to initialize
1609/// \param arrayBegin an arrayType*
1610/// \param zeroInitialize true if each element should be
1611/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001612void CodeGenFunction::EmitCXXAggrConstructorCall(
1613 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1614 llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001615 QualType elementType;
1616 llvm::Value *numElements =
1617 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001618
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001619 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001620}
1621
John McCallf677a8e2011-07-13 06:10:41 +00001622/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1623/// constructor for each of several members of an array.
1624///
1625/// \param ctor the constructor to call for each element
1626/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001627/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001628/// \param arrayBegin a T*, where T is the type constructed by ctor
1629/// \param zeroInitialize true if each element should be
1630/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001631void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1632 llvm::Value *numElements,
1633 llvm::Value *arrayBegin,
1634 const CXXConstructExpr *E,
1635 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001636
1637 // It's legal for numElements to be zero. This can happen both
1638 // dynamically, because x can be zero in 'new A[x]', and statically,
1639 // because of GCC extensions that permit zero-length arrays. There
1640 // are probably legitimate places where we could assume that this
1641 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001642 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001643
1644 // Optimize for a constant count.
1645 llvm::ConstantInt *constantCount
1646 = dyn_cast<llvm::ConstantInt>(numElements);
1647 if (constantCount) {
1648 // Just skip out if the constant count is zero.
1649 if (constantCount->isZero()) return;
1650
1651 // Otherwise, emit the check.
1652 } else {
1653 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1654 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1655 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1656 EmitBlock(loopBB);
1657 }
1658
John McCallf677a8e2011-07-13 06:10:41 +00001659 // Find the end of the array.
1660 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1661 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001662
John McCallf677a8e2011-07-13 06:10:41 +00001663 // Enter the loop, setting up a phi for the current location to initialize.
1664 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1665 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1666 EmitBlock(loopBB);
1667 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1668 "arrayctor.cur");
1669 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001670
Anders Carlsson27da15b2010-01-01 20:29:01 +00001671 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001672
1673 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001674
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001675 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001676 if (zeroInitialize)
1677 EmitNullInitialization(cur, type);
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001678
Anders Carlsson27da15b2010-01-01 20:29:01 +00001679 // C++ [class.temporary]p4:
1680 // There are two contexts in which temporaries are destroyed at a different
1681 // point than the end of the full-expression. The first context is when a
1682 // default constructor is called to initialize an element of an array.
1683 // If the constructor has one or more default arguments, the destruction of
1684 // every temporary created in a default argument expression is sequenced
1685 // before the construction of the next array element, if any.
1686
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001687 {
John McCallbd309292010-07-06 01:34:17 +00001688 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001689
John McCallf677a8e2011-07-13 06:10:41 +00001690 // Evaluate the constructor and its arguments in a regular
1691 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001692 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001693 !ctor->getParent()->hasTrivialDestructor()) {
1694 Destroyer *destroyer = destroyCXXObject;
1695 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1696 }
1697
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001698 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1699 /*Delegating=*/false, cur, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001700 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001701
John McCallf677a8e2011-07-13 06:10:41 +00001702 // Go to the next element.
1703 llvm::Value *next =
1704 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1705 "arrayctor.next");
1706 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001707
John McCallf677a8e2011-07-13 06:10:41 +00001708 // Check whether that's the end of the loop.
1709 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1710 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1711 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001712
John McCall6549b312011-07-13 07:37:11 +00001713 // Patch the earlier check to skip over the loop.
1714 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1715
John McCallf677a8e2011-07-13 06:10:41 +00001716 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001717}
1718
John McCall82fe67b2011-07-09 01:37:26 +00001719void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1720 llvm::Value *addr,
1721 QualType type) {
1722 const RecordType *rtype = type->castAs<RecordType>();
1723 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1724 const CXXDestructorDecl *dtor = record->getDestructor();
1725 assert(!dtor->isTrivial());
1726 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001727 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001728}
1729
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001730void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1731 CXXCtorType Type,
1732 bool ForVirtualBase,
1733 bool Delegating, llvm::Value *This,
1734 const CXXConstructExpr *E) {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001735 // If this is a trivial constructor, just emit what's needed.
Kostya Serebryany597dcc72014-12-06 01:23:08 +00001736 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding()) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001737 if (E->getNumArgs() == 0) {
John McCallca972cd2010-02-06 00:25:16 +00001738 // Trivial default constructor, no codegen required.
1739 assert(D->isDefaultConstructor() &&
1740 "trivial 0-arg ctor not a default ctor");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001741 return;
1742 }
John McCallca972cd2010-02-06 00:25:16 +00001743
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001744 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001745 assert(D->isCopyOrMoveConstructor() &&
1746 "trivial 1-arg ctor not a copy/move ctor");
John McCallca972cd2010-02-06 00:25:16 +00001747
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001748 const Expr *Arg = E->getArg(0);
David Majnemerfd1e7392015-02-03 23:04:06 +00001749 QualType SrcTy = Arg->getType();
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001750 llvm::Value *Src = EmitLValue(Arg).getAddress();
David Majnemerfd1e7392015-02-03 23:04:06 +00001751 QualType DestTy = getContext().getTypeDeclType(D->getParent());
1752 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001753 return;
1754 }
1755
Reid Kleckner89077a12013-12-17 19:46:40 +00001756 // C++11 [class.mfct.non-static]p2:
1757 // If a non-static member function of a class X is called for an object that
1758 // is not of type X, or of a type derived from X, the behavior is undefined.
1759 // FIXME: Provide a source location here.
1760 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1761 getContext().getRecordType(D->getParent()));
1762
1763 CallArgList Args;
1764
1765 // Push the this ptr.
1766 Args.add(RValue::get(This), D->getThisType(getContext()));
1767
1768 // Add the rest of the user-supplied arguments.
1769 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001770 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
Reid Kleckner89077a12013-12-17 19:46:40 +00001771
1772 // Insert any ABI-specific implicit constructor arguments.
1773 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1774 *this, D, Type, ForVirtualBase, Delegating, Args);
1775
1776 // Emit the call.
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001777 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
Reid Kleckner89077a12013-12-17 19:46:40 +00001778 const CGFunctionInfo &Info =
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001779 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
Reid Kleckner89077a12013-12-17 19:46:40 +00001780 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001781}
1782
John McCallf8ff7b92010-02-23 00:48:20 +00001783void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001784CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1785 llvm::Value *This, llvm::Value *Src,
Alexey Samsonov525bf652014-08-25 21:58:56 +00001786 const CXXConstructExpr *E) {
Kostya Serebryany597dcc72014-12-06 01:23:08 +00001787 if (D->isTrivial() &&
1788 !D->getParent()->mayInsertExtraPadding()) {
Alexey Samsonov96fd0a42014-08-26 20:18:26 +00001789 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001790 assert(D->isCopyOrMoveConstructor() &&
1791 "trivial 1-arg ctor not a copy/move ctor");
David Majnemerfd1e7392015-02-03 23:04:06 +00001792 EmitAggregateCopyCtor(This, Src,
1793 getContext().getTypeDeclType(D->getParent()),
1794 E->arg_begin()->getType());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001795 return;
1796 }
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001797 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001798 assert(D->isInstance() &&
1799 "Trying to emit a member call expr on a static method!");
1800
Reid Kleckner739756c2013-12-04 19:23:12 +00001801 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001802
1803 CallArgList Args;
1804
1805 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001806 Args.add(RValue::get(This), D->getThisType(getContext()));
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001807
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001808 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00001809 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001810 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001811 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001812 Args.add(RValue::get(Src), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00001813
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001814 // Skip over first argument (Src).
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001815 EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1816 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001817
John McCall8dda7b22012-07-07 06:41:13 +00001818 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1819 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001820}
1821
1822void
John McCallf8ff7b92010-02-23 00:48:20 +00001823CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1824 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001825 const FunctionArgList &Args,
1826 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00001827 CallArgList DelegateArgs;
1828
1829 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1830 assert(I != E && "no parameters to constructor");
1831
1832 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001833 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001834 ++I;
1835
1836 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001837 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00001838 /*ForVirtualBase=*/false,
1839 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001840 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001841 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001842
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001843 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001844 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001845 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001846 ++I;
1847 }
1848 }
1849
1850 // Explicit arguments.
1851 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001852 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001853 // FIXME: per-argument source location
1854 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00001855 }
1856
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001857 llvm::Value *Callee =
1858 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001859 EmitCall(CGM.getTypes()
1860 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
Manman Ren01754612013-03-20 16:59:38 +00001861 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00001862}
1863
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001864namespace {
1865 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1866 const CXXDestructorDecl *Dtor;
1867 llvm::Value *Addr;
1868 CXXDtorType Type;
1869
1870 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1871 CXXDtorType Type)
1872 : Dtor(D), Addr(Addr), Type(Type) {}
1873
Craig Topper4f12f102014-03-12 06:41:41 +00001874 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001875 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001876 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001877 }
1878 };
1879}
1880
Alexis Hunt61bc1732011-05-01 07:04:31 +00001881void
1882CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1883 const FunctionArgList &Args) {
1884 assert(Ctor->isDelegatingConstructor());
1885
1886 llvm::Value *ThisPtr = LoadCXXThis();
1887
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001888 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00001889 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00001890 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001891 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001892 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001893 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001894 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001895
1896 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001897
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001898 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001899 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001900 CXXDtorType Type =
1901 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1902
1903 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1904 ClassDecl->getDestructor(),
1905 ThisPtr, Type);
1906 }
1907}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001908
Anders Carlsson27da15b2010-01-01 20:29:01 +00001909void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1910 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001911 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001912 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001913 llvm::Value *This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001914 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1915 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001916}
1917
John McCall53cad2e2010-07-21 01:41:18 +00001918namespace {
John McCallcda666c2010-07-21 07:22:38 +00001919 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001920 const CXXDestructorDecl *Dtor;
1921 llvm::Value *Addr;
1922
1923 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1924 : Dtor(D), Addr(Addr) {}
1925
Craig Topper4f12f102014-03-12 06:41:41 +00001926 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00001927 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001928 /*ForVirtualBase=*/false,
1929 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00001930 }
1931 };
1932}
1933
John McCall8680f872010-07-21 06:29:51 +00001934void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1935 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001936 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001937}
1938
John McCallbd309292010-07-06 01:34:17 +00001939void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1940 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1941 if (!ClassDecl) return;
1942 if (ClassDecl->hasTrivialDestructor()) return;
1943
1944 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001945 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001946 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001947}
1948
Anders Carlssone87fae92010-03-28 19:40:00 +00001949void
1950CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001951 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001952 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001953 const CXXRecordDecl *VTableClass) {
David Majnemer129f4172015-02-02 10:22:20 +00001954 const CXXRecordDecl *RD = Base.getBase();
1955
1956 // Don't initialize the vtable pointer if the class is marked with the
1957 // 'novtable' attribute.
1958 if ((RD == VTableClass || RD == NearestVBase) &&
David Majnemer8ab003a2015-02-02 19:30:52 +00001959 VTableClass->hasAttr<MSNoVTableAttr>())
David Majnemer129f4172015-02-02 10:22:20 +00001960 return;
1961
Anders Carlssone87fae92010-03-28 19:40:00 +00001962 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001963 bool NeedsVirtualOffset;
1964 llvm::Value *VTableAddressPoint =
1965 CGM.getCXXABI().getVTableAddressPointInStructor(
1966 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1967 if (!VTableAddressPoint)
1968 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00001969
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001970 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00001971 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001972 CharUnits NonVirtualOffset = CharUnits::Zero();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001973
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001974 if (NeedsVirtualOffset) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00001975 // We need to use the virtual base offset offset because the virtual base
1976 // might have a different offset in the most derived class.
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001977 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1978 LoadCXXThis(),
1979 VTableClass,
1980 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001981 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001982 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001983 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001984 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001985 }
Anders Carlssonc58fb552010-05-03 00:29:58 +00001986
1987 // Apply the offsets.
1988 llvm::Value *VTableField = LoadCXXThis();
1989
Ken Dyckcfc332c2011-03-23 00:45:26 +00001990 if (!NonVirtualOffset.isZero() || VirtualOffset)
Anders Carlssonc58fb552010-05-03 00:29:58 +00001991 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
1992 NonVirtualOffset,
1993 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001994
Reid Kleckner8d585132014-12-03 21:00:21 +00001995 // Finally, store the address point. Use the same LLVM types as the field to
1996 // support optimization.
1997 llvm::Type *VTablePtrTy =
1998 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
1999 ->getPointerTo()
2000 ->getPointerTo();
2001 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2002 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002003 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2004 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00002005}
2006
Anders Carlssond5895932010-03-28 21:07:49 +00002007void
2008CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00002009 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00002010 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00002011 bool BaseIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00002012 const CXXRecordDecl *VTableClass,
2013 VisitedVirtualBasesSetTy& VBases) {
2014 // If this base is a non-virtual primary base the address point has already
2015 // been set.
2016 if (!BaseIsNonVirtualPrimaryBase) {
2017 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002018 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002019 VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00002020 }
2021
2022 const CXXRecordDecl *RD = Base.getBase();
2023
2024 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002025 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002026 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002027 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002028
2029 // Ignore classes without a vtable.
2030 if (!BaseDecl->isDynamicClass())
2031 continue;
2032
Ken Dyck3fb4c892011-03-23 01:04:18 +00002033 CharUnits BaseOffset;
2034 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002035 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002036
Aaron Ballman574705e2014-03-13 15:41:46 +00002037 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002038 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002039 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002040 continue;
2041
2042 const ASTRecordLayout &Layout =
2043 getContext().getASTRecordLayout(VTableClass);
2044
Ken Dyck3fb4c892011-03-23 01:04:18 +00002045 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2046 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002047 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002048 } else {
2049 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2050
Ken Dyck16ffcac2011-03-24 01:21:01 +00002051 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002052 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002053 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002054 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002055 }
2056
Ken Dyck16ffcac2011-03-24 01:21:01 +00002057 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Aaron Ballman574705e2014-03-13 15:41:46 +00002058 I.isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002059 BaseOffsetFromNearestVBase,
Anders Carlsson948d3f42010-03-29 01:16:41 +00002060 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002061 VTableClass, VBases);
Anders Carlssond5895932010-03-28 21:07:49 +00002062 }
2063}
2064
2065void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2066 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002067 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002068 return;
2069
Anders Carlssond5895932010-03-28 21:07:49 +00002070 // Initialize the vtable pointers for this class and all of its bases.
2071 VisitedVirtualBasesSetTy VBases;
Ken Dyck16ffcac2011-03-24 01:21:01 +00002072 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
Craig Topper8a13c412014-05-21 05:09:00 +00002073 /*NearestVBase=*/nullptr,
Ken Dyck3fb4c892011-03-23 01:04:18 +00002074 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002075 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002076
2077 if (RD->getNumVBases())
2078 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002079}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002080
2081llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00002082 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00002083 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002084 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2085 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2086 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002087}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002088
Peter Collingbourned2926c92015-03-14 02:42:25 +00002089// If a class has a single non-virtual base and does not introduce or override
2090// virtual member functions or fields, it will have the same layout as its base.
2091// This function returns the least derived such class.
2092//
2093// Casting an instance of a base class to such a derived class is technically
2094// undefined behavior, but it is a relatively common hack for introducing member
2095// functions on class instances with specific properties (e.g. llvm::Operator)
2096// that works under most compilers and should not have security implications, so
2097// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2098static const CXXRecordDecl *
2099LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2100 if (!RD->field_empty())
2101 return RD;
2102
2103 if (RD->getNumVBases() != 0)
2104 return RD;
2105
2106 if (RD->getNumBases() != 1)
2107 return RD;
2108
2109 for (const CXXMethodDecl *MD : RD->methods()) {
2110 if (MD->isVirtual()) {
2111 // Virtual member functions are only ok if they are implicit destructors
2112 // because the implicit destructor will have the same semantics as the
2113 // base class's destructor if no fields are added.
2114 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2115 continue;
2116 return RD;
2117 }
2118 }
2119
2120 return LeastDerivedClassWithSameLayout(
2121 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2122}
2123
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002124void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
2125 llvm::Value *VTable) {
2126 const CXXRecordDecl *ClassDecl = MD->getParent();
2127 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2128 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2129
2130 EmitVTablePtrCheck(ClassDecl, VTable);
2131}
2132
Peter Collingbourned2926c92015-03-14 02:42:25 +00002133void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2134 llvm::Value *Derived,
2135 bool MayBeNull) {
2136 if (!getLangOpts().CPlusPlus)
2137 return;
2138
2139 auto *ClassTy = T->getAs<RecordType>();
2140 if (!ClassTy)
2141 return;
2142
2143 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2144
2145 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2146 return;
2147
2148 SmallString<64> MangledName;
2149 llvm::raw_svector_ostream Out(MangledName);
2150 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(T.getUnqualifiedType(),
2151 Out);
2152
2153 // Blacklist based on the mangled type.
2154 if (CGM.getContext().getSanitizerBlacklist().isBlacklistedType(Out.str()))
2155 return;
2156
2157 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2158 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2159
2160 llvm::BasicBlock *ContBlock = 0;
2161
2162 if (MayBeNull) {
2163 llvm::Value *DerivedNotNull =
2164 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2165
2166 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2167 ContBlock = createBasicBlock("cast.cont");
2168
2169 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2170
2171 EmitBlock(CheckBlock);
2172 }
2173
2174 llvm::Value *VTable = GetVTablePtr(Derived, Int8PtrTy);
2175 EmitVTablePtrCheck(ClassDecl, VTable);
2176
2177 if (MayBeNull) {
2178 Builder.CreateBr(ContBlock);
2179 EmitBlock(ContBlock);
2180 }
2181}
2182
2183void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
2184 llvm::Value *VTable) {
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002185 // FIXME: Add blacklisting scheme.
2186 if (RD->isInStdNamespace())
2187 return;
2188
2189 std::string OutName;
2190 llvm::raw_string_ostream Out(OutName);
2191 CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
2192
2193 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
2194 getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
2195
2196 llvm::Value *BitSetTest = Builder.CreateCall2(
2197 CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2198 Builder.CreateBitCast(VTable, CGM.Int8PtrTy), BitSetName);
2199
2200 llvm::BasicBlock *ContBlock = createBasicBlock("vtable.check.cont");
2201 llvm::BasicBlock *TrapBlock = createBasicBlock("vtable.check.trap");
2202
2203 Builder.CreateCondBr(BitSetTest, ContBlock, TrapBlock);
2204
2205 EmitBlock(TrapBlock);
2206 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::trap));
2207 Builder.CreateUnreachable();
2208
2209 EmitBlock(ContBlock);
2210}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002211
2212// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2213// quite what we want.
2214static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2215 while (true) {
2216 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2217 E = PE->getSubExpr();
2218 continue;
2219 }
2220
2221 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2222 if (CE->getCastKind() == CK_NoOp) {
2223 E = CE->getSubExpr();
2224 continue;
2225 }
2226 }
2227 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2228 if (UO->getOpcode() == UO_Extension) {
2229 E = UO->getSubExpr();
2230 continue;
2231 }
2232 }
2233 return E;
2234 }
2235}
2236
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002237bool
2238CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2239 const CXXMethodDecl *MD) {
2240 // When building with -fapple-kext, all calls must go through the vtable since
2241 // the kernel linker can do runtime patching of vtables.
2242 if (getLangOpts().AppleKext)
2243 return false;
2244
Anders Carlssonc36783e2011-05-08 20:32:23 +00002245 // If the most derived class is marked final, we know that no subclass can
2246 // override this member function and so we can devirtualize it. For example:
2247 //
2248 // struct A { virtual void f(); }
2249 // struct B final : A { };
2250 //
2251 // void f(B *b) {
2252 // b->f();
2253 // }
2254 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002255 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002256 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2257 return true;
2258
2259 // If the member function is marked 'final', we know that it can't be
2260 // overridden and can therefore devirtualize it.
2261 if (MD->hasAttr<FinalAttr>())
2262 return true;
2263
2264 // Similarly, if the class itself is marked 'final' it can't be overridden
2265 // and we can therefore devirtualize the member function call.
2266 if (MD->getParent()->hasAttr<FinalAttr>())
2267 return true;
2268
2269 Base = skipNoOpCastsAndParens(Base);
2270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2271 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2272 // This is a record decl. We know the type and can devirtualize it.
2273 return VD->getType()->isRecordType();
2274 }
2275
2276 return false;
2277 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002278
2279 // We can devirtualize calls on an object accessed by a class member access
2280 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2281 // a derived class object constructed in the same location.
2282 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2283 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2284 return VD->getType()->isRecordType();
2285
Anders Carlssonc36783e2011-05-08 20:32:23 +00002286 // We can always devirtualize calls on temporary object expressions.
2287 if (isa<CXXConstructExpr>(Base))
2288 return true;
2289
2290 // And calls on bound temporaries.
2291 if (isa<CXXBindTemporaryExpr>(Base))
2292 return true;
2293
2294 // Check if this is a call expr that returns a record type.
2295 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
David Majnemerced8bdf2015-02-25 17:36:15 +00002296 return CE->getCallReturnType(getContext())->isRecordType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002297
2298 // We can't devirtualize the call.
2299 return false;
2300}
2301
Faisal Vali571df122013-09-29 08:45:24 +00002302void CodeGenFunction::EmitForwardingCallToLambda(
2303 const CXXMethodDecl *callOperator,
2304 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002305 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002306 const CGFunctionInfo &calleeFnInfo =
2307 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2308 llvm::Value *callee =
2309 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2310 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002311
John McCall8dda7b22012-07-07 06:41:13 +00002312 // Prepare the return slot.
2313 const FunctionProtoType *FPT =
2314 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002315 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002316 ReturnValueSlot returnSlot;
2317 if (!resultType->isVoidType() &&
2318 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002319 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002320 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2321
2322 // We don't need to separately arrange the call arguments because
2323 // the call can't be variadic anyway --- it's impossible to forward
2324 // variadic arguments.
Eli Friedman5b446882012-02-16 03:47:28 +00002325
2326 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002327 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2328 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002329
John McCall8dda7b22012-07-07 06:41:13 +00002330 // If necessary, copy the returned value into the slot.
2331 if (!resultType->isVoidType() && returnSlot.isNull())
2332 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002333 else
2334 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002335}
2336
Eli Friedman2495ab02012-02-25 02:48:22 +00002337void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2338 const BlockDecl *BD = BlockInfo->getBlockDecl();
2339 const VarDecl *variable = BD->capture_begin()->getVariable();
2340 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2341
2342 // Start building arguments for forwarding call
2343 CallArgList CallArgs;
2344
2345 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2346 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2347 CallArgs.add(RValue::get(ThisPtr), ThisType);
2348
2349 // Add the rest of the parameters.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002350 for (auto param : BD->params())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002351 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002352
Faisal Vali571df122013-09-29 08:45:24 +00002353 assert(!Lambda->isGenericLambda() &&
2354 "generic lambda interconversion to block not implemented");
2355 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002356}
2357
2358void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002359 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002360 // FIXME: Making this work correctly is nasty because it requires either
2361 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002362 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002363 return;
2364 }
2365
Richard Smithb47c36f2013-11-05 09:12:18 +00002366 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002367}
2368
2369void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2370 const CXXRecordDecl *Lambda = MD->getParent();
2371
2372 // Start building arguments for forwarding call
2373 CallArgList CallArgs;
2374
2375 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2376 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2377 CallArgs.add(RValue::get(ThisPtr), ThisType);
2378
2379 // Add the rest of the parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002380 for (auto Param : MD->params())
2381 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2382
Faisal Vali571df122013-09-29 08:45:24 +00002383 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2384 // For a generic lambda, find the corresponding call operator specialization
2385 // to which the call to the static-invoker shall be forwarded.
2386 if (Lambda->isGenericLambda()) {
2387 assert(MD->isFunctionTemplateSpecialization());
2388 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2389 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002390 void *InsertPos = nullptr;
Faisal Vali571df122013-09-29 08:45:24 +00002391 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002392 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002393 assert(CorrespondingCallOpSpecialization);
2394 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2395 }
2396 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002397}
2398
Douglas Gregor355efbb2012-02-17 03:02:34 +00002399void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2400 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002401 // FIXME: Making this work correctly is nasty because it requires either
2402 // cloning the body of the call operator or making the call operator forward.
2403 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002404 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002405 }
2406
Douglas Gregor355efbb2012-02-17 03:02:34 +00002407 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002408}