blob: 62df9820a6c32dacad2bd86b0c3eea4a5fe6670d [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
David Majnemerc1709d32015-06-23 07:31:11 +000032CharUnits CodeGenModule::computeNonVirtualBaseClassOffset(
33 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start,
34 CastExpr::path_const_iterator End) {
Ken Dycka1a4ae32011-03-22 00:53:26 +000035 CharUnits Offset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +000036
David Majnemerc1709d32015-06-23 07:31:11 +000037 const ASTContext &Context = getContext();
Anders Carlssond829a022010-04-24 21:06:20 +000038 const CXXRecordDecl *RD = DerivedClass;
Justin Bogner1cd11f12015-05-20 15:53:59 +000039
John McCallcf142162010-08-07 06:22:56 +000040 for (CastExpr::path_const_iterator I = Start; I != End; ++I) {
Anders Carlssond829a022010-04-24 21:06:20 +000041 const CXXBaseSpecifier *Base = *I;
42 assert(!Base->isVirtual() && "Should not see virtual bases here!");
43
44 // Get the layout.
45 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +000046
47 const CXXRecordDecl *BaseDecl =
Anders Carlssond829a022010-04-24 21:06:20 +000048 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +000049
Anders Carlssond829a022010-04-24 21:06:20 +000050 // Add the offset.
Ken Dycka1a4ae32011-03-22 00:53:26 +000051 Offset += Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +000052
Anders Carlssond829a022010-04-24 21:06:20 +000053 RD = BaseDecl;
54 }
Justin Bogner1cd11f12015-05-20 15:53:59 +000055
Ken Dycka1a4ae32011-03-22 00:53:26 +000056 return Offset;
Anders Carlssond829a022010-04-24 21:06:20 +000057}
Anders Carlsson9a57c5a2009-09-12 04:27:24 +000058
Anders Carlsson9150a2a2009-09-29 03:13:20 +000059llvm::Constant *
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000060CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl,
John McCallcf142162010-08-07 06:22:56 +000061 CastExpr::path_const_iterator PathBegin,
62 CastExpr::path_const_iterator PathEnd) {
63 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000064
Justin Bogner1cd11f12015-05-20 15:53:59 +000065 CharUnits Offset =
David Majnemerc1709d32015-06-23 07:31:11 +000066 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd);
Ken Dycka1a4ae32011-03-22 00:53:26 +000067 if (Offset.isZero())
Craig Topper8a13c412014-05-21 05:09:00 +000068 return nullptr;
69
Justin Bogner1cd11f12015-05-20 15:53:59 +000070 llvm::Type *PtrDiffTy =
Anders Carlsson8a64c1c2010-04-24 21:23:59 +000071 Types.ConvertType(getContext().getPointerDiffType());
Justin Bogner1cd11f12015-05-20 15:53:59 +000072
Ken Dycka1a4ae32011-03-22 00:53:26 +000073 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity());
Anders Carlsson9150a2a2009-09-29 03:13:20 +000074}
75
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000076/// Gets the address of a direct base class within a complete object.
John McCall6ce74722010-02-16 04:15:37 +000077/// This should only be used for (1) non-virtual bases or (2) virtual bases
78/// when the type is known to be complete (e.g. in complete destructors).
79///
80/// The object pointed to by 'This' is assumed to be non-null.
81llvm::Value *
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000082CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This,
83 const CXXRecordDecl *Derived,
84 const CXXRecordDecl *Base,
85 bool BaseIsVirtual) {
John McCall6ce74722010-02-16 04:15:37 +000086 // 'this' must be a pointer (in some address space) to Derived.
87 assert(This->getType()->isPointerTy() &&
88 cast<llvm::PointerType>(This->getType())->getElementType()
89 == ConvertType(Derived));
90
91 // Compute the offset of the virtual base.
Ken Dyck6aa767c2011-03-22 01:21:15 +000092 CharUnits Offset;
John McCall6ce74722010-02-16 04:15:37 +000093 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived);
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +000094 if (BaseIsVirtual)
Ken Dyck6aa767c2011-03-22 01:21:15 +000095 Offset = Layout.getVBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000096 else
Ken Dyck6aa767c2011-03-22 01:21:15 +000097 Offset = Layout.getBaseClassOffset(Base);
John McCall6ce74722010-02-16 04:15:37 +000098
99 // Shift and cast down to the base type.
100 // TODO: for complete types, this should be possible with a GEP.
101 llvm::Value *V = This;
Ken Dyck6aa767c2011-03-22 01:21:15 +0000102 if (Offset.isPositive()) {
John McCall6ce74722010-02-16 04:15:37 +0000103 V = Builder.CreateBitCast(V, Int8PtrTy);
Ken Dyck6aa767c2011-03-22 01:21:15 +0000104 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity());
John McCall6ce74722010-02-16 04:15:37 +0000105 }
106 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo());
107
108 return V;
Anders Carlssone87fae92010-03-28 19:40:00 +0000109}
John McCall6ce74722010-02-16 04:15:37 +0000110
Anders Carlsson53cebd12010-04-20 16:03:35 +0000111static llvm::Value *
John McCall13a39c62012-08-01 05:04:58 +0000112ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ptr,
113 CharUnits nonVirtualOffset,
114 llvm::Value *virtualOffset) {
115 // Assert that we have something to do.
Craig Topper8a13c412014-05-21 05:09:00 +0000116 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr);
John McCall13a39c62012-08-01 05:04:58 +0000117
118 // Compute the offset from the static and dynamic components.
119 llvm::Value *baseOffset;
120 if (!nonVirtualOffset.isZero()) {
121 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy,
122 nonVirtualOffset.getQuantity());
123 if (virtualOffset) {
124 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset);
125 }
126 } else {
127 baseOffset = virtualOffset;
128 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000129
Anders Carlsson53cebd12010-04-20 16:03:35 +0000130 // Apply the base offset.
John McCall13a39c62012-08-01 05:04:58 +0000131 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy);
132 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr");
133 return ptr;
Anders Carlsson53cebd12010-04-20 16:03:35 +0000134}
135
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000136llvm::Value *CodeGenFunction::GetAddressOfBaseClass(
137 llvm::Value *Value, const CXXRecordDecl *Derived,
138 CastExpr::path_const_iterator PathBegin,
139 CastExpr::path_const_iterator PathEnd, bool NullCheckValue,
140 SourceLocation Loc) {
John McCallcf142162010-08-07 06:22:56 +0000141 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlssond829a022010-04-24 21:06:20 +0000142
John McCallcf142162010-08-07 06:22:56 +0000143 CastExpr::path_const_iterator Start = PathBegin;
Craig Topper8a13c412014-05-21 05:09:00 +0000144 const CXXRecordDecl *VBase = nullptr;
145
John McCall13a39c62012-08-01 05:04:58 +0000146 // Sema has done some convenient canonicalization here: if the
147 // access path involved any virtual steps, the conversion path will
148 // *start* with a step down to the correct virtual base subobject,
149 // and hence will not require any further steps.
Anders Carlssond829a022010-04-24 21:06:20 +0000150 if ((*Start)->isVirtual()) {
Justin Bogner1cd11f12015-05-20 15:53:59 +0000151 VBase =
Anders Carlssond829a022010-04-24 21:06:20 +0000152 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl());
153 ++Start;
154 }
John McCall13a39c62012-08-01 05:04:58 +0000155
156 // Compute the static offset of the ultimate destination within its
157 // allocating subobject (the virtual base, if there is one, or else
158 // the "complete" object that we see).
David Majnemerc1709d32015-06-23 07:31:11 +0000159 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset(
160 VBase ? VBase : Derived, Start, PathEnd);
Anders Carlssond829a022010-04-24 21:06:20 +0000161
John McCall13a39c62012-08-01 05:04:58 +0000162 // If there's a virtual step, we can sometimes "devirtualize" it.
163 // For now, that's limited to when the derived type is final.
164 // TODO: "devirtualize" this for accesses to known-complete objects.
165 if (VBase && Derived->hasAttr<FinalAttr>()) {
166 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived);
167 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase);
168 NonVirtualOffset += vBaseOffset;
Craig Topper8a13c412014-05-21 05:09:00 +0000169 VBase = nullptr; // we no longer have a virtual step
John McCall13a39c62012-08-01 05:04:58 +0000170 }
171
Anders Carlssond829a022010-04-24 21:06:20 +0000172 // Get the base pointer type.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000173 llvm::Type *BasePtrTy =
John McCallcf142162010-08-07 06:22:56 +0000174 ConvertType((PathEnd[-1])->getType())->getPointerTo();
John McCall13a39c62012-08-01 05:04:58 +0000175
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000176 QualType DerivedTy = getContext().getRecordType(Derived);
177 CharUnits DerivedAlign = getContext().getTypeAlignInChars(DerivedTy);
178
John McCall13a39c62012-08-01 05:04:58 +0000179 // If the static offset is zero and we don't have a virtual step,
180 // just do a bitcast; null checks are unnecessary.
Ken Dycka1a4ae32011-03-22 00:53:26 +0000181 if (NonVirtualOffset.isZero() && !VBase) {
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000182 if (sanitizePerformTypeCheck()) {
183 EmitTypeCheck(TCK_Upcast, Loc, Value, DerivedTy, DerivedAlign,
184 !NullCheckValue);
185 }
Anders Carlssond829a022010-04-24 21:06:20 +0000186 return Builder.CreateBitCast(Value, BasePtrTy);
Craig Topper8a13c412014-05-21 05:09:00 +0000187 }
John McCall13a39c62012-08-01 05:04:58 +0000188
Craig Topper8a13c412014-05-21 05:09:00 +0000189 llvm::BasicBlock *origBB = nullptr;
190 llvm::BasicBlock *endBB = nullptr;
191
John McCall13a39c62012-08-01 05:04:58 +0000192 // Skip over the offset (and the vtable load) if we're supposed to
193 // null-check the pointer.
Anders Carlssond829a022010-04-24 21:06:20 +0000194 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000195 origBB = Builder.GetInsertBlock();
196 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull");
197 endBB = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000198
John McCall13a39c62012-08-01 05:04:58 +0000199 llvm::Value *isNull = Builder.CreateIsNull(Value);
200 Builder.CreateCondBr(isNull, endBB, notNullBB);
201 EmitBlock(notNullBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000202 }
203
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +0000204 if (sanitizePerformTypeCheck()) {
205 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, Value,
206 DerivedTy, DerivedAlign, true);
207 }
208
John McCall13a39c62012-08-01 05:04:58 +0000209 // Compute the virtual offset.
Craig Topper8a13c412014-05-21 05:09:00 +0000210 llvm::Value *VirtualOffset = nullptr;
Anders Carlssona376b532011-01-29 03:18:56 +0000211 if (VBase) {
Reid Klecknerd8cbeec2013-05-29 18:02:47 +0000212 VirtualOffset =
213 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase);
Anders Carlssona376b532011-01-29 03:18:56 +0000214 }
Anders Carlssond829a022010-04-24 21:06:20 +0000215
John McCall13a39c62012-08-01 05:04:58 +0000216 // Apply both offsets.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000217 Value = ApplyNonVirtualAndVirtualOffset(*this, Value,
Ken Dyckcfc332c2011-03-23 00:45:26 +0000218 NonVirtualOffset,
Anders Carlssond829a022010-04-24 21:06:20 +0000219 VirtualOffset);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000220
John McCall13a39c62012-08-01 05:04:58 +0000221 // Cast to the destination type.
Anders Carlssond829a022010-04-24 21:06:20 +0000222 Value = Builder.CreateBitCast(Value, BasePtrTy);
John McCall13a39c62012-08-01 05:04:58 +0000223
224 // Build a phi if we needed a null check.
Anders Carlssond829a022010-04-24 21:06:20 +0000225 if (NullCheckValue) {
John McCall13a39c62012-08-01 05:04:58 +0000226 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock();
227 Builder.CreateBr(endBB);
228 EmitBlock(endBB);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000229
John McCall13a39c62012-08-01 05:04:58 +0000230 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result");
231 PHI->addIncoming(Value, notNullBB);
232 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB);
Anders Carlssond829a022010-04-24 21:06:20 +0000233 Value = PHI;
234 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000235
Anders Carlssond829a022010-04-24 21:06:20 +0000236 return Value;
237}
238
239llvm::Value *
Anders Carlsson8c793172009-11-23 17:57:54 +0000240CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value,
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000241 const CXXRecordDecl *Derived,
John McCallcf142162010-08-07 06:22:56 +0000242 CastExpr::path_const_iterator PathBegin,
243 CastExpr::path_const_iterator PathEnd,
Anders Carlsson8c793172009-11-23 17:57:54 +0000244 bool NullCheckValue) {
John McCallcf142162010-08-07 06:22:56 +0000245 assert(PathBegin != PathEnd && "Base path should not be empty!");
Anders Carlsson8a64c1c2010-04-24 21:23:59 +0000246
Anders Carlsson8c793172009-11-23 17:57:54 +0000247 QualType DerivedTy =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000248 getContext().getCanonicalType(getContext().getTagDeclType(Derived));
Chris Lattner2192fe52011-07-18 04:24:23 +0000249 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo();
Richard Smith2c5868c2013-02-13 21:18:23 +0000250
Anders Carlsson600f7372010-01-31 01:43:37 +0000251 llvm::Value *NonVirtualOffset =
John McCallcf142162010-08-07 06:22:56 +0000252 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000253
Anders Carlsson600f7372010-01-31 01:43:37 +0000254 if (!NonVirtualOffset) {
255 // No offset, we can just cast back.
256 return Builder.CreateBitCast(Value, DerivedPtrTy);
257 }
Craig Topper8a13c412014-05-21 05:09:00 +0000258
259 llvm::BasicBlock *CastNull = nullptr;
260 llvm::BasicBlock *CastNotNull = nullptr;
261 llvm::BasicBlock *CastEnd = nullptr;
262
Anders Carlsson8c793172009-11-23 17:57:54 +0000263 if (NullCheckValue) {
264 CastNull = createBasicBlock("cast.null");
265 CastNotNull = createBasicBlock("cast.notnull");
266 CastEnd = createBasicBlock("cast.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000267
Anders Carlsson98981b12011-04-11 00:30:07 +0000268 llvm::Value *IsNull = Builder.CreateIsNull(Value);
Anders Carlsson8c793172009-11-23 17:57:54 +0000269 Builder.CreateCondBr(IsNull, CastNull, CastNotNull);
270 EmitBlock(CastNotNull);
271 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000272
Anders Carlsson600f7372010-01-31 01:43:37 +0000273 // Apply the offset.
Eli Friedman87549262012-02-28 22:07:56 +0000274 Value = Builder.CreateBitCast(Value, Int8PtrTy);
275 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset),
276 "sub.ptr");
Anders Carlsson600f7372010-01-31 01:43:37 +0000277
278 // Just cast.
279 Value = Builder.CreateBitCast(Value, DerivedPtrTy);
Anders Carlsson8c793172009-11-23 17:57:54 +0000280
281 if (NullCheckValue) {
282 Builder.CreateBr(CastEnd);
283 EmitBlock(CastNull);
284 Builder.CreateBr(CastEnd);
285 EmitBlock(CastEnd);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000286
Jay Foad20c0f022011-03-30 11:28:58 +0000287 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2);
Anders Carlsson8c793172009-11-23 17:57:54 +0000288 PHI->addIncoming(Value, CastNotNull);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000289 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()),
Anders Carlsson8c793172009-11-23 17:57:54 +0000290 CastNull);
291 Value = PHI;
292 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000293
Anders Carlsson8c793172009-11-23 17:57:54 +0000294 return Value;
Anders Carlsson9a57c5a2009-09-12 04:27:24 +0000295}
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000296
297llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
298 bool ForVirtualBase,
299 bool Delegating) {
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000300 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000301 // This constructor/destructor does not need a VTT parameter.
Craig Topper8a13c412014-05-21 05:09:00 +0000302 return nullptr;
Anders Carlssone36a6b32010-01-02 01:01:18 +0000303 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000304
John McCalldec348f72013-05-03 07:33:41 +0000305 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
Anders Carlssone36a6b32010-01-02 01:01:18 +0000306 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
John McCall5c60a6f2010-02-18 19:59:28 +0000307
Anders Carlssone36a6b32010-01-02 01:01:18 +0000308 llvm::Value *VTT;
309
John McCall5c60a6f2010-02-18 19:59:28 +0000310 uint64_t SubVTTIndex;
311
Douglas Gregor61535002013-01-31 05:50:40 +0000312 if (Delegating) {
313 // If this is a delegating constructor call, just load the VTT.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000314 return LoadCXXVTT();
Douglas Gregor61535002013-01-31 05:50:40 +0000315 } else if (RD == Base) {
316 // If the record matches the base, this is the complete ctor/dtor
317 // variant calling the base variant in a class with virtual bases.
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000318 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) &&
John McCall5c60a6f2010-02-18 19:59:28 +0000319 "doing no-op VTT offset in base dtor/ctor?");
Anders Carlsson4d205ba2010-05-02 23:33:10 +0000320 assert(!ForVirtualBase && "Can't have same class as virtual base!");
John McCall5c60a6f2010-02-18 19:59:28 +0000321 SubVTTIndex = 0;
322 } else {
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000323 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000324 CharUnits BaseOffset = ForVirtualBase ?
325 Layout.getVBaseClassOffset(Base) :
Ken Dyck16ffcac2011-03-24 01:21:01 +0000326 Layout.getBaseClassOffset(Base);
Anders Carlsson859b3062010-05-02 23:53:25 +0000327
Justin Bogner1cd11f12015-05-20 15:53:59 +0000328 SubVTTIndex =
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000329 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset));
John McCall5c60a6f2010-02-18 19:59:28 +0000330 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!");
331 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000332
Peter Collingbourne66f82e62013-06-28 20:45:28 +0000333 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
Anders Carlssone36a6b32010-01-02 01:01:18 +0000334 // A VTT parameter was passed to the constructor, use it.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000335 VTT = LoadCXXVTT();
336 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000337 } else {
338 // We're the complete constructor, so get the VTT by name.
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000339 VTT = CGM.getVTables().GetAddrOfVTT(RD);
340 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex);
Anders Carlssone36a6b32010-01-02 01:01:18 +0000341 }
342
343 return VTT;
344}
345
John McCall1d987562010-07-21 01:23:41 +0000346namespace {
John McCallf99a6312010-07-21 05:30:47 +0000347 /// Call the destructor for a direct base class.
John McCallcda666c2010-07-21 07:22:38 +0000348 struct CallBaseDtor : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +0000349 const CXXRecordDecl *BaseClass;
350 bool BaseIsVirtual;
351 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual)
352 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {}
John McCall1d987562010-07-21 01:23:41 +0000353
Craig Topper4f12f102014-03-12 06:41:41 +0000354 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +0000355 const CXXRecordDecl *DerivedClass =
356 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent();
357
358 const CXXDestructorDecl *D = BaseClass->getDestructor();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000359 llvm::Value *Addr =
John McCallf99a6312010-07-21 05:30:47 +0000360 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(),
361 DerivedClass, BaseClass,
362 BaseIsVirtual);
Douglas Gregor61535002013-01-31 05:50:40 +0000363 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual,
364 /*Delegating=*/false, Addr);
John McCall1d987562010-07-21 01:23:41 +0000365 }
366 };
John McCall769250e2010-09-17 02:31:44 +0000367
368 /// A visitor which checks whether an initializer uses 'this' in a
369 /// way which requires the vtable to be properly set.
Scott Douglass503fc392015-06-10 13:53:15 +0000370 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> {
371 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super;
John McCall769250e2010-09-17 02:31:44 +0000372
373 bool UsesThis;
374
Scott Douglass503fc392015-06-10 13:53:15 +0000375 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {}
John McCall769250e2010-09-17 02:31:44 +0000376
377 // Black-list all explicit and implicit references to 'this'.
378 //
379 // Do we need to worry about external references to 'this' derived
380 // from arbitrary code? If so, then anything which runs arbitrary
381 // external code might potentially access the vtable.
Scott Douglass503fc392015-06-10 13:53:15 +0000382 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; }
John McCall769250e2010-09-17 02:31:44 +0000383 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000384}
John McCall769250e2010-09-17 02:31:44 +0000385
386static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) {
387 DynamicThisUseChecker Checker(C);
Scott Douglass503fc392015-06-10 13:53:15 +0000388 Checker.Visit(Init);
John McCall769250e2010-09-17 02:31:44 +0000389 return Checker.UsesThis;
John McCall1d987562010-07-21 01:23:41 +0000390}
391
Justin Bogner1cd11f12015-05-20 15:53:59 +0000392static void EmitBaseInitializer(CodeGenFunction &CGF,
Anders Carlssonfb404882009-12-24 22:46:43 +0000393 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000394 CXXCtorInitializer *BaseInit,
Anders Carlssonfb404882009-12-24 22:46:43 +0000395 CXXCtorType CtorType) {
396 assert(BaseInit->isBaseInitializer() &&
397 "Must have base initializer!");
398
399 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Justin Bogner1cd11f12015-05-20 15:53:59 +0000400
Anders Carlssonfb404882009-12-24 22:46:43 +0000401 const Type *BaseType = BaseInit->getBaseClass();
402 CXXRecordDecl *BaseClassDecl =
403 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl());
404
Anders Carlsson1c0f8bb2010-04-12 00:51:03 +0000405 bool isBaseVirtual = BaseInit->isBaseVirtual();
Anders Carlssonfb404882009-12-24 22:46:43 +0000406
407 // The base constructor doesn't construct virtual bases.
408 if (CtorType == Ctor_Base && isBaseVirtual)
409 return;
410
John McCall769250e2010-09-17 02:31:44 +0000411 // If the initializer for the base (other than the constructor
412 // itself) accesses 'this' in any way, we need to initialize the
413 // vtables.
414 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit()))
415 CGF.InitializeVTablePointers(ClassDecl);
416
John McCall6ce74722010-02-16 04:15:37 +0000417 // We can pretend to be a complete class because it only matters for
418 // virtual bases, and we only do virtual bases for complete ctors.
Justin Bogner1cd11f12015-05-20 15:53:59 +0000419 llvm::Value *V =
Anders Carlssonc4ba0cd2010-04-24 23:01:49 +0000420 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl,
John McCallf99a6312010-07-21 05:30:47 +0000421 BaseClassDecl,
422 isBaseVirtual);
Eli Friedman38cd36d2011-12-03 02:13:40 +0000423 CharUnits Alignment = CGF.getContext().getTypeAlignInChars(BaseType);
John McCall8d6fc952011-08-25 20:40:09 +0000424 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000425 AggValueSlot::forAddr(V, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +0000426 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +0000427 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000428 AggValueSlot::IsNotAliased);
John McCall7a626f62010-09-15 10:14:12 +0000429
430 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000431
432 if (CGF.CGM.getLangOpts().Exceptions &&
Anders Carlsson08ce5ed2011-02-20 00:20:27 +0000433 !BaseClassDecl->hasTrivialDestructor())
John McCallcda666c2010-07-21 07:22:38 +0000434 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl,
435 isBaseVirtual);
Anders Carlssonfb404882009-12-24 22:46:43 +0000436}
437
Douglas Gregor94f9a482010-05-05 05:51:00 +0000438static void EmitAggMemberInitializer(CodeGenFunction &CGF,
439 LValue LHS,
Eli Friedman6ae63022012-02-14 02:15:49 +0000440 Expr *Init,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000441 llvm::Value *ArrayIndexVar,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000442 QualType T,
Eli Friedman6ae63022012-02-14 02:15:49 +0000443 ArrayRef<VarDecl *> ArrayIndexes,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000444 unsigned Index) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000445 if (Index == ArrayIndexes.size()) {
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000446 LValue LV = LHS;
Eli Friedmanc1d85b92011-12-03 00:54:26 +0000447
Richard Smithcc1b96d2013-06-12 22:31:48 +0000448 if (ArrayIndexVar) {
449 // If we have an array index variable, load it and use it as an offset.
450 // Then, increment the value.
451 llvm::Value *Dest = LHS.getAddress();
452 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar);
453 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress");
454 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1);
455 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc");
456 CGF.Builder.CreateStore(Next, ArrayIndexVar);
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000457
Richard Smithcc1b96d2013-06-12 22:31:48 +0000458 // Update the LValue.
459 LV.setAddress(Dest);
460 CharUnits Align = CGF.getContext().getTypeAlignInChars(T);
461 LV.setAlignment(std::min(Align, LV.getAlignment()));
Douglas Gregor94f9a482010-05-05 05:51:00 +0000462 }
John McCall7a626f62010-09-15 10:14:12 +0000463
Richard Smithcc1b96d2013-06-12 22:31:48 +0000464 switch (CGF.getEvaluationKind(T)) {
465 case TEK_Scalar:
Craig Topper8a13c412014-05-21 05:09:00 +0000466 CGF.EmitScalarInit(Init, /*decl*/ nullptr, LV, false);
Richard Smithcc1b96d2013-06-12 22:31:48 +0000467 break;
468 case TEK_Complex:
469 CGF.EmitComplexExprIntoLValue(Init, LV, /*isInit*/ true);
470 break;
471 case TEK_Aggregate: {
472 AggValueSlot Slot =
473 AggValueSlot::forLValue(LV,
474 AggValueSlot::IsDestructed,
475 AggValueSlot::DoesNotNeedGCBarriers,
476 AggValueSlot::IsNotAliased);
477
478 CGF.EmitAggExpr(Init, Slot);
479 break;
480 }
481 }
Sebastian Redl4e04dd12012-02-19 15:41:54 +0000482
Douglas Gregor94f9a482010-05-05 05:51:00 +0000483 return;
484 }
Richard Smithcc1b96d2013-06-12 22:31:48 +0000485
Douglas Gregor94f9a482010-05-05 05:51:00 +0000486 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T);
487 assert(Array && "Array initialization without the array type?");
488 llvm::Value *IndexVar
Eli Friedman6ae63022012-02-14 02:15:49 +0000489 = CGF.GetAddrOfLocalVar(ArrayIndexes[Index]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000490 assert(IndexVar && "Array index variable not loaded");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000491
Douglas Gregor94f9a482010-05-05 05:51:00 +0000492 // Initialize this index variable to zero.
493 llvm::Value* Zero
494 = llvm::Constant::getNullValue(
495 CGF.ConvertType(CGF.getContext().getSizeType()));
496 CGF.Builder.CreateStore(Zero, IndexVar);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000497
Douglas Gregor94f9a482010-05-05 05:51:00 +0000498 // Start the loop with a block that tests the condition.
499 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond");
500 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000501
Douglas Gregor94f9a482010-05-05 05:51:00 +0000502 CGF.EmitBlock(CondBlock);
503
504 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body");
505 // Generate: if (loop-index < number-of-elements) fall to the loop body,
506 // otherwise, go to the block after the for-loop.
507 uint64_t NumElements = Array->getSize().getZExtValue();
Douglas Gregor94f9a482010-05-05 05:51:00 +0000508 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar);
Chris Lattner44456d22010-05-06 06:35:23 +0000509 llvm::Value *NumElementsPtr =
510 llvm::ConstantInt::get(Counter->getType(), NumElements);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000511 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr,
512 "isless");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000513
Douglas Gregor94f9a482010-05-05 05:51:00 +0000514 // If the condition is true, execute the body.
515 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor);
516
517 CGF.EmitBlock(ForBody);
518 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc");
Richard Smithcc1b96d2013-06-12 22:31:48 +0000519
520 // Inside the loop body recurse to emit the inner loop or, eventually, the
521 // constructor call.
522 EmitAggMemberInitializer(CGF, LHS, Init, ArrayIndexVar,
523 Array->getElementType(), ArrayIndexes, Index + 1);
524
Douglas Gregor94f9a482010-05-05 05:51:00 +0000525 CGF.EmitBlock(ContinueBlock);
526
527 // Emit the increment of the loop counter.
528 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1);
529 Counter = CGF.Builder.CreateLoad(IndexVar);
530 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc");
531 CGF.Builder.CreateStore(NextVal, IndexVar);
532
533 // Finally, branch back up to the condition for the next iteration.
534 CGF.EmitBranch(CondBlock);
535
536 // Emit the fall-through block.
537 CGF.EmitBlock(AfterFor, true);
538}
John McCall1d987562010-07-21 01:23:41 +0000539
Richard Smith419bd092015-04-29 19:26:57 +0000540static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) {
541 auto *CD = dyn_cast<CXXConstructorDecl>(D);
542 if (!(CD && CD->isCopyOrMoveConstructor()) &&
543 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator())
544 return false;
545
546 // We can emit a memcpy for a trivial copy or move constructor/assignment.
547 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding())
548 return true;
549
550 // We *must* emit a memcpy for a defaulted union copy or move op.
551 if (D->getParent()->isUnion() && D->isDefaulted())
552 return true;
553
554 return false;
555}
556
Anders Carlssonfb404882009-12-24 22:46:43 +0000557static void EmitMemberInitializer(CodeGenFunction &CGF,
558 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000559 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000560 const CXXConstructorDecl *Constructor,
561 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000562 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000563 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000564 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000565 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000566
Anders Carlssonfb404882009-12-24 22:46:43 +0000567 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000568 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000569 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000570
571 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000572 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000573 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000574
Francois Pichetd583da02010-12-04 09:14:42 +0000575 if (MemberInit->isIndirectMemberInitializer()) {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000576 // If we are initializing an anonymous union field, drill down to
577 // the field.
578 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
Aaron Ballman29c94602014-03-07 18:36:15 +0000579 for (const auto *I : IndirectField->chain())
Aaron Ballman13916082014-03-07 18:11:58 +0000580 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
Francois Pichetd583da02010-12-04 09:14:42 +0000581 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType();
John McCallc4094932010-05-21 01:18:57 +0000582 } else {
Eli Friedmanf6d21842012-08-08 03:51:37 +0000583 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
Anders Carlssonfb404882009-12-24 22:46:43 +0000584 }
585
Eli Friedman6ae63022012-02-14 02:15:49 +0000586 // Special case: if we are in a copy or move constructor, and we are copying
587 // an array of PODs or classes with trivial copy constructors, ignore the
588 // AST and perform the copy we know is equivalent.
589 // FIXME: This is hacky at best... if we had a bit more explicit information
590 // in the AST, we could generalize it more easily.
591 const ConstantArrayType *Array
592 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000593 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000594 Constructor->isCopyOrMoveConstructor()) {
595 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000596 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000597 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000598 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000599 unsigned SrcArgIndex =
600 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000601 llvm::Value *SrcPtr
602 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000603 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
604 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000605
Eli Friedman6ae63022012-02-14 02:15:49 +0000606 // Copy the aggregate.
607 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000608 LHS.isVolatileQualified());
Eli Friedman6ae63022012-02-14 02:15:49 +0000609 return;
610 }
611 }
612
613 ArrayRef<VarDecl *> ArrayIndexes;
614 if (MemberInit->getNumArrayIndices())
615 ArrayIndexes = MemberInit->getArrayIndexes();
David Blaikie66e41972015-01-14 07:38:27 +0000616 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000617}
618
David Blaikie66e41972015-01-14 07:38:27 +0000619void CodeGenFunction::EmitInitializerForField(
620 FieldDecl *Field, LValue LHS, Expr *Init,
621 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000622 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000623 switch (getEvaluationKind(FieldType)) {
624 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000625 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000626 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000627 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000628 RValue RHS = RValue::get(EmitScalarExpr(Init));
629 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000630 }
John McCall47fb9502013-03-07 21:37:08 +0000631 break;
632 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000633 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000634 break;
635 case TEK_Aggregate: {
Craig Topper8a13c412014-05-21 05:09:00 +0000636 llvm::Value *ArrayIndexVar = nullptr;
Eli Friedman6ae63022012-02-14 02:15:49 +0000637 if (ArrayIndexes.size()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000638 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000639
Douglas Gregor94f9a482010-05-05 05:51:00 +0000640 // The LHS is a pointer to the first object we'll be constructing, as
641 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000642 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
643 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000644 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000645 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000646 BasePtr);
647 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000648
Douglas Gregor94f9a482010-05-05 05:51:00 +0000649 // Create an array index that will be used to walk over all of the
650 // objects we're constructing.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000651 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregor94f9a482010-05-05 05:51:00 +0000652 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000653 Builder.CreateStore(Zero, ArrayIndexVar);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000654
655
Douglas Gregor94f9a482010-05-05 05:51:00 +0000656 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000657 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000658 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000659 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000660
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000661 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000662 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000663 }
John McCall47fb9502013-03-07 21:37:08 +0000664 }
John McCall12cc42a2013-02-01 05:11:40 +0000665
666 // Ensure that we destroy this object if an exception is thrown
667 // later in the constructor.
668 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
669 if (needsEHCleanup(dtorKind))
670 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000671}
672
John McCallf8ff7b92010-02-23 00:48:20 +0000673/// Checks whether the given constructor is a valid subject for the
674/// complete-to-base constructor delegation optimization, i.e.
675/// emitting the complete constructor as a simple call to the base
676/// constructor.
677static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
678
679 // Currently we disable the optimization for classes with virtual
680 // bases because (1) the addresses of parameter variables need to be
681 // consistent across all initializers but (2) the delegate function
682 // call necessarily creates a second copy of the parameter variable.
683 //
684 // The limiting example (purely theoretical AFAIK):
685 // struct A { A(int &c) { c++; } };
686 // struct B : virtual A {
687 // B(int count) : A(count) { printf("%d\n", count); }
688 // };
689 // ...although even this example could in principle be emitted as a
690 // delegation since the address of the parameter doesn't escape.
691 if (Ctor->getParent()->getNumVBases()) {
692 // TODO: white-list trivial vbase initializers. This case wouldn't
693 // be subject to the restrictions below.
694
695 // TODO: white-list cases where:
696 // - there are no non-reference parameters to the constructor
697 // - the initializers don't access any non-reference parameters
698 // - the initializers don't take the address of non-reference
699 // parameters
700 // - etc.
701 // If we ever add any of the above cases, remember that:
702 // - function-try-blocks will always blacklist this optimization
703 // - we need to perform the constructor prologue and cleanup in
704 // EmitConstructorBody.
705
706 return false;
707 }
708
709 // We also disable the optimization for variadic functions because
710 // it's impossible to "re-pass" varargs.
711 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
712 return false;
713
Alexis Hunt61bc1732011-05-01 07:04:31 +0000714 // FIXME: Decide if we can do a delegation of a delegating constructor.
715 if (Ctor->isDelegatingConstructor())
716 return false;
717
John McCallf8ff7b92010-02-23 00:48:20 +0000718 return true;
719}
720
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000721// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
722// to poison the extra field paddings inserted under
723// -fsanitize-address-field-padding=1|2.
724void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
725 ASTContext &Context = getContext();
726 const CXXRecordDecl *ClassDecl =
727 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
728 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
729 if (!ClassDecl->mayInsertExtraPadding()) return;
730
731 struct SizeAndOffset {
732 uint64_t Size;
733 uint64_t Offset;
734 };
735
736 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
737 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
738
739 // Populate sizes and offsets of fields.
740 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
741 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
742 SSV[i].Offset =
743 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
744
745 size_t NumFields = 0;
746 for (const auto *Field : ClassDecl->fields()) {
747 const FieldDecl *D = Field;
748 std::pair<CharUnits, CharUnits> FieldInfo =
749 Context.getTypeInfoInChars(D->getType());
750 CharUnits FieldSize = FieldInfo.first;
751 assert(NumFields < SSV.size());
752 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
753 NumFields++;
754 }
755 assert(NumFields == SSV.size());
756 if (SSV.size() <= 1) return;
757
758 // We will insert calls to __asan_* run-time functions.
759 // LLVM AddressSanitizer pass may decide to inline them later.
760 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
761 llvm::FunctionType *FTy =
762 llvm::FunctionType::get(CGM.VoidTy, Args, false);
763 llvm::Constant *F = CGM.CreateRuntimeFunction(
764 FTy, Prologue ? "__asan_poison_intra_object_redzone"
765 : "__asan_unpoison_intra_object_redzone");
766
767 llvm::Value *ThisPtr = LoadCXXThis();
768 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000769 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000770 // For each field check if it has sufficient padding,
771 // if so (un)poison it with a call.
772 for (size_t i = 0; i < SSV.size(); i++) {
773 uint64_t AsanAlignment = 8;
774 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
775 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
776 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
777 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
778 (NextField % AsanAlignment) != 0)
779 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000780 Builder.CreateCall(
781 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
782 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000783 }
784}
785
John McCallb81884d2010-02-19 09:25:03 +0000786/// EmitConstructorBody - Emits the body of the current constructor.
787void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000788 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000789 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
790 CXXCtorType CtorType = CurGD.getCtorType();
791
Reid Kleckner340ad862014-01-13 22:57:31 +0000792 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
793 CtorType == Ctor_Complete) &&
794 "can only generate complete ctor for this ABI");
795
John McCallf8ff7b92010-02-23 00:48:20 +0000796 // Before we go any further, try the complete->base constructor
797 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000798 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000799 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000800 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000801 return;
802 }
803
Richard Smith46bb5812014-08-01 01:56:39 +0000804 const FunctionDecl *Definition = 0;
805 Stmt *Body = Ctor->getBody(Definition);
806 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000807
John McCallf8ff7b92010-02-23 00:48:20 +0000808 // Enter the function-try-block before the constructor prologue if
809 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000810 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000811 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000812 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000813
Justin Bogner66242d62015-04-23 23:06:47 +0000814 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000815
Richard Smithcc1b96d2013-06-12 22:31:48 +0000816 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000817
John McCall88313032012-03-30 04:25:03 +0000818 // TODO: in restricted cases, we can emit the vbase initializers of
819 // a complete ctor and then delegate to the base ctor.
820
John McCallf8ff7b92010-02-23 00:48:20 +0000821 // Emit the constructor prologue, i.e. the base and member
822 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000823 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000824
825 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000826 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000827 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
828 else if (Body)
829 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000830
831 // Emit any cleanup blocks associated with the member or base
832 // initializers, which includes (along the exceptional path) the
833 // destructors for those members and bases that were fully
834 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000835 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000836
John McCallf8ff7b92010-02-23 00:48:20 +0000837 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000838 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000839}
840
Lang Hamesbf122742013-02-17 07:22:09 +0000841namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000842 /// RAII object to indicate that codegen is copying the value representation
843 /// instead of the object representation. Useful when copying a struct or
844 /// class which has uninitialized members and we're only performing
845 /// lvalue-to-rvalue conversion on the object but not its members.
846 class CopyingValueRepresentation {
847 public:
848 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000849 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000850 CGF.SanOpts.set(SanitizerKind::Bool, false);
851 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000852 }
853 ~CopyingValueRepresentation() {
854 CGF.SanOpts = OldSanOpts;
855 }
856 private:
857 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000858 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000859 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000860}
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000861
862namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000863 class FieldMemcpyizer {
864 public:
865 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
866 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000867 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000868 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000869 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
870 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000871
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000872 bool isMemcpyableField(FieldDecl *F) const {
873 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000874 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000875 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000876 Qualifiers Qual = F->getType().getQualifiers();
877 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
878 return false;
879 return true;
880 }
881
882 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000883 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000884 addInitialField(F);
885 else
886 addNextField(F);
887 }
888
David Majnemera586eb22014-10-10 18:57:10 +0000889 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000890 unsigned LastFieldSize =
891 LastField->isBitField() ?
892 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +0000893 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +0000894 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000895 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000896 CGF.getContext().getCharWidth() - 1;
897 CharUnits MemcpySize =
898 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
899 return MemcpySize;
900 }
901
902 void emitMemcpy() {
903 // Give the subclass a chance to bail out if it feels the memcpy isn't
904 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000905 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000906 return;
907 }
908
Lang Hames1694e0d2013-02-27 04:14:49 +0000909 CharUnits Alignment;
Lang Hamesbf122742013-02-17 07:22:09 +0000910
David Majnemera586eb22014-10-10 18:57:10 +0000911 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000912 if (FirstField->isBitField()) {
913 const CGRecordLayout &RL =
914 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
915 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
Lang Hames1694e0d2013-02-27 04:14:49 +0000916 Alignment = CharUnits::fromQuantity(BFInfo.StorageAlignment);
David Majnemera586eb22014-10-10 18:57:10 +0000917 // FirstFieldOffset is not appropriate for bitfields,
918 // it won't tell us what the storage offset should be and thus might not
919 // be properly aligned.
920 //
921 // Instead calculate the storage offset using the offset of the field in
922 // the struct type.
923 const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
924 FirstByteOffset =
925 DL.getStructLayout(RL.getLLVMType())
926 ->getElementOffsetInBits(RL.getLLVMFieldNo(FirstField));
Lang Hames1694e0d2013-02-27 04:14:49 +0000927 } else {
Lang Hames224ae882013-03-05 20:27:24 +0000928 Alignment = CGF.getContext().getDeclAlign(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000929 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000930 }
Lang Hamesbf122742013-02-17 07:22:09 +0000931
David Majnemera586eb22014-10-10 18:57:10 +0000932 assert((CGF.getContext().toCharUnitsFromBits(FirstByteOffset) %
Lang Hames1694e0d2013-02-27 04:14:49 +0000933 Alignment) == 0 && "Bad field alignment.");
934
David Majnemera586eb22014-10-10 18:57:10 +0000935 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000936 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
937 llvm::Value *ThisPtr = CGF.LoadCXXThis();
938 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
939 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
940 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
941 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
942 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
943
944 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
945 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
946 MemcpySize, Alignment);
947 reset();
948 }
949
950 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000951 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000952 }
953
954 protected:
955 CodeGenFunction &CGF;
956 const CXXRecordDecl *ClassDecl;
957
958 private:
959
960 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
961 CharUnits Size, CharUnits Alignment) {
962 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
963 llvm::Type *DBP =
964 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
965 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
966
967 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
968 llvm::Type *SBP =
969 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
970 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
971
972 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
973 Alignment.getQuantity());
974 }
975
976 void addInitialField(FieldDecl *F) {
977 FirstField = F;
978 LastField = F;
979 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
980 LastFieldOffset = FirstFieldOffset;
981 LastAddedFieldIndex = F->getFieldIndex();
982 return;
983 }
984
985 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000986 // For the most part, the following invariant will hold:
987 // F->getFieldIndex() == LastAddedFieldIndex + 1
988 // The one exception is that Sema won't add a copy-initializer for an
989 // unnamed bitfield, which will show up here as a gap in the sequence.
990 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
991 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000992 LastAddedFieldIndex = F->getFieldIndex();
993
994 // The 'first' and 'last' fields are chosen by offset, rather than field
995 // index. This allows the code to support bitfields, as well as regular
996 // fields.
997 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
998 if (FOffset < FirstFieldOffset) {
999 FirstField = F;
1000 FirstFieldOffset = FOffset;
1001 } else if (FOffset > LastFieldOffset) {
1002 LastField = F;
1003 LastFieldOffset = FOffset;
1004 }
1005 }
1006
1007 const VarDecl *SrcRec;
1008 const ASTRecordLayout &RecLayout;
1009 FieldDecl *FirstField;
1010 FieldDecl *LastField;
1011 uint64_t FirstFieldOffset, LastFieldOffset;
1012 unsigned LastAddedFieldIndex;
1013 };
1014
1015 class ConstructorMemcpyizer : public FieldMemcpyizer {
1016 private:
1017
1018 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001019 /// constructor.
1020 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1021 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001022 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001023 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001024 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001025 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001026 }
1027
1028 // Returns true if a CXXCtorInitializer represents a member initialization
1029 // that can be rolled into a memcpy.
1030 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1031 if (!MemcpyableCtor)
1032 return false;
1033 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001034 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001035 QualType FieldType = Field->getType();
1036 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1037
Richard Smith419bd092015-04-29 19:26:57 +00001038 // Bail out on non-memcpyable, not-trivially-copyable members.
1039 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001040 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1041 FieldType->isReferenceType()))
1042 return false;
1043
1044 // Bail out on volatile fields.
1045 if (!isMemcpyableField(Field))
1046 return false;
1047
1048 // Otherwise we're good.
1049 return true;
1050 }
1051
1052 public:
1053 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1054 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001055 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001056 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001057 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001058 CD->isCopyOrMoveConstructor() &&
1059 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1060 Args(Args) { }
1061
1062 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1063 if (isMemberInitMemcpyable(MemberInit)) {
1064 AggregatedInits.push_back(MemberInit);
1065 addMemcpyableField(MemberInit->getMember());
1066 } else {
1067 emitAggregatedInits();
1068 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1069 ConstructorDecl, Args);
1070 }
1071 }
1072
1073 void emitAggregatedInits() {
1074 if (AggregatedInits.size() <= 1) {
1075 // This memcpy is too small to be worthwhile. Fall back on default
1076 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001077 if (!AggregatedInits.empty()) {
1078 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001079 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001080 AggregatedInits[0], ConstructorDecl, Args);
Lang Hamesbf122742013-02-17 07:22:09 +00001081 }
1082 reset();
1083 return;
1084 }
1085
1086 pushEHDestructors();
1087 emitMemcpy();
1088 AggregatedInits.clear();
1089 }
1090
1091 void pushEHDestructors() {
1092 llvm::Value *ThisPtr = CGF.LoadCXXThis();
1093 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
1094 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
1095
1096 for (unsigned i = 0; i < AggregatedInits.size(); ++i) {
1097 QualType FieldType = AggregatedInits[i]->getMember()->getType();
1098 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
1099 if (CGF.needsEHCleanup(dtorKind))
1100 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
1101 }
1102 }
1103
1104 void finish() {
1105 emitAggregatedInits();
1106 }
1107
1108 private:
1109 const CXXConstructorDecl *ConstructorDecl;
1110 bool MemcpyableCtor;
1111 FunctionArgList &Args;
1112 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1113 };
1114
1115 class AssignmentMemcpyizer : public FieldMemcpyizer {
1116 private:
1117
1118 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001119 // exists. Otherwise returns null.
1120 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001121 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001122 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001123 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1124 // Recognise trivial assignments.
1125 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001126 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001127 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1128 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001129 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001130 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1131 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001132 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001133 Stmt *RHS = BO->getRHS();
1134 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1135 RHS = EC->getSubExpr();
1136 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001137 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001138 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1139 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
Craig Topper8a13c412014-05-21 05:09:00 +00001140 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001141 return Field;
1142 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1143 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001144 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001145 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001146 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1147 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001148 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001149 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1150 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001151 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001152 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1153 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001154 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001155 return Field;
1156 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1157 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1158 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001159 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001160 Expr *DstPtr = CE->getArg(0);
1161 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1162 DstPtr = DC->getSubExpr();
1163 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1164 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001165 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001166 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1167 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001168 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001169 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1170 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001171 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001172 Expr *SrcPtr = CE->getArg(1);
1173 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1174 SrcPtr = SC->getSubExpr();
1175 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1176 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001177 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001178 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1179 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001180 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001181 return Field;
1182 }
1183
Craig Topper8a13c412014-05-21 05:09:00 +00001184 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001185 }
1186
1187 bool AssignmentsMemcpyable;
1188 SmallVector<Stmt*, 16> AggregatedStmts;
1189
1190 public:
1191
1192 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1193 FunctionArgList &Args)
1194 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1195 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1196 assert(Args.size() == 2);
1197 }
1198
1199 void emitAssignment(Stmt *S) {
1200 FieldDecl *F = getMemcpyableField(S);
1201 if (F) {
1202 addMemcpyableField(F);
1203 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001204 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001205 emitAggregatedStmts();
1206 CGF.EmitStmt(S);
1207 }
1208 }
1209
1210 void emitAggregatedStmts() {
1211 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001212 if (!AggregatedStmts.empty()) {
1213 CopyingValueRepresentation CVR(CGF);
1214 CGF.EmitStmt(AggregatedStmts[0]);
1215 }
Lang Hamesbf122742013-02-17 07:22:09 +00001216 reset();
1217 }
1218
1219 emitMemcpy();
1220 AggregatedStmts.clear();
1221 }
1222
1223 void finish() {
1224 emitAggregatedStmts();
1225 }
1226 };
1227
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001228}
Lang Hamesbf122742013-02-17 07:22:09 +00001229
Anders Carlssonfb404882009-12-24 22:46:43 +00001230/// EmitCtorPrologue - This routine generates necessary code to initialize
1231/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001232void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001233 CXXCtorType CtorType,
1234 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001235 if (CD->isDelegatingConstructor())
1236 return EmitDelegatingCXXConstructorCall(CD, Args);
1237
Anders Carlssonfb404882009-12-24 22:46:43 +00001238 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001239
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001240 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1241 E = CD->init_end();
1242
Craig Topper8a13c412014-05-21 05:09:00 +00001243 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001244 if (ClassDecl->getNumVBases() &&
1245 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1246 // The ABIs that don't have constructor variants need to put a branch
1247 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001248 BaseCtorContinueBB =
1249 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001250 assert(BaseCtorContinueBB);
1251 }
1252
1253 // Virtual base initializers first.
1254 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1255 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1256 }
1257
1258 if (BaseCtorContinueBB) {
1259 // Complete object handler should continue to the remaining initializers.
1260 Builder.CreateBr(BaseCtorContinueBB);
1261 EmitBlock(BaseCtorContinueBB);
1262 }
1263
1264 // Then, non-virtual base initializers.
1265 for (; B != E && (*B)->isBaseInitializer(); B++) {
1266 assert(!(*B)->isBaseVirtual());
1267 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001268 }
1269
Anders Carlssond5895932010-03-28 21:07:49 +00001270 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001271
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001272 // And finally, initialize class members.
Richard Smith852c9db2013-04-20 22:23:05 +00001273 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hamesbf122742013-02-17 07:22:09 +00001274 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001275 for (; B != E; B++) {
1276 CXXCtorInitializer *Member = (*B);
1277 assert(!Member->isBaseInitializer());
1278 assert(Member->isAnyMemberInitializer() &&
1279 "Delegating initializer on non-delegating constructor");
1280 CM.addMemberInitializer(Member);
1281 }
Lang Hamesbf122742013-02-17 07:22:09 +00001282 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001283}
1284
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001285static bool
1286FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1287
1288static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001289HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001290 const CXXRecordDecl *BaseClassDecl,
1291 const CXXRecordDecl *MostDerivedClassDecl)
1292{
1293 // If the destructor is trivial we don't have to check anything else.
1294 if (BaseClassDecl->hasTrivialDestructor())
1295 return true;
1296
1297 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1298 return false;
1299
1300 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001301 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001302 if (!FieldHasTrivialDestructorBody(Context, Field))
1303 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001304
1305 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001306 for (const auto &I : BaseClassDecl->bases()) {
1307 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001308 continue;
1309
1310 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001311 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001312 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1313 MostDerivedClassDecl))
1314 return false;
1315 }
1316
1317 if (BaseClassDecl == MostDerivedClassDecl) {
1318 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001319 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001320 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001321 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001322 if (!HasTrivialDestructorBody(Context, VirtualBase,
1323 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001324 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001325 }
1326 }
1327
1328 return true;
1329}
1330
1331static bool
1332FieldHasTrivialDestructorBody(ASTContext &Context,
1333 const FieldDecl *Field)
1334{
1335 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1336
1337 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1338 if (!RT)
1339 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001340
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001341 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001342
1343 // The destructor for an implicit anonymous union member is never invoked.
1344 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1345 return false;
1346
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001347 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1348}
1349
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001350/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1351/// any vtable pointers before calling this destructor.
1352static bool CanSkipVTablePointerInitialization(ASTContext &Context,
Anders Carlssond6f15182011-05-16 04:08:36 +00001353 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001354 if (!Dtor->hasTrivialBody())
1355 return false;
1356
1357 // Check the fields.
1358 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001359 for (const auto *Field : ClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001360 if (!FieldHasTrivialDestructorBody(Context, Field))
1361 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001362
1363 return true;
1364}
1365
John McCallb81884d2010-02-19 09:25:03 +00001366/// EmitDestructorBody - Emits the body of the current destructor.
1367void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1368 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1369 CXXDtorType DtorType = CurGD.getDtorType();
1370
Justin Bognerfb298222015-05-20 16:16:23 +00001371 Stmt *Body = Dtor->getBody();
1372 if (Body)
1373 incrementProfileCounter(Body);
1374
John McCallf99a6312010-07-21 05:30:47 +00001375 // The call to operator delete in a deleting destructor happens
1376 // outside of the function-try-block, which means it's always
1377 // possible to delegate the destructor body to the complete
1378 // destructor. Do so.
1379 if (DtorType == Dtor_Deleting) {
1380 EnterDtorCleanups(Dtor, Dtor_Deleting);
1381 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001382 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001383 PopCleanupBlock();
1384 return;
1385 }
1386
John McCallb81884d2010-02-19 09:25:03 +00001387 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001388 // anything else.
1389 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001390 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001391 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001392 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001393
John McCallf99a6312010-07-21 05:30:47 +00001394 // Enter the epilogue cleanups.
1395 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001396
John McCallb81884d2010-02-19 09:25:03 +00001397 // If this is the complete variant, just invoke the base variant;
1398 // the epilogue will destruct the virtual bases. But we can't do
1399 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001400 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001401 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001402 switch (DtorType) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00001403 case Dtor_Comdat:
1404 llvm_unreachable("not expecting a COMDAT");
1405
John McCallf99a6312010-07-21 05:30:47 +00001406 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1407
1408 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001409 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1410 "can't emit a dtor without a body for non-Microsoft ABIs");
1411
John McCallf99a6312010-07-21 05:30:47 +00001412 // Enter the cleanup scopes for virtual bases.
1413 EnterDtorCleanups(Dtor, Dtor_Complete);
1414
Reid Klecknere7de47e2013-07-22 13:51:44 +00001415 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001416 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001417 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001418 break;
1419 }
1420 // Fallthrough: act like we're in the base variant.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001421
John McCallf99a6312010-07-21 05:30:47 +00001422 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001423 assert(Body);
1424
John McCallf99a6312010-07-21 05:30:47 +00001425 // Enter the cleanup scopes for fields and non-virtual bases.
1426 EnterDtorCleanups(Dtor, Dtor_Base);
1427
1428 // Initialize the vtable pointers before entering the body.
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001429 if (!CanSkipVTablePointerInitialization(getContext(), Dtor))
1430 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +00001431
1432 if (isTryBody)
1433 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1434 else if (Body)
1435 EmitStmt(Body);
1436 else {
1437 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1438 // nothing to do besides what's in the epilogue
1439 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001440 // -fapple-kext must inline any call to this dtor into
1441 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001442 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +00001443 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
John McCallf99a6312010-07-21 05:30:47 +00001444 break;
John McCallb81884d2010-02-19 09:25:03 +00001445 }
1446
John McCallf99a6312010-07-21 05:30:47 +00001447 // Jump out through the epilogue cleanups.
1448 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001449
1450 // Exit the try if applicable.
1451 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001452 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001453}
1454
Lang Hamesbf122742013-02-17 07:22:09 +00001455void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1456 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1457 const Stmt *RootS = AssignOp->getBody();
1458 assert(isa<CompoundStmt>(RootS) &&
1459 "Body of an implicit assignment operator should be compound stmt.");
1460 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1461
1462 LexicalScope Scope(*this, RootCS->getSourceRange());
1463
1464 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001465 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001466 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001467 AM.finish();
1468}
1469
John McCallf99a6312010-07-21 05:30:47 +00001470namespace {
1471 /// Call the operator delete associated with the current destructor.
John McCallcda666c2010-07-21 07:22:38 +00001472 struct CallDtorDelete : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001473 CallDtorDelete() {}
1474
Craig Topper4f12f102014-03-12 06:41:41 +00001475 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001476 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1477 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1478 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1479 CGF.getContext().getTagDeclType(ClassDecl));
1480 }
1481 };
1482
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001483 struct CallDtorDeleteConditional : EHScopeStack::Cleanup {
1484 llvm::Value *ShouldDeleteCondition;
1485 public:
1486 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
1487 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001488 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001489 }
1490
Craig Topper4f12f102014-03-12 06:41:41 +00001491 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001492 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1493 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1494 llvm::Value *ShouldCallDelete
1495 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1496 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1497
1498 CGF.EmitBlock(callDeleteBB);
1499 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1500 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1501 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1502 CGF.getContext().getTagDeclType(ClassDecl));
1503 CGF.Builder.CreateBr(continueBB);
1504
1505 CGF.EmitBlock(continueBB);
1506 }
1507 };
1508
John McCall4bd0fb12011-07-12 16:41:08 +00001509 class DestroyField : public EHScopeStack::Cleanup {
1510 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001511 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001512 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001513
John McCall4bd0fb12011-07-12 16:41:08 +00001514 public:
1515 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1516 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001517 : field(field), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001518 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001519
Craig Topper4f12f102014-03-12 06:41:41 +00001520 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001521 // Find the address of the field.
1522 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001523 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1524 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1525 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001526 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001527
John McCall4bd0fb12011-07-12 16:41:08 +00001528 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001529 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001530 }
1531 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001532}
John McCallf99a6312010-07-21 05:30:47 +00001533
Hans Wennborgdeff7032013-12-18 01:39:59 +00001534/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001535/// destructor. This is to call destructors on members and base classes
1536/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001537void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1538 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001539 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1540 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001541
John McCallf99a6312010-07-21 05:30:47 +00001542 // The deleting-destructor phase just needs to call the appropriate
1543 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001544 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001545 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001546 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001547 if (CXXStructorImplicitParamValue) {
1548 // If there is an implicit param to the deleting dtor, it's a boolean
1549 // telling whether we should call delete at the end of the dtor.
1550 EHStack.pushCleanup<CallDtorDeleteConditional>(
1551 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1552 } else {
1553 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1554 }
John McCall5c60a6f2010-02-18 19:59:28 +00001555 return;
1556 }
1557
John McCallf99a6312010-07-21 05:30:47 +00001558 const CXXRecordDecl *ClassDecl = DD->getParent();
1559
Richard Smith20104042011-09-18 12:11:43 +00001560 // Unions have no bases and do not call field destructors.
1561 if (ClassDecl->isUnion())
1562 return;
1563
John McCallf99a6312010-07-21 05:30:47 +00001564 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001565 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001566
1567 // We push them in the forward order so that they'll be popped in
1568 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001569 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001570 CXXRecordDecl *BaseClassDecl
1571 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001572
John McCall5c60a6f2010-02-18 19:59:28 +00001573 // Ignore trivial destructors.
1574 if (BaseClassDecl->hasTrivialDestructor())
1575 continue;
John McCallf99a6312010-07-21 05:30:47 +00001576
John McCallcda666c2010-07-21 07:22:38 +00001577 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1578 BaseClassDecl,
1579 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001580 }
John McCallf99a6312010-07-21 05:30:47 +00001581
John McCall5c60a6f2010-02-18 19:59:28 +00001582 return;
1583 }
1584
1585 assert(DtorType == Dtor_Base);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001586
John McCallf99a6312010-07-21 05:30:47 +00001587 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001588 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001589 // Ignore virtual bases.
1590 if (Base.isVirtual())
1591 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001592
John McCallf99a6312010-07-21 05:30:47 +00001593 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001594
John McCallf99a6312010-07-21 05:30:47 +00001595 // Ignore trivial destructors.
1596 if (BaseClassDecl->hasTrivialDestructor())
1597 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001598
John McCallcda666c2010-07-21 07:22:38 +00001599 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1600 BaseClassDecl,
1601 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001602 }
1603
1604 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001605 for (const auto *Field : ClassDecl->fields()) {
1606 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001607 QualType::DestructionKind dtorKind = type.isDestructedType();
1608 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001609
Richard Smith921bd202012-02-26 09:11:52 +00001610 // Anonymous union members do not have their destructors called.
1611 const RecordType *RT = type->getAsUnionType();
1612 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1613
John McCall4bd0fb12011-07-12 16:41:08 +00001614 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001615 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001616 getDestroyer(dtorKind),
1617 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001618 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001619}
1620
John McCallf677a8e2011-07-13 06:10:41 +00001621/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1622/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001623///
John McCallf677a8e2011-07-13 06:10:41 +00001624/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001625/// \param arrayType the type of the array to initialize
1626/// \param arrayBegin an arrayType*
1627/// \param zeroInitialize true if each element should be
1628/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001629void CodeGenFunction::EmitCXXAggrConstructorCall(
1630 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1631 llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001632 QualType elementType;
1633 llvm::Value *numElements =
1634 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001635
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001636 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001637}
1638
John McCallf677a8e2011-07-13 06:10:41 +00001639/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1640/// constructor for each of several members of an array.
1641///
1642/// \param ctor the constructor to call for each element
1643/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001644/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001645/// \param arrayBegin a T*, where T is the type constructed by ctor
1646/// \param zeroInitialize true if each element should be
1647/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001648void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1649 llvm::Value *numElements,
1650 llvm::Value *arrayBegin,
1651 const CXXConstructExpr *E,
1652 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001653
1654 // It's legal for numElements to be zero. This can happen both
1655 // dynamically, because x can be zero in 'new A[x]', and statically,
1656 // because of GCC extensions that permit zero-length arrays. There
1657 // are probably legitimate places where we could assume that this
1658 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001659 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001660
1661 // Optimize for a constant count.
1662 llvm::ConstantInt *constantCount
1663 = dyn_cast<llvm::ConstantInt>(numElements);
1664 if (constantCount) {
1665 // Just skip out if the constant count is zero.
1666 if (constantCount->isZero()) return;
1667
1668 // Otherwise, emit the check.
1669 } else {
1670 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1671 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1672 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1673 EmitBlock(loopBB);
1674 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001675
John McCallf677a8e2011-07-13 06:10:41 +00001676 // Find the end of the array.
1677 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1678 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001679
John McCallf677a8e2011-07-13 06:10:41 +00001680 // Enter the loop, setting up a phi for the current location to initialize.
1681 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1682 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1683 EmitBlock(loopBB);
1684 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1685 "arrayctor.cur");
1686 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001687
Anders Carlsson27da15b2010-01-01 20:29:01 +00001688 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001689
1690 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001691
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001692 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001693 if (zeroInitialize)
1694 EmitNullInitialization(cur, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001695
1696 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001697 // There are two contexts in which temporaries are destroyed at a different
1698 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001699 // default constructor is called to initialize an element of an array.
1700 // If the constructor has one or more default arguments, the destruction of
1701 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001702 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001703
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001704 {
John McCallbd309292010-07-06 01:34:17 +00001705 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001706
John McCallf677a8e2011-07-13 06:10:41 +00001707 // Evaluate the constructor and its arguments in a regular
1708 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001709 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001710 !ctor->getParent()->hasTrivialDestructor()) {
1711 Destroyer *destroyer = destroyCXXObject;
1712 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1713 }
1714
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001715 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1716 /*Delegating=*/false, cur, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001717 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001718
John McCallf677a8e2011-07-13 06:10:41 +00001719 // Go to the next element.
1720 llvm::Value *next =
1721 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1722 "arrayctor.next");
1723 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001724
John McCallf677a8e2011-07-13 06:10:41 +00001725 // Check whether that's the end of the loop.
1726 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1727 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1728 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001729
John McCall6549b312011-07-13 07:37:11 +00001730 // Patch the earlier check to skip over the loop.
1731 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1732
John McCallf677a8e2011-07-13 06:10:41 +00001733 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001734}
1735
John McCall82fe67b2011-07-09 01:37:26 +00001736void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1737 llvm::Value *addr,
1738 QualType type) {
1739 const RecordType *rtype = type->castAs<RecordType>();
1740 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1741 const CXXDestructorDecl *dtor = record->getDestructor();
1742 assert(!dtor->isTrivial());
1743 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001744 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001745}
1746
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001747void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1748 CXXCtorType Type,
1749 bool ForVirtualBase,
1750 bool Delegating, llvm::Value *This,
1751 const CXXConstructExpr *E) {
Richard Smith419bd092015-04-29 19:26:57 +00001752 // C++11 [class.mfct.non-static]p2:
1753 // If a non-static member function of a class X is called for an object that
1754 // is not of type X, or of a type derived from X, the behavior is undefined.
1755 // FIXME: Provide a source location here.
1756 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
1757 getContext().getRecordType(D->getParent()));
John McCallca972cd2010-02-06 00:25:16 +00001758
Richard Smith419bd092015-04-29 19:26:57 +00001759 if (D->isTrivial() && D->isDefaultConstructor()) {
1760 assert(E->getNumArgs() == 0 && "trivial default ctor with args");
1761 return;
1762 }
1763
1764 // If this is a trivial constructor, just emit what's needed. If this is a
1765 // union copy constructor, we must emit a memcpy, because the AST does not
1766 // model that copy.
1767 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001768 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00001769
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001770 const Expr *Arg = E->getArg(0);
David Majnemerfd1e7392015-02-03 23:04:06 +00001771 QualType SrcTy = Arg->getType();
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001772 llvm::Value *Src = EmitLValue(Arg).getAddress();
David Majnemerfd1e7392015-02-03 23:04:06 +00001773 QualType DestTy = getContext().getTypeDeclType(D->getParent());
1774 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001775 return;
1776 }
1777
Reid Kleckner89077a12013-12-17 19:46:40 +00001778 CallArgList Args;
1779
1780 // Push the this ptr.
1781 Args.add(RValue::get(This), D->getThisType(getContext()));
1782
1783 // Add the rest of the user-supplied arguments.
1784 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001785 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end(), E->getConstructor());
Reid Kleckner89077a12013-12-17 19:46:40 +00001786
1787 // Insert any ABI-specific implicit constructor arguments.
1788 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1789 *this, D, Type, ForVirtualBase, Delegating, Args);
1790
1791 // Emit the call.
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001792 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
Reid Kleckner89077a12013-12-17 19:46:40 +00001793 const CGFunctionInfo &Info =
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001794 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
Reid Kleckner89077a12013-12-17 19:46:40 +00001795 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001796}
1797
John McCallf8ff7b92010-02-23 00:48:20 +00001798void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001799CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1800 llvm::Value *This, llvm::Value *Src,
Alexey Samsonov525bf652014-08-25 21:58:56 +00001801 const CXXConstructExpr *E) {
Richard Smith419bd092015-04-29 19:26:57 +00001802 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov96fd0a42014-08-26 20:18:26 +00001803 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001804 assert(D->isCopyOrMoveConstructor() &&
1805 "trivial 1-arg ctor not a copy/move ctor");
David Majnemerfd1e7392015-02-03 23:04:06 +00001806 EmitAggregateCopyCtor(This, Src,
1807 getContext().getTypeDeclType(D->getParent()),
1808 E->arg_begin()->getType());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001809 return;
1810 }
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001811 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001812 assert(D->isInstance() &&
1813 "Trying to emit a member call expr on a static method!");
Justin Bogner1cd11f12015-05-20 15:53:59 +00001814
Reid Kleckner739756c2013-12-04 19:23:12 +00001815 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001816
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001817 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001818
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001819 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001820 Args.add(RValue::get(This), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00001821
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001822 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00001823 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001824 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001825 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001826 Args.add(RValue::get(Src), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00001827
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001828 // Skip over first argument (Src).
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001829 EmitCallArgs(Args, FPT, E->arg_begin() + 1, E->arg_end(), E->getConstructor(),
1830 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001831
John McCall8dda7b22012-07-07 06:41:13 +00001832 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1833 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001834}
1835
1836void
John McCallf8ff7b92010-02-23 00:48:20 +00001837CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1838 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001839 const FunctionArgList &Args,
1840 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00001841 CallArgList DelegateArgs;
1842
1843 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1844 assert(I != E && "no parameters to constructor");
1845
1846 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001847 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001848 ++I;
1849
1850 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001851 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00001852 /*ForVirtualBase=*/false,
1853 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001854 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001855 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001856
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001857 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001858 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001859 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001860 ++I;
1861 }
1862 }
1863
1864 // Explicit arguments.
1865 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001866 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001867 // FIXME: per-argument source location
1868 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00001869 }
1870
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001871 llvm::Value *Callee =
1872 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001873 EmitCall(CGM.getTypes()
1874 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
Manman Ren01754612013-03-20 16:59:38 +00001875 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00001876}
1877
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001878namespace {
1879 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup {
1880 const CXXDestructorDecl *Dtor;
1881 llvm::Value *Addr;
1882 CXXDtorType Type;
1883
1884 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1885 CXXDtorType Type)
1886 : Dtor(D), Addr(Addr), Type(Type) {}
1887
Craig Topper4f12f102014-03-12 06:41:41 +00001888 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001889 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001890 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001891 }
1892 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001893}
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001894
Alexis Hunt61bc1732011-05-01 07:04:31 +00001895void
1896CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
1897 const FunctionArgList &Args) {
1898 assert(Ctor->isDelegatingConstructor());
1899
1900 llvm::Value *ThisPtr = LoadCXXThis();
1901
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001902 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00001903 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00001904 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00001905 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00001906 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001907 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001908 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001909
1910 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00001911
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001912 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001913 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001914 CXXDtorType Type =
1915 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
1916
1917 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
1918 ClassDecl->getDestructor(),
1919 ThisPtr, Type);
1920 }
1921}
Alexis Hunt61bc1732011-05-01 07:04:31 +00001922
Anders Carlsson27da15b2010-01-01 20:29:01 +00001923void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
1924 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00001925 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00001926 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00001927 llvm::Value *This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00001928 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
1929 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001930}
1931
John McCall53cad2e2010-07-21 01:41:18 +00001932namespace {
John McCallcda666c2010-07-21 07:22:38 +00001933 struct CallLocalDtor : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00001934 const CXXDestructorDecl *Dtor;
1935 llvm::Value *Addr;
1936
1937 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
1938 : Dtor(D), Addr(Addr) {}
1939
Craig Topper4f12f102014-03-12 06:41:41 +00001940 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00001941 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00001942 /*ForVirtualBase=*/false,
1943 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00001944 }
1945 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001946}
John McCall53cad2e2010-07-21 01:41:18 +00001947
John McCall8680f872010-07-21 06:29:51 +00001948void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
1949 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00001950 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00001951}
1952
John McCallbd309292010-07-06 01:34:17 +00001953void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
1954 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
1955 if (!ClassDecl) return;
1956 if (ClassDecl->hasTrivialDestructor()) return;
1957
1958 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00001959 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00001960 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00001961}
1962
Anders Carlssone87fae92010-03-28 19:40:00 +00001963void
Justin Bogner1cd11f12015-05-20 15:53:59 +00001964CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00001965 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00001966 CharUnits OffsetFromNearestVBase,
Anders Carlssone87fae92010-03-28 19:40:00 +00001967 const CXXRecordDecl *VTableClass) {
David Majnemer129f4172015-02-02 10:22:20 +00001968 const CXXRecordDecl *RD = Base.getBase();
1969
1970 // Don't initialize the vtable pointer if the class is marked with the
1971 // 'novtable' attribute.
1972 if ((RD == VTableClass || RD == NearestVBase) &&
David Majnemer8ab003a2015-02-02 19:30:52 +00001973 VTableClass->hasAttr<MSNoVTableAttr>())
David Majnemer129f4172015-02-02 10:22:20 +00001974 return;
1975
Anders Carlssone87fae92010-03-28 19:40:00 +00001976 // Compute the address point.
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001977 bool NeedsVirtualOffset;
1978 llvm::Value *VTableAddressPoint =
1979 CGM.getCXXABI().getVTableAddressPointInStructor(
1980 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
1981 if (!VTableAddressPoint)
1982 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00001983
Anders Carlsson6a0227d2010-04-20 16:22:16 +00001984 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00001985 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00001986 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001987
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00001988 if (NeedsVirtualOffset) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00001989 // We need to use the virtual base offset offset because the virtual base
1990 // might have a different offset in the most derived class.
Reid Klecknerd8cbeec2013-05-29 18:02:47 +00001991 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
1992 LoadCXXThis(),
1993 VTableClass,
1994 NearestVBase);
Ken Dyck3fb4c892011-03-23 01:04:18 +00001995 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00001996 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00001997 // We can just use the base offset in the complete class.
Ken Dyck16ffcac2011-03-24 01:21:01 +00001998 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00001999 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002000
Anders Carlssonc58fb552010-05-03 00:29:58 +00002001 // Apply the offsets.
2002 llvm::Value *VTableField = LoadCXXThis();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002003
Ken Dyckcfc332c2011-03-23 00:45:26 +00002004 if (!NonVirtualOffset.isZero() || VirtualOffset)
Justin Bogner1cd11f12015-05-20 15:53:59 +00002005 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
Anders Carlssonc58fb552010-05-03 00:29:58 +00002006 NonVirtualOffset,
2007 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002008
Reid Kleckner8d585132014-12-03 21:00:21 +00002009 // Finally, store the address point. Use the same LLVM types as the field to
2010 // support optimization.
2011 llvm::Type *VTablePtrTy =
2012 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2013 ->getPointerTo()
2014 ->getPointerTo();
2015 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2016 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002017 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2018 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00002019}
2020
Anders Carlssond5895932010-03-28 21:07:49 +00002021void
Justin Bogner1cd11f12015-05-20 15:53:59 +00002022CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
Anders Carlsson652758c2010-04-20 05:22:15 +00002023 const CXXRecordDecl *NearestVBase,
Ken Dyck3fb4c892011-03-23 01:04:18 +00002024 CharUnits OffsetFromNearestVBase,
Anders Carlssond5895932010-03-28 21:07:49 +00002025 bool BaseIsNonVirtualPrimaryBase,
Anders Carlssond5895932010-03-28 21:07:49 +00002026 const CXXRecordDecl *VTableClass,
2027 VisitedVirtualBasesSetTy& VBases) {
2028 // If this base is a non-virtual primary base the address point has already
2029 // been set.
2030 if (!BaseIsNonVirtualPrimaryBase) {
2031 // Initialize the vtable pointer for this base.
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002032 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002033 VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00002034 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002035
Anders Carlssond5895932010-03-28 21:07:49 +00002036 const CXXRecordDecl *RD = Base.getBase();
2037
2038 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002039 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002040 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002041 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002042
2043 // Ignore classes without a vtable.
2044 if (!BaseDecl->isDynamicClass())
2045 continue;
2046
Ken Dyck3fb4c892011-03-23 01:04:18 +00002047 CharUnits BaseOffset;
2048 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002049 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002050
Aaron Ballman574705e2014-03-13 15:41:46 +00002051 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002052 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002053 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002054 continue;
2055
Justin Bogner1cd11f12015-05-20 15:53:59 +00002056 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002057 getContext().getASTRecordLayout(VTableClass);
2058
Ken Dyck3fb4c892011-03-23 01:04:18 +00002059 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2060 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002061 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002062 } else {
2063 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2064
Ken Dyck16ffcac2011-03-24 01:21:01 +00002065 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002066 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002067 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002068 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002069 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002070
2071 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
Aaron Ballman574705e2014-03-13 15:41:46 +00002072 I.isVirtual() ? BaseDecl : NearestVBase,
Anders Carlssonc4d0d0f2010-05-03 00:07:07 +00002073 BaseOffsetFromNearestVBase,
Justin Bogner1cd11f12015-05-20 15:53:59 +00002074 BaseDeclIsNonVirtualPrimaryBase,
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002075 VTableClass, VBases);
Anders Carlssond5895932010-03-28 21:07:49 +00002076 }
2077}
2078
2079void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2080 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002081 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002082 return;
2083
Anders Carlssond5895932010-03-28 21:07:49 +00002084 // Initialize the vtable pointers for this class and all of its bases.
2085 VisitedVirtualBasesSetTy VBases;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002086 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
Craig Topper8a13c412014-05-21 05:09:00 +00002087 /*NearestVBase=*/nullptr,
Ken Dyck3fb4c892011-03-23 01:04:18 +00002088 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
Timur Iskhodzhanovd8fa10d2013-08-21 17:33:16 +00002089 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002090
2091 if (RD->getNumVBases())
2092 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002093}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002094
2095llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00002096 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00002097 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002098 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2099 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2100 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002101}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002102
Peter Collingbourned2926c92015-03-14 02:42:25 +00002103// If a class has a single non-virtual base and does not introduce or override
2104// virtual member functions or fields, it will have the same layout as its base.
2105// This function returns the least derived such class.
2106//
2107// Casting an instance of a base class to such a derived class is technically
2108// undefined behavior, but it is a relatively common hack for introducing member
2109// functions on class instances with specific properties (e.g. llvm::Operator)
2110// that works under most compilers and should not have security implications, so
2111// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2112static const CXXRecordDecl *
2113LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2114 if (!RD->field_empty())
2115 return RD;
2116
2117 if (RD->getNumVBases() != 0)
2118 return RD;
2119
2120 if (RD->getNumBases() != 1)
2121 return RD;
2122
2123 for (const CXXMethodDecl *MD : RD->methods()) {
2124 if (MD->isVirtual()) {
2125 // Virtual member functions are only ok if they are implicit destructors
2126 // because the implicit destructor will have the same semantics as the
2127 // base class's destructor if no fields are added.
2128 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2129 continue;
2130 return RD;
2131 }
2132 }
2133
2134 return LeastDerivedClassWithSameLayout(
2135 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2136}
2137
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002138void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002139 llvm::Value *VTable,
2140 CFITypeCheckKind TCK,
2141 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002142 const CXXRecordDecl *ClassDecl = MD->getParent();
2143 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2144 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2145
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002146 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002147}
2148
Peter Collingbourned2926c92015-03-14 02:42:25 +00002149void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2150 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002151 bool MayBeNull,
2152 CFITypeCheckKind TCK,
2153 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002154 if (!getLangOpts().CPlusPlus)
2155 return;
2156
2157 auto *ClassTy = T->getAs<RecordType>();
2158 if (!ClassTy)
2159 return;
2160
2161 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2162
2163 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2164 return;
2165
2166 SmallString<64> MangledName;
2167 llvm::raw_svector_ostream Out(MangledName);
2168 CGM.getCXXABI().getMangleContext().mangleCXXRTTI(T.getUnqualifiedType(),
2169 Out);
2170
2171 // Blacklist based on the mangled type.
2172 if (CGM.getContext().getSanitizerBlacklist().isBlacklistedType(Out.str()))
2173 return;
2174
2175 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2176 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2177
2178 llvm::BasicBlock *ContBlock = 0;
2179
2180 if (MayBeNull) {
2181 llvm::Value *DerivedNotNull =
2182 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2183
2184 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2185 ContBlock = createBasicBlock("cast.cont");
2186
2187 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2188
2189 EmitBlock(CheckBlock);
2190 }
2191
2192 llvm::Value *VTable = GetVTablePtr(Derived, Int8PtrTy);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002193 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002194
2195 if (MayBeNull) {
2196 Builder.CreateBr(ContBlock);
2197 EmitBlock(ContBlock);
2198 }
2199}
2200
2201void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002202 llvm::Value *VTable,
2203 CFITypeCheckKind TCK,
2204 SourceLocation Loc) {
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002205 // FIXME: Add blacklisting scheme.
2206 if (RD->isInStdNamespace())
2207 return;
2208
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002209 SanitizerScope SanScope(this);
2210
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002211 std::string OutName;
2212 llvm::raw_string_ostream Out(OutName);
2213 CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
2214
2215 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
2216 getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
2217
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002218 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2219 llvm::Value *BitSetTest =
2220 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2221 {CastedVTable, BitSetName});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002222
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002223 SanitizerMask M;
2224 switch (TCK) {
2225 case CFITCK_VCall:
2226 M = SanitizerKind::CFIVCall;
2227 break;
2228 case CFITCK_NVCall:
2229 M = SanitizerKind::CFINVCall;
2230 break;
2231 case CFITCK_DerivedCast:
2232 M = SanitizerKind::CFIDerivedCast;
2233 break;
2234 case CFITCK_UnrelatedCast:
2235 M = SanitizerKind::CFIUnrelatedCast;
2236 break;
2237 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002238
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002239 llvm::Constant *StaticData[] = {
2240 EmitCheckSourceLocation(Loc),
2241 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2242 llvm::ConstantInt::get(Int8Ty, TCK),
2243 };
2244 EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
2245 CastedVTable);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002246}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002247
2248// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2249// quite what we want.
2250static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2251 while (true) {
2252 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2253 E = PE->getSubExpr();
2254 continue;
2255 }
2256
2257 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2258 if (CE->getCastKind() == CK_NoOp) {
2259 E = CE->getSubExpr();
2260 continue;
2261 }
2262 }
2263 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2264 if (UO->getOpcode() == UO_Extension) {
2265 E = UO->getSubExpr();
2266 continue;
2267 }
2268 }
2269 return E;
2270 }
2271}
2272
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002273bool
2274CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2275 const CXXMethodDecl *MD) {
2276 // When building with -fapple-kext, all calls must go through the vtable since
2277 // the kernel linker can do runtime patching of vtables.
2278 if (getLangOpts().AppleKext)
2279 return false;
2280
Anders Carlssonc36783e2011-05-08 20:32:23 +00002281 // If the most derived class is marked final, we know that no subclass can
2282 // override this member function and so we can devirtualize it. For example:
2283 //
2284 // struct A { virtual void f(); }
2285 // struct B final : A { };
2286 //
2287 // void f(B *b) {
2288 // b->f();
2289 // }
2290 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002291 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002292 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2293 return true;
2294
2295 // If the member function is marked 'final', we know that it can't be
2296 // overridden and can therefore devirtualize it.
2297 if (MD->hasAttr<FinalAttr>())
2298 return true;
2299
2300 // Similarly, if the class itself is marked 'final' it can't be overridden
2301 // and we can therefore devirtualize the member function call.
2302 if (MD->getParent()->hasAttr<FinalAttr>())
2303 return true;
2304
2305 Base = skipNoOpCastsAndParens(Base);
2306 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2307 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2308 // This is a record decl. We know the type and can devirtualize it.
2309 return VD->getType()->isRecordType();
2310 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002311
Anders Carlssonc36783e2011-05-08 20:32:23 +00002312 return false;
2313 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002314
2315 // We can devirtualize calls on an object accessed by a class member access
2316 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2317 // a derived class object constructed in the same location.
2318 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2319 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2320 return VD->getType()->isRecordType();
2321
Anders Carlssonc36783e2011-05-08 20:32:23 +00002322 // We can always devirtualize calls on temporary object expressions.
2323 if (isa<CXXConstructExpr>(Base))
2324 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002325
Anders Carlssonc36783e2011-05-08 20:32:23 +00002326 // And calls on bound temporaries.
2327 if (isa<CXXBindTemporaryExpr>(Base))
2328 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002329
Anders Carlssonc36783e2011-05-08 20:32:23 +00002330 // Check if this is a call expr that returns a record type.
2331 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
David Majnemerced8bdf2015-02-25 17:36:15 +00002332 return CE->getCallReturnType(getContext())->isRecordType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002333
2334 // We can't devirtualize the call.
2335 return false;
2336}
2337
Faisal Vali571df122013-09-29 08:45:24 +00002338void CodeGenFunction::EmitForwardingCallToLambda(
2339 const CXXMethodDecl *callOperator,
2340 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002341 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002342 const CGFunctionInfo &calleeFnInfo =
2343 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2344 llvm::Value *callee =
2345 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2346 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002347
John McCall8dda7b22012-07-07 06:41:13 +00002348 // Prepare the return slot.
2349 const FunctionProtoType *FPT =
2350 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002351 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002352 ReturnValueSlot returnSlot;
2353 if (!resultType->isVoidType() &&
2354 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002355 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002356 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2357
2358 // We don't need to separately arrange the call arguments because
2359 // the call can't be variadic anyway --- it's impossible to forward
2360 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002361
Eli Friedman5b446882012-02-16 03:47:28 +00002362 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002363 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2364 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002365
John McCall8dda7b22012-07-07 06:41:13 +00002366 // If necessary, copy the returned value into the slot.
2367 if (!resultType->isVoidType() && returnSlot.isNull())
2368 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002369 else
2370 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002371}
2372
Eli Friedman2495ab02012-02-25 02:48:22 +00002373void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2374 const BlockDecl *BD = BlockInfo->getBlockDecl();
2375 const VarDecl *variable = BD->capture_begin()->getVariable();
2376 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2377
2378 // Start building arguments for forwarding call
2379 CallArgList CallArgs;
2380
2381 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2382 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2383 CallArgs.add(RValue::get(ThisPtr), ThisType);
2384
2385 // Add the rest of the parameters.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002386 for (auto param : BD->params())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002387 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002388
Justin Bogner1cd11f12015-05-20 15:53:59 +00002389 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002390 "generic lambda interconversion to block not implemented");
2391 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002392}
2393
2394void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002395 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002396 // FIXME: Making this work correctly is nasty because it requires either
2397 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002398 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002399 return;
2400 }
2401
Richard Smithb47c36f2013-11-05 09:12:18 +00002402 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002403}
2404
2405void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2406 const CXXRecordDecl *Lambda = MD->getParent();
2407
2408 // Start building arguments for forwarding call
2409 CallArgList CallArgs;
2410
2411 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2412 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2413 CallArgs.add(RValue::get(ThisPtr), ThisType);
2414
2415 // Add the rest of the parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002416 for (auto Param : MD->params())
2417 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2418
Faisal Vali571df122013-09-29 08:45:24 +00002419 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2420 // For a generic lambda, find the corresponding call operator specialization
2421 // to which the call to the static-invoker shall be forwarded.
2422 if (Lambda->isGenericLambda()) {
2423 assert(MD->isFunctionTemplateSpecialization());
2424 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2425 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002426 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002427 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002428 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002429 assert(CorrespondingCallOpSpecialization);
2430 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2431 }
2432 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002433}
2434
Douglas Gregor355efbb2012-02-17 03:02:34 +00002435void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2436 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002437 // FIXME: Making this work correctly is nasty because it requires either
2438 // cloning the body of the call operator or making the call operator forward.
2439 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002440 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002441 }
2442
Douglas Gregor355efbb2012-02-17 03:02:34 +00002443 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002444}