blob: 3cada88b48759e2b7c516013653fe79cf5b64944 [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.
David Blaikie7e70d682015-08-18 22:40:54 +0000348 struct CallBaseDtor final : 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
Alexey Bataev152c71f2015-07-14 07:55:48 +0000557static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF,
558 CXXCtorInitializer *MemberInit,
559 LValue &LHS) {
560 FieldDecl *Field = MemberInit->getAnyMember();
561 if (MemberInit->isIndirectMemberInitializer()) {
562 // If we are initializing an anonymous union field, drill down to the field.
563 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember();
564 for (const auto *I : IndirectField->chain())
565 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I));
566 } else {
567 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field);
568 }
569}
570
Anders Carlssonfb404882009-12-24 22:46:43 +0000571static void EmitMemberInitializer(CodeGenFunction &CGF,
572 const CXXRecordDecl *ClassDecl,
Alexis Hunt1d792652011-01-08 20:30:50 +0000573 CXXCtorInitializer *MemberInit,
Douglas Gregor94f9a482010-05-05 05:51:00 +0000574 const CXXConstructorDecl *Constructor,
575 FunctionArgList &Args) {
David Blaikiea81d4102015-01-18 00:12:58 +0000576 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation());
Francois Pichetd583da02010-12-04 09:14:42 +0000577 assert(MemberInit->isAnyMemberInitializer() &&
Anders Carlssonfb404882009-12-24 22:46:43 +0000578 "Must have member initializer!");
Richard Smith938f40b2011-06-11 17:19:42 +0000579 assert(MemberInit->getInit() && "Must have initializer!");
Justin Bogner1cd11f12015-05-20 15:53:59 +0000580
Anders Carlssonfb404882009-12-24 22:46:43 +0000581 // non-static data member initializers.
Francois Pichetd583da02010-12-04 09:14:42 +0000582 FieldDecl *Field = MemberInit->getAnyMember();
Eli Friedman6ae63022012-02-14 02:15:49 +0000583 QualType FieldType = Field->getType();
Anders Carlssonfb404882009-12-24 22:46:43 +0000584
585 llvm::Value *ThisPtr = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +0000586 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
Eli Friedmanf6d21842012-08-08 03:51:37 +0000587 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
Eli Friedman7f1ff602012-04-16 03:54:45 +0000588
Alexey Bataev152c71f2015-07-14 07:55:48 +0000589 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS);
Anders Carlssonfb404882009-12-24 22:46:43 +0000590
Eli Friedman6ae63022012-02-14 02:15:49 +0000591 // Special case: if we are in a copy or move constructor, and we are copying
592 // an array of PODs or classes with trivial copy constructors, ignore the
593 // AST and perform the copy we know is equivalent.
594 // FIXME: This is hacky at best... if we had a bit more explicit information
595 // in the AST, we could generalize it more easily.
596 const ConstantArrayType *Array
597 = CGF.getContext().getAsConstantArrayType(FieldType);
Jordan Rose54533f72013-08-07 16:16:48 +0000598 if (Array && Constructor->isDefaulted() &&
Eli Friedman6ae63022012-02-14 02:15:49 +0000599 Constructor->isCopyOrMoveConstructor()) {
600 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array);
Richard Smith993f25a2012-11-07 23:56:21 +0000601 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
Eli Friedman6ae63022012-02-14 02:15:49 +0000602 if (BaseElementTy.isPODType(CGF.getContext()) ||
Richard Smith419bd092015-04-29 19:26:57 +0000603 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) {
David Majnemer1573d732014-10-15 04:54:54 +0000604 unsigned SrcArgIndex =
605 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args);
Eli Friedman6ae63022012-02-14 02:15:49 +0000606 llvm::Value *SrcPtr
607 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex]));
Eli Friedman7f1ff602012-04-16 03:54:45 +0000608 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
609 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000610
Eli Friedman6ae63022012-02-14 02:15:49 +0000611 // Copy the aggregate.
612 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType,
Chad Rosier615ed1a2012-03-29 17:37:10 +0000613 LHS.isVolatileQualified());
Alexey Bataev5d49b832015-07-08 07:31:02 +0000614 // Ensure that we destroy the objects if an exception is thrown later in
615 // the constructor.
616 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
617 if (CGF.needsEHCleanup(dtorKind))
618 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Eli Friedman6ae63022012-02-14 02:15:49 +0000619 return;
620 }
621 }
622
623 ArrayRef<VarDecl *> ArrayIndexes;
624 if (MemberInit->getNumArrayIndices())
625 ArrayIndexes = MemberInit->getArrayIndexes();
David Blaikie66e41972015-01-14 07:38:27 +0000626 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit(), ArrayIndexes);
Eli Friedman6ae63022012-02-14 02:15:49 +0000627}
628
David Blaikie66e41972015-01-14 07:38:27 +0000629void CodeGenFunction::EmitInitializerForField(
630 FieldDecl *Field, LValue LHS, Expr *Init,
631 ArrayRef<VarDecl *> ArrayIndexes) {
Eli Friedman6ae63022012-02-14 02:15:49 +0000632 QualType FieldType = Field->getType();
John McCall47fb9502013-03-07 21:37:08 +0000633 switch (getEvaluationKind(FieldType)) {
634 case TEK_Scalar:
John McCall31168b02011-06-15 23:02:42 +0000635 if (LHS.isSimple()) {
David Blaikie66e41972015-01-14 07:38:27 +0000636 EmitExprAsInit(Init, Field, LHS, false);
John McCall31168b02011-06-15 23:02:42 +0000637 } else {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000638 RValue RHS = RValue::get(EmitScalarExpr(Init));
639 EmitStoreThroughLValue(RHS, LHS);
John McCall31168b02011-06-15 23:02:42 +0000640 }
John McCall47fb9502013-03-07 21:37:08 +0000641 break;
642 case TEK_Complex:
David Blaikie66e41972015-01-14 07:38:27 +0000643 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true);
John McCall47fb9502013-03-07 21:37:08 +0000644 break;
645 case TEK_Aggregate: {
Craig Topper8a13c412014-05-21 05:09:00 +0000646 llvm::Value *ArrayIndexVar = nullptr;
Eli Friedman6ae63022012-02-14 02:15:49 +0000647 if (ArrayIndexes.size()) {
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000648 llvm::Type *SizeTy = ConvertType(getContext().getSizeType());
Justin Bogner1cd11f12015-05-20 15:53:59 +0000649
Douglas Gregor94f9a482010-05-05 05:51:00 +0000650 // The LHS is a pointer to the first object we'll be constructing, as
651 // a flat array.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000652 QualType BaseElementTy = getContext().getBaseElementType(FieldType);
653 llvm::Type *BasePtr = ConvertType(BaseElementTy);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000654 BasePtr = llvm::PointerType::getUnqual(BasePtr);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000655 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(LHS.getAddress(),
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000656 BasePtr);
657 LHS = MakeAddrLValue(BaseAddrPtr, BaseElementTy);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000658
Douglas Gregor94f9a482010-05-05 05:51:00 +0000659 // Create an array index that will be used to walk over all of the
660 // objects we're constructing.
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000661 ArrayIndexVar = CreateTempAlloca(SizeTy, "object.index");
Douglas Gregor94f9a482010-05-05 05:51:00 +0000662 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy);
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000663 Builder.CreateStore(Zero, ArrayIndexVar);
Justin Bogner1cd11f12015-05-20 15:53:59 +0000664
665
Douglas Gregor94f9a482010-05-05 05:51:00 +0000666 // Emit the block variables for the array indices, if any.
Eli Friedman6ae63022012-02-14 02:15:49 +0000667 for (unsigned I = 0, N = ArrayIndexes.size(); I != N; ++I)
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000668 EmitAutoVarDecl(*ArrayIndexes[I]);
Douglas Gregor94f9a482010-05-05 05:51:00 +0000669 }
Justin Bogner1cd11f12015-05-20 15:53:59 +0000670
Eli Friedman5f1a04f2012-02-14 02:31:03 +0000671 EmitAggMemberInitializer(*this, LHS, Init, ArrayIndexVar, FieldType,
Eli Friedman6ae63022012-02-14 02:15:49 +0000672 ArrayIndexes, 0);
Anders Carlssonfb404882009-12-24 22:46:43 +0000673 }
John McCall47fb9502013-03-07 21:37:08 +0000674 }
John McCall12cc42a2013-02-01 05:11:40 +0000675
676 // Ensure that we destroy this object if an exception is thrown
677 // later in the constructor.
678 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
679 if (needsEHCleanup(dtorKind))
680 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType);
Anders Carlssonfb404882009-12-24 22:46:43 +0000681}
682
John McCallf8ff7b92010-02-23 00:48:20 +0000683/// Checks whether the given constructor is a valid subject for the
684/// complete-to-base constructor delegation optimization, i.e.
685/// emitting the complete constructor as a simple call to the base
686/// constructor.
687static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) {
688
689 // Currently we disable the optimization for classes with virtual
690 // bases because (1) the addresses of parameter variables need to be
691 // consistent across all initializers but (2) the delegate function
692 // call necessarily creates a second copy of the parameter variable.
693 //
694 // The limiting example (purely theoretical AFAIK):
695 // struct A { A(int &c) { c++; } };
696 // struct B : virtual A {
697 // B(int count) : A(count) { printf("%d\n", count); }
698 // };
699 // ...although even this example could in principle be emitted as a
700 // delegation since the address of the parameter doesn't escape.
701 if (Ctor->getParent()->getNumVBases()) {
702 // TODO: white-list trivial vbase initializers. This case wouldn't
703 // be subject to the restrictions below.
704
705 // TODO: white-list cases where:
706 // - there are no non-reference parameters to the constructor
707 // - the initializers don't access any non-reference parameters
708 // - the initializers don't take the address of non-reference
709 // parameters
710 // - etc.
711 // If we ever add any of the above cases, remember that:
712 // - function-try-blocks will always blacklist this optimization
713 // - we need to perform the constructor prologue and cleanup in
714 // EmitConstructorBody.
715
716 return false;
717 }
718
719 // We also disable the optimization for variadic functions because
720 // it's impossible to "re-pass" varargs.
721 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic())
722 return false;
723
Alexis Hunt61bc1732011-05-01 07:04:31 +0000724 // FIXME: Decide if we can do a delegation of a delegating constructor.
725 if (Ctor->isDelegatingConstructor())
726 return false;
727
John McCallf8ff7b92010-02-23 00:48:20 +0000728 return true;
729}
730
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000731// Emit code in ctor (Prologue==true) or dtor (Prologue==false)
732// to poison the extra field paddings inserted under
733// -fsanitize-address-field-padding=1|2.
734void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) {
735 ASTContext &Context = getContext();
736 const CXXRecordDecl *ClassDecl =
737 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent()
738 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent();
739 if (!ClassDecl->mayInsertExtraPadding()) return;
740
741 struct SizeAndOffset {
742 uint64_t Size;
743 uint64_t Offset;
744 };
745
746 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits();
747 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl);
748
749 // Populate sizes and offsets of fields.
750 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount());
751 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i)
752 SSV[i].Offset =
753 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity();
754
755 size_t NumFields = 0;
756 for (const auto *Field : ClassDecl->fields()) {
757 const FieldDecl *D = Field;
758 std::pair<CharUnits, CharUnits> FieldInfo =
759 Context.getTypeInfoInChars(D->getType());
760 CharUnits FieldSize = FieldInfo.first;
761 assert(NumFields < SSV.size());
762 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity();
763 NumFields++;
764 }
765 assert(NumFields == SSV.size());
766 if (SSV.size() <= 1) return;
767
768 // We will insert calls to __asan_* run-time functions.
769 // LLVM AddressSanitizer pass may decide to inline them later.
770 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy};
771 llvm::FunctionType *FTy =
772 llvm::FunctionType::get(CGM.VoidTy, Args, false);
773 llvm::Constant *F = CGM.CreateRuntimeFunction(
774 FTy, Prologue ? "__asan_poison_intra_object_redzone"
775 : "__asan_unpoison_intra_object_redzone");
776
777 llvm::Value *ThisPtr = LoadCXXThis();
778 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy);
Kostya Serebryany64449212014-10-17 21:02:13 +0000779 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity();
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000780 // For each field check if it has sufficient padding,
781 // if so (un)poison it with a call.
782 for (size_t i = 0; i < SSV.size(); i++) {
783 uint64_t AsanAlignment = 8;
784 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset;
785 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size;
786 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size;
787 if (PoisonSize < AsanAlignment || !SSV[i].Size ||
788 (NextField % AsanAlignment) != 0)
789 continue;
David Blaikie43f9bb72015-05-18 22:14:03 +0000790 Builder.CreateCall(
791 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)),
792 Builder.getIntN(PtrSize, PoisonSize)});
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000793 }
794}
795
John McCallb81884d2010-02-19 09:25:03 +0000796/// EmitConstructorBody - Emits the body of the current constructor.
797void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000798 EmitAsanPrologueOrEpilogue(true);
John McCallb81884d2010-02-19 09:25:03 +0000799 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl());
800 CXXCtorType CtorType = CurGD.getCtorType();
801
Reid Kleckner340ad862014-01-13 22:57:31 +0000802 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() ||
803 CtorType == Ctor_Complete) &&
804 "can only generate complete ctor for this ABI");
805
John McCallf8ff7b92010-02-23 00:48:20 +0000806 // Before we go any further, try the complete->base constructor
807 // delegation optimization.
Timur Iskhodzhanovf32a3772012-04-20 08:05:00 +0000808 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
John McCallc8e01702013-04-16 22:48:15 +0000809 CGM.getTarget().getCXXABI().hasConstructorVariants()) {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000810 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd());
John McCallf8ff7b92010-02-23 00:48:20 +0000811 return;
812 }
813
Richard Smith46bb5812014-08-01 01:56:39 +0000814 const FunctionDecl *Definition = 0;
815 Stmt *Body = Ctor->getBody(Definition);
816 assert(Definition == Ctor && "emitting wrong constructor body");
John McCallb81884d2010-02-19 09:25:03 +0000817
John McCallf8ff7b92010-02-23 00:48:20 +0000818 // Enter the function-try-block before the constructor prologue if
819 // applicable.
John McCallf8ff7b92010-02-23 00:48:20 +0000820 bool IsTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallf8ff7b92010-02-23 00:48:20 +0000821 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000822 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000823
Justin Bogner66242d62015-04-23 23:06:47 +0000824 incrementProfileCounter(Body);
Justin Bogner81c22c22014-01-23 02:54:27 +0000825
Richard Smithcc1b96d2013-06-12 22:31:48 +0000826 RunCleanupsScope RunCleanups(*this);
John McCallb81884d2010-02-19 09:25:03 +0000827
John McCall88313032012-03-30 04:25:03 +0000828 // TODO: in restricted cases, we can emit the vbase initializers of
829 // a complete ctor and then delegate to the base ctor.
830
John McCallf8ff7b92010-02-23 00:48:20 +0000831 // Emit the constructor prologue, i.e. the base and member
832 // initializers.
Douglas Gregor94f9a482010-05-05 05:51:00 +0000833 EmitCtorPrologue(Ctor, CtorType, Args);
John McCallb81884d2010-02-19 09:25:03 +0000834
835 // Emit the body of the statement.
John McCallf8ff7b92010-02-23 00:48:20 +0000836 if (IsTryBody)
John McCallb81884d2010-02-19 09:25:03 +0000837 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
838 else if (Body)
839 EmitStmt(Body);
John McCallb81884d2010-02-19 09:25:03 +0000840
841 // Emit any cleanup blocks associated with the member or base
842 // initializers, which includes (along the exceptional path) the
843 // destructors for those members and bases that were fully
844 // constructed.
Richard Smithcc1b96d2013-06-12 22:31:48 +0000845 RunCleanups.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +0000846
John McCallf8ff7b92010-02-23 00:48:20 +0000847 if (IsTryBody)
John McCallb609d3f2010-07-07 06:56:46 +0000848 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +0000849}
850
Lang Hamesbf122742013-02-17 07:22:09 +0000851namespace {
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000852 /// RAII object to indicate that codegen is copying the value representation
853 /// instead of the object representation. Useful when copying a struct or
854 /// class which has uninitialized members and we're only performing
855 /// lvalue-to-rvalue conversion on the object but not its members.
856 class CopyingValueRepresentation {
857 public:
858 explicit CopyingValueRepresentation(CodeGenFunction &CGF)
Alexey Samsonov035462c2014-10-30 19:33:44 +0000859 : CGF(CGF), OldSanOpts(CGF.SanOpts) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000860 CGF.SanOpts.set(SanitizerKind::Bool, false);
861 CGF.SanOpts.set(SanitizerKind::Enum, false);
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000862 }
863 ~CopyingValueRepresentation() {
864 CGF.SanOpts = OldSanOpts;
865 }
866 private:
867 CodeGenFunction &CGF;
Alexey Samsonova0416102014-11-11 01:26:14 +0000868 SanitizerSet OldSanOpts;
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000869 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000870}
Nick Lewycky8b4e3792013-09-11 02:03:20 +0000871
872namespace {
Lang Hamesbf122742013-02-17 07:22:09 +0000873 class FieldMemcpyizer {
874 public:
875 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl,
876 const VarDecl *SrcRec)
Justin Bogner1cd11f12015-05-20 15:53:59 +0000877 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec),
Lang Hamesbf122742013-02-17 07:22:09 +0000878 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)),
Craig Topper8a13c412014-05-21 05:09:00 +0000879 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0),
880 LastFieldOffset(0), LastAddedFieldIndex(0) {}
Lang Hamesbf122742013-02-17 07:22:09 +0000881
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000882 bool isMemcpyableField(FieldDecl *F) const {
883 // Never memcpy fields when we are adding poisoned paddings.
Alexey Samsonova0416102014-11-11 01:26:14 +0000884 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding)
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000885 return false;
Lang Hamesbf122742013-02-17 07:22:09 +0000886 Qualifiers Qual = F->getType().getQualifiers();
887 if (Qual.hasVolatile() || Qual.hasObjCLifetime())
888 return false;
889 return true;
890 }
891
892 void addMemcpyableField(FieldDecl *F) {
Craig Topper8a13c412014-05-21 05:09:00 +0000893 if (!FirstField)
Lang Hamesbf122742013-02-17 07:22:09 +0000894 addInitialField(F);
895 else
896 addNextField(F);
897 }
898
David Majnemera586eb22014-10-10 18:57:10 +0000899 CharUnits getMemcpySize(uint64_t FirstByteOffset) const {
Lang Hamesbf122742013-02-17 07:22:09 +0000900 unsigned LastFieldSize =
901 LastField->isBitField() ?
902 LastField->getBitWidthValue(CGF.getContext()) :
Justin Bogner1cd11f12015-05-20 15:53:59 +0000903 CGF.getContext().getTypeSize(LastField->getType());
Lang Hamesbf122742013-02-17 07:22:09 +0000904 uint64_t MemcpySizeBits =
David Majnemera586eb22014-10-10 18:57:10 +0000905 LastFieldOffset + LastFieldSize - FirstByteOffset +
Lang Hamesbf122742013-02-17 07:22:09 +0000906 CGF.getContext().getCharWidth() - 1;
907 CharUnits MemcpySize =
908 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits);
909 return MemcpySize;
910 }
911
912 void emitMemcpy() {
913 // Give the subclass a chance to bail out if it feels the memcpy isn't
914 // worth it (e.g. Hasn't aggregated enough data).
Craig Topper8a13c412014-05-21 05:09:00 +0000915 if (!FirstField) {
Lang Hamesbf122742013-02-17 07:22:09 +0000916 return;
917 }
918
David Majnemera586eb22014-10-10 18:57:10 +0000919 uint64_t FirstByteOffset;
Lang Hamesbf122742013-02-17 07:22:09 +0000920 if (FirstField->isBitField()) {
921 const CGRecordLayout &RL =
922 CGF.getTypes().getCGRecordLayout(FirstField->getParent());
923 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField);
David Majnemera586eb22014-10-10 18:57:10 +0000924 // FirstFieldOffset is not appropriate for bitfields,
Ulrich Weigand73263d72015-07-13 11:52:14 +0000925 // we need to use the storage offset instead.
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000926 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset);
Lang Hames1694e0d2013-02-27 04:14:49 +0000927 } else {
David Majnemera586eb22014-10-10 18:57:10 +0000928 FirstByteOffset = FirstFieldOffset;
Lang Hames1694e0d2013-02-27 04:14:49 +0000929 }
Lang Hamesbf122742013-02-17 07:22:09 +0000930
David Majnemera586eb22014-10-10 18:57:10 +0000931 CharUnits MemcpySize = getMemcpySize(FirstByteOffset);
Lang Hamesbf122742013-02-17 07:22:09 +0000932 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl);
933 llvm::Value *ThisPtr = CGF.LoadCXXThis();
934 LValue DestLV = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy);
935 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField);
936 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec));
937 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy);
938 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField);
939
Ulrich Weigand03ce2a12015-07-10 17:30:00 +0000940 CharUnits Offset = CGF.getContext().toCharUnitsFromBits(FirstByteOffset);
941 CharUnits Alignment = DestLV.getAlignment().alignmentAtOffset(Offset);
942
Lang Hamesbf122742013-02-17 07:22:09 +0000943 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddr() : Dest.getAddress(),
944 Src.isBitField() ? Src.getBitFieldAddr() : Src.getAddress(),
945 MemcpySize, Alignment);
946 reset();
947 }
948
949 void reset() {
Craig Topper8a13c412014-05-21 05:09:00 +0000950 FirstField = nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +0000951 }
952
953 protected:
954 CodeGenFunction &CGF;
955 const CXXRecordDecl *ClassDecl;
956
957 private:
958
959 void emitMemcpyIR(llvm::Value *DestPtr, llvm::Value *SrcPtr,
960 CharUnits Size, CharUnits Alignment) {
961 llvm::PointerType *DPT = cast<llvm::PointerType>(DestPtr->getType());
962 llvm::Type *DBP =
963 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace());
964 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP);
965
966 llvm::PointerType *SPT = cast<llvm::PointerType>(SrcPtr->getType());
967 llvm::Type *SBP =
968 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace());
969 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP);
970
971 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity(),
972 Alignment.getQuantity());
973 }
974
975 void addInitialField(FieldDecl *F) {
976 FirstField = F;
977 LastField = F;
978 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex());
979 LastFieldOffset = FirstFieldOffset;
980 LastAddedFieldIndex = F->getFieldIndex();
981 return;
982 }
983
984 void addNextField(FieldDecl *F) {
John McCall6054d5a2013-05-07 05:20:46 +0000985 // For the most part, the following invariant will hold:
986 // F->getFieldIndex() == LastAddedFieldIndex + 1
987 // The one exception is that Sema won't add a copy-initializer for an
988 // unnamed bitfield, which will show up here as a gap in the sequence.
989 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 &&
990 "Cannot aggregate fields out of order.");
Lang Hamesbf122742013-02-17 07:22:09 +0000991 LastAddedFieldIndex = F->getFieldIndex();
992
993 // The 'first' and 'last' fields are chosen by offset, rather than field
994 // index. This allows the code to support bitfields, as well as regular
995 // fields.
996 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex());
997 if (FOffset < FirstFieldOffset) {
998 FirstField = F;
999 FirstFieldOffset = FOffset;
1000 } else if (FOffset > LastFieldOffset) {
1001 LastField = F;
1002 LastFieldOffset = FOffset;
1003 }
1004 }
1005
1006 const VarDecl *SrcRec;
1007 const ASTRecordLayout &RecLayout;
1008 FieldDecl *FirstField;
1009 FieldDecl *LastField;
1010 uint64_t FirstFieldOffset, LastFieldOffset;
1011 unsigned LastAddedFieldIndex;
1012 };
1013
1014 class ConstructorMemcpyizer : public FieldMemcpyizer {
1015 private:
1016
1017 /// Get source argument for copy constructor. Returns null if not a copy
David Majnemer196ac332014-09-11 23:05:02 +00001018 /// constructor.
1019 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF,
1020 const CXXConstructorDecl *CD,
Lang Hamesbf122742013-02-17 07:22:09 +00001021 FunctionArgList &Args) {
Jordan Rose54533f72013-08-07 16:16:48 +00001022 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted())
David Majnemer196ac332014-09-11 23:05:02 +00001023 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)];
Craig Topper8a13c412014-05-21 05:09:00 +00001024 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001025 }
1026
1027 // Returns true if a CXXCtorInitializer represents a member initialization
1028 // that can be rolled into a memcpy.
1029 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const {
1030 if (!MemcpyableCtor)
1031 return false;
1032 FieldDecl *Field = MemberInit->getMember();
Craig Topper8a13c412014-05-21 05:09:00 +00001033 assert(Field && "No field for member init.");
Lang Hamesbf122742013-02-17 07:22:09 +00001034 QualType FieldType = Field->getType();
1035 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit());
1036
Richard Smith419bd092015-04-29 19:26:57 +00001037 // Bail out on non-memcpyable, not-trivially-copyable members.
1038 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) &&
Lang Hamesbf122742013-02-17 07:22:09 +00001039 !(FieldType.isTriviallyCopyableType(CGF.getContext()) ||
1040 FieldType->isReferenceType()))
1041 return false;
1042
1043 // Bail out on volatile fields.
1044 if (!isMemcpyableField(Field))
1045 return false;
1046
1047 // Otherwise we're good.
1048 return true;
1049 }
1050
1051 public:
1052 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD,
1053 FunctionArgList &Args)
David Majnemer196ac332014-09-11 23:05:02 +00001054 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)),
Lang Hamesbf122742013-02-17 07:22:09 +00001055 ConstructorDecl(CD),
Jordan Rose54533f72013-08-07 16:16:48 +00001056 MemcpyableCtor(CD->isDefaulted() &&
Lang Hamesbf122742013-02-17 07:22:09 +00001057 CD->isCopyOrMoveConstructor() &&
1058 CGF.getLangOpts().getGC() == LangOptions::NonGC),
1059 Args(Args) { }
1060
1061 void addMemberInitializer(CXXCtorInitializer *MemberInit) {
1062 if (isMemberInitMemcpyable(MemberInit)) {
1063 AggregatedInits.push_back(MemberInit);
1064 addMemcpyableField(MemberInit->getMember());
1065 } else {
1066 emitAggregatedInits();
1067 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit,
1068 ConstructorDecl, Args);
1069 }
1070 }
1071
1072 void emitAggregatedInits() {
1073 if (AggregatedInits.size() <= 1) {
1074 // This memcpy is too small to be worthwhile. Fall back on default
1075 // codegen.
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001076 if (!AggregatedInits.empty()) {
1077 CopyingValueRepresentation CVR(CGF);
Lang Hamesbf122742013-02-17 07:22:09 +00001078 EmitMemberInitializer(CGF, ConstructorDecl->getParent(),
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001079 AggregatedInits[0], ConstructorDecl, Args);
Alexey Bataev152c71f2015-07-14 07:55:48 +00001080 AggregatedInits.clear();
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) {
Alexey Bataev152c71f2015-07-14 07:55:48 +00001097 CXXCtorInitializer *MemberInit = AggregatedInits[i];
1098 QualType FieldType = MemberInit->getAnyMember()->getType();
Lang Hamesbf122742013-02-17 07:22:09 +00001099 QualType::DestructionKind dtorKind = FieldType.isDestructedType();
Alexey Bataev152c71f2015-07-14 07:55:48 +00001100 if (!CGF.needsEHCleanup(dtorKind))
1101 continue;
1102 LValue FieldLHS = LHS;
1103 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS);
1104 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType);
Lang Hamesbf122742013-02-17 07:22:09 +00001105 }
1106 }
1107
1108 void finish() {
1109 emitAggregatedInits();
1110 }
1111
1112 private:
1113 const CXXConstructorDecl *ConstructorDecl;
1114 bool MemcpyableCtor;
1115 FunctionArgList &Args;
1116 SmallVector<CXXCtorInitializer*, 16> AggregatedInits;
1117 };
1118
1119 class AssignmentMemcpyizer : public FieldMemcpyizer {
1120 private:
1121
1122 // Returns the memcpyable field copied by the given statement, if one
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001123 // exists. Otherwise returns null.
1124 FieldDecl *getMemcpyableField(Stmt *S) {
Lang Hamesbf122742013-02-17 07:22:09 +00001125 if (!AssignmentsMemcpyable)
Craig Topper8a13c412014-05-21 05:09:00 +00001126 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001127 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) {
1128 // Recognise trivial assignments.
1129 if (BO->getOpcode() != BO_Assign)
Craig Topper8a13c412014-05-21 05:09:00 +00001130 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001131 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS());
1132 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001133 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001134 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1135 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001136 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001137 Stmt *RHS = BO->getRHS();
1138 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS))
1139 RHS = EC->getSubExpr();
1140 if (!RHS)
Craig Topper8a13c412014-05-21 05:09:00 +00001141 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001142 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS);
1143 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field)
Craig Topper8a13c412014-05-21 05:09:00 +00001144 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001145 return Field;
1146 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) {
1147 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl());
Richard Smith419bd092015-04-29 19:26:57 +00001148 if (!(MD && isMemcpyEquivalentSpecialMember(MD)))
Craig Topper8a13c412014-05-21 05:09:00 +00001149 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001150 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument());
1151 if (!IOA)
Craig Topper8a13c412014-05-21 05:09:00 +00001152 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001153 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl());
1154 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001155 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001156 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0));
1157 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001158 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001159 return Field;
1160 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
1161 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl());
1162 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy)
Craig Topper8a13c412014-05-21 05:09:00 +00001163 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001164 Expr *DstPtr = CE->getArg(0);
1165 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr))
1166 DstPtr = DC->getSubExpr();
1167 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr);
1168 if (!DUO || DUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001169 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001170 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr());
1171 if (!ME)
Craig Topper8a13c412014-05-21 05:09:00 +00001172 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001173 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
1174 if (!Field || !isMemcpyableField(Field))
Craig Topper8a13c412014-05-21 05:09:00 +00001175 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001176 Expr *SrcPtr = CE->getArg(1);
1177 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr))
1178 SrcPtr = SC->getSubExpr();
1179 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr);
1180 if (!SUO || SUO->getOpcode() != UO_AddrOf)
Craig Topper8a13c412014-05-21 05:09:00 +00001181 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001182 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr());
1183 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl()))
Craig Topper8a13c412014-05-21 05:09:00 +00001184 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001185 return Field;
1186 }
1187
Craig Topper8a13c412014-05-21 05:09:00 +00001188 return nullptr;
Lang Hamesbf122742013-02-17 07:22:09 +00001189 }
1190
1191 bool AssignmentsMemcpyable;
1192 SmallVector<Stmt*, 16> AggregatedStmts;
1193
1194 public:
1195
1196 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD,
1197 FunctionArgList &Args)
1198 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]),
1199 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) {
1200 assert(Args.size() == 2);
1201 }
1202
1203 void emitAssignment(Stmt *S) {
1204 FieldDecl *F = getMemcpyableField(S);
1205 if (F) {
1206 addMemcpyableField(F);
1207 AggregatedStmts.push_back(S);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001208 } else {
Lang Hamesbf122742013-02-17 07:22:09 +00001209 emitAggregatedStmts();
1210 CGF.EmitStmt(S);
1211 }
1212 }
1213
1214 void emitAggregatedStmts() {
1215 if (AggregatedStmts.size() <= 1) {
Nick Lewycky8b4e3792013-09-11 02:03:20 +00001216 if (!AggregatedStmts.empty()) {
1217 CopyingValueRepresentation CVR(CGF);
1218 CGF.EmitStmt(AggregatedStmts[0]);
1219 }
Lang Hamesbf122742013-02-17 07:22:09 +00001220 reset();
1221 }
1222
1223 emitMemcpy();
1224 AggregatedStmts.clear();
1225 }
1226
1227 void finish() {
1228 emitAggregatedStmts();
1229 }
1230 };
1231
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001232}
Lang Hamesbf122742013-02-17 07:22:09 +00001233
Anders Carlssonfb404882009-12-24 22:46:43 +00001234/// EmitCtorPrologue - This routine generates necessary code to initialize
1235/// base classes and non-static data members belonging to this constructor.
Anders Carlssonfb404882009-12-24 22:46:43 +00001236void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
Douglas Gregor94f9a482010-05-05 05:51:00 +00001237 CXXCtorType CtorType,
1238 FunctionArgList &Args) {
Alexis Hunt61bc1732011-05-01 07:04:31 +00001239 if (CD->isDelegatingConstructor())
1240 return EmitDelegatingCXXConstructorCall(CD, Args);
1241
Anders Carlssonfb404882009-12-24 22:46:43 +00001242 const CXXRecordDecl *ClassDecl = CD->getParent();
Anders Carlsson5dc86332010-02-02 19:58:43 +00001243
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001244 CXXConstructorDecl::init_const_iterator B = CD->init_begin(),
1245 E = CD->init_end();
1246
Craig Topper8a13c412014-05-21 05:09:00 +00001247 llvm::BasicBlock *BaseCtorContinueBB = nullptr;
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001248 if (ClassDecl->getNumVBases() &&
1249 !CGM.getTarget().getCXXABI().hasConstructorVariants()) {
1250 // The ABIs that don't have constructor variants need to put a branch
1251 // before the virtual base initialization code.
Reid Kleckner7810af02013-06-19 15:20:38 +00001252 BaseCtorContinueBB =
1253 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001254 assert(BaseCtorContinueBB);
1255 }
1256
1257 // Virtual base initializers first.
1258 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) {
1259 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
1260 }
1261
1262 if (BaseCtorContinueBB) {
1263 // Complete object handler should continue to the remaining initializers.
1264 Builder.CreateBr(BaseCtorContinueBB);
1265 EmitBlock(BaseCtorContinueBB);
1266 }
1267
1268 // Then, non-virtual base initializers.
1269 for (; B != E && (*B)->isBaseInitializer(); B++) {
1270 assert(!(*B)->isBaseVirtual());
1271 EmitBaseInitializer(*this, ClassDecl, *B, CtorType);
Anders Carlssonfb404882009-12-24 22:46:43 +00001272 }
1273
Anders Carlssond5895932010-03-28 21:07:49 +00001274 InitializeVTablePointers(ClassDecl);
Anders Carlsson5dc86332010-02-02 19:58:43 +00001275
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001276 // And finally, initialize class members.
Richard Smith852c9db2013-04-20 22:23:05 +00001277 FieldConstructionScope FCS(*this, CXXThisValue);
Lang Hamesbf122742013-02-17 07:22:09 +00001278 ConstructorMemcpyizer CM(*this, CD, Args);
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001279 for (; B != E; B++) {
1280 CXXCtorInitializer *Member = (*B);
1281 assert(!Member->isBaseInitializer());
1282 assert(Member->isAnyMemberInitializer() &&
1283 "Delegating initializer on non-delegating constructor");
1284 CM.addMemberInitializer(Member);
1285 }
Lang Hamesbf122742013-02-17 07:22:09 +00001286 CM.finish();
Anders Carlssonfb404882009-12-24 22:46:43 +00001287}
1288
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001289static bool
1290FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field);
1291
1292static bool
Justin Bogner1cd11f12015-05-20 15:53:59 +00001293HasTrivialDestructorBody(ASTContext &Context,
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001294 const CXXRecordDecl *BaseClassDecl,
1295 const CXXRecordDecl *MostDerivedClassDecl)
1296{
1297 // If the destructor is trivial we don't have to check anything else.
1298 if (BaseClassDecl->hasTrivialDestructor())
1299 return true;
1300
1301 if (!BaseClassDecl->getDestructor()->hasTrivialBody())
1302 return false;
1303
1304 // Check fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001305 for (const auto *Field : BaseClassDecl->fields())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001306 if (!FieldHasTrivialDestructorBody(Context, Field))
1307 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001308
1309 // Check non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001310 for (const auto &I : BaseClassDecl->bases()) {
1311 if (I.isVirtual())
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001312 continue;
1313
1314 const CXXRecordDecl *NonVirtualBase =
Aaron Ballman574705e2014-03-13 15:41:46 +00001315 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001316 if (!HasTrivialDestructorBody(Context, NonVirtualBase,
1317 MostDerivedClassDecl))
1318 return false;
1319 }
1320
1321 if (BaseClassDecl == MostDerivedClassDecl) {
1322 // Check virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001323 for (const auto &I : BaseClassDecl->vbases()) {
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001324 const CXXRecordDecl *VirtualBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00001325 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001326 if (!HasTrivialDestructorBody(Context, VirtualBase,
1327 MostDerivedClassDecl))
Justin Bogner1cd11f12015-05-20 15:53:59 +00001328 return false;
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001329 }
1330 }
1331
1332 return true;
1333}
1334
1335static bool
1336FieldHasTrivialDestructorBody(ASTContext &Context,
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001337 const FieldDecl *Field)
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001338{
1339 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType());
1340
1341 const RecordType *RT = FieldBaseElementType->getAs<RecordType>();
1342 if (!RT)
1343 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001344
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001345 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
Davide Italiano982bbf42015-06-26 00:18:35 +00001346
1347 // The destructor for an implicit anonymous union member is never invoked.
1348 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
1349 return false;
1350
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001351 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl);
1352}
1353
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001354/// CanSkipVTablePointerInitialization - Check whether we need to initialize
1355/// any vtable pointers before calling this destructor.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001356static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF,
Anders Carlssond6f15182011-05-16 04:08:36 +00001357 const CXXDestructorDecl *Dtor) {
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001358 if (!Dtor->hasTrivialBody())
1359 return false;
1360
1361 // Check the fields.
1362 const CXXRecordDecl *ClassDecl = Dtor->getParent();
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001363 for (const auto *Field : ClassDecl->fields())
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001364 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field))
Anders Carlsson49c0bd22011-05-15 17:36:21 +00001365 return false;
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001366
1367 return true;
1368}
1369
John McCallb81884d2010-02-19 09:25:03 +00001370/// EmitDestructorBody - Emits the body of the current destructor.
1371void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
1372 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl());
1373 CXXDtorType DtorType = CurGD.getDtorType();
1374
Justin Bognerfb298222015-05-20 16:16:23 +00001375 Stmt *Body = Dtor->getBody();
1376 if (Body)
1377 incrementProfileCounter(Body);
1378
John McCallf99a6312010-07-21 05:30:47 +00001379 // The call to operator delete in a deleting destructor happens
1380 // outside of the function-try-block, which means it's always
1381 // possible to delegate the destructor body to the complete
1382 // destructor. Do so.
1383 if (DtorType == Dtor_Deleting) {
1384 EnterDtorCleanups(Dtor, Dtor_Deleting);
1385 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001386 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001387 PopCleanupBlock();
1388 return;
1389 }
1390
John McCallb81884d2010-02-19 09:25:03 +00001391 // If the body is a function-try-block, enter the try before
John McCallf99a6312010-07-21 05:30:47 +00001392 // anything else.
1393 bool isTryBody = (Body && isa<CXXTryStmt>(Body));
John McCallb81884d2010-02-19 09:25:03 +00001394 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001395 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001396 EmitAsanPrologueOrEpilogue(false);
John McCallb81884d2010-02-19 09:25:03 +00001397
John McCallf99a6312010-07-21 05:30:47 +00001398 // Enter the epilogue cleanups.
1399 RunCleanupsScope DtorEpilogue(*this);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001400
John McCallb81884d2010-02-19 09:25:03 +00001401 // If this is the complete variant, just invoke the base variant;
1402 // the epilogue will destruct the virtual bases. But we can't do
1403 // this optimization if the body is a function-try-block, because
Justin Bogner1cd11f12015-05-20 15:53:59 +00001404 // we'd introduce *two* handler blocks. In the Microsoft ABI, we
Reid Klecknere7de47e2013-07-22 13:51:44 +00001405 // always delegate because we might not have a definition in this TU.
John McCallf99a6312010-07-21 05:30:47 +00001406 switch (DtorType) {
Rafael Espindola1e4df922014-09-16 15:18:21 +00001407 case Dtor_Comdat:
1408 llvm_unreachable("not expecting a COMDAT");
1409
John McCallf99a6312010-07-21 05:30:47 +00001410 case Dtor_Deleting: llvm_unreachable("already handled deleting case");
1411
1412 case Dtor_Complete:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001413 assert((Body || getTarget().getCXXABI().isMicrosoft()) &&
1414 "can't emit a dtor without a body for non-Microsoft ABIs");
1415
John McCallf99a6312010-07-21 05:30:47 +00001416 // Enter the cleanup scopes for virtual bases.
1417 EnterDtorCleanups(Dtor, Dtor_Complete);
1418
Reid Klecknere7de47e2013-07-22 13:51:44 +00001419 if (!isTryBody) {
John McCallf99a6312010-07-21 05:30:47 +00001420 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00001421 /*Delegating=*/false, LoadCXXThis());
John McCallf99a6312010-07-21 05:30:47 +00001422 break;
1423 }
1424 // Fallthrough: act like we're in the base variant.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001425
John McCallf99a6312010-07-21 05:30:47 +00001426 case Dtor_Base:
Reid Klecknere7de47e2013-07-22 13:51:44 +00001427 assert(Body);
1428
John McCallf99a6312010-07-21 05:30:47 +00001429 // Enter the cleanup scopes for fields and non-virtual bases.
1430 EnterDtorCleanups(Dtor, Dtor_Base);
1431
1432 // Initialize the vtable pointers before entering the body.
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001433 if (!CanSkipVTablePointerInitialization(*this, Dtor))
Anders Carlsson9bd7d162011-05-14 23:26:09 +00001434 InitializeVTablePointers(Dtor->getParent());
John McCallf99a6312010-07-21 05:30:47 +00001435
1436 if (isTryBody)
1437 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock());
1438 else if (Body)
1439 EmitStmt(Body);
1440 else {
1441 assert(Dtor->isImplicit() && "bodyless dtor not implicit");
1442 // nothing to do besides what's in the epilogue
1443 }
Fariborz Jahanian0c12ed12011-02-02 23:12:46 +00001444 // -fapple-kext must inline any call to this dtor into
1445 // the caller's body.
Richard Smith9c6890a2012-11-01 22:30:59 +00001446 if (getLangOpts().AppleKext)
Bill Wendling207f0532012-12-20 19:27:06 +00001447 CurFn->addFnAttr(llvm::Attribute::AlwaysInline);
Naomi Musgravee50cb9b2015-08-13 18:35:11 +00001448
John McCallf99a6312010-07-21 05:30:47 +00001449 break;
John McCallb81884d2010-02-19 09:25:03 +00001450 }
1451
John McCallf99a6312010-07-21 05:30:47 +00001452 // Jump out through the epilogue cleanups.
1453 DtorEpilogue.ForceCleanup();
John McCallb81884d2010-02-19 09:25:03 +00001454
1455 // Exit the try if applicable.
1456 if (isTryBody)
John McCallb609d3f2010-07-07 06:56:46 +00001457 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true);
John McCallb81884d2010-02-19 09:25:03 +00001458}
1459
Lang Hamesbf122742013-02-17 07:22:09 +00001460void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) {
1461 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl());
1462 const Stmt *RootS = AssignOp->getBody();
1463 assert(isa<CompoundStmt>(RootS) &&
1464 "Body of an implicit assignment operator should be compound stmt.");
1465 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS);
1466
1467 LexicalScope Scope(*this, RootCS->getSourceRange());
1468
1469 AssignmentMemcpyizer AM(*this, AssignOp, Args);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00001470 for (auto *I : RootCS->body())
Justin Bogner1cd11f12015-05-20 15:53:59 +00001471 AM.emitAssignment(I);
Lang Hamesbf122742013-02-17 07:22:09 +00001472 AM.finish();
1473}
1474
John McCallf99a6312010-07-21 05:30:47 +00001475namespace {
1476 /// Call the operator delete associated with the current destructor.
David Blaikie7e70d682015-08-18 22:40:54 +00001477 struct CallDtorDelete final : EHScopeStack::Cleanup {
John McCallf99a6312010-07-21 05:30:47 +00001478 CallDtorDelete() {}
1479
Craig Topper4f12f102014-03-12 06:41:41 +00001480 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallf99a6312010-07-21 05:30:47 +00001481 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1482 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1483 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1484 CGF.getContext().getTagDeclType(ClassDecl));
1485 }
1486 };
1487
David Blaikie7e70d682015-08-18 22:40:54 +00001488 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001489 llvm::Value *ShouldDeleteCondition;
1490 public:
1491 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001492 : ShouldDeleteCondition(ShouldDeleteCondition) {
Craig Topper8a13c412014-05-21 05:09:00 +00001493 assert(ShouldDeleteCondition != nullptr);
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001494 }
1495
Craig Topper4f12f102014-03-12 06:41:41 +00001496 void Emit(CodeGenFunction &CGF, Flags flags) override {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001497 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete");
1498 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue");
1499 llvm::Value *ShouldCallDelete
1500 = CGF.Builder.CreateIsNull(ShouldDeleteCondition);
1501 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB);
1502
1503 CGF.EmitBlock(callDeleteBB);
1504 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl);
1505 const CXXRecordDecl *ClassDecl = Dtor->getParent();
1506 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(),
1507 CGF.getContext().getTagDeclType(ClassDecl));
1508 CGF.Builder.CreateBr(continueBB);
1509
1510 CGF.EmitBlock(continueBB);
1511 }
1512 };
1513
David Blaikie7e70d682015-08-18 22:40:54 +00001514 class DestroyField final : public EHScopeStack::Cleanup {
John McCall4bd0fb12011-07-12 16:41:08 +00001515 const FieldDecl *field;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001516 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001517 bool useEHCleanupForArray;
John McCallf99a6312010-07-21 05:30:47 +00001518
John McCall4bd0fb12011-07-12 16:41:08 +00001519 public:
1520 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer,
1521 bool useEHCleanupForArray)
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001522 : field(field), destroyer(destroyer),
1523 useEHCleanupForArray(useEHCleanupForArray) {}
John McCallf99a6312010-07-21 05:30:47 +00001524
Craig Topper4f12f102014-03-12 06:41:41 +00001525 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001526 // Find the address of the field.
1527 llvm::Value *thisValue = CGF.LoadCXXThis();
Eli Friedman7f1ff602012-04-16 03:54:45 +00001528 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent());
1529 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy);
1530 LValue LV = CGF.EmitLValueForField(ThisLV, field);
John McCall4bd0fb12011-07-12 16:41:08 +00001531 assert(LV.isSimple());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001532
John McCall4bd0fb12011-07-12 16:41:08 +00001533 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001534 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCallf99a6312010-07-21 05:30:47 +00001535 }
1536 };
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001537
1538 class SanitizeDtor final : public EHScopeStack::Cleanup {
1539 const CXXDestructorDecl *Dtor;
1540
1541 public:
1542 SanitizeDtor(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {}
1543
1544 // Generate function call for handling object poisoning.
1545 // Disables tail call elimination, to prevent the current stack frame
1546 // from disappearing from the stack trace.
1547 void Emit(CodeGenFunction &CGF, Flags flags) override {
1548 const ASTRecordLayout &Layout =
1549 CGF.getContext().getASTRecordLayout(Dtor->getParent());
1550
1551 // Nothing to poison.
1552 if (Layout.getFieldCount() == 0)
1553 return;
1554
1555 // Prevent the current stack frame from disappearing from the stack trace.
1556 CGF.CurFn->addFnAttr("disable-tail-calls", "true");
1557
1558 // Construct pointer to region to begin poisoning, and calculate poison
1559 // size, so that only members declared in this class are poisoned.
1560 ASTContext &Context = CGF.getContext();
1561 unsigned fieldIndex = 0;
1562 int startIndex = -1;
1563 // RecordDecl::field_iterator Field;
1564 for (const FieldDecl *Field : Dtor->getParent()->fields()) {
1565 // Poison field if it is trivial
1566 if (FieldHasTrivialDestructorBody(Context, Field)) {
1567 // Start sanitizing at this field
1568 if (startIndex < 0)
1569 startIndex = fieldIndex;
1570
1571 // Currently on the last field, and it must be poisoned with the
1572 // current block.
1573 if (fieldIndex == Layout.getFieldCount() - 1) {
1574 PoisonBlock(CGF, startIndex, Layout.getFieldCount());
1575 }
1576 } else if (startIndex >= 0) {
1577 // No longer within a block of memory to poison, so poison the block
1578 PoisonBlock(CGF, startIndex, fieldIndex);
1579 // Re-set the start index
1580 startIndex = -1;
1581 }
1582 fieldIndex += 1;
1583 }
1584 }
1585
1586 private:
1587 /// \param layoutStartOffset: index of the ASTRecordLayout field to
1588 /// start poisoning (inclusive)
1589 /// \param layoutEndOffset: index of the ASTRecordLayout field to
1590 /// end poisoning (exclusive)
1591 void PoisonBlock(CodeGenFunction &CGF, unsigned layoutStartOffset,
1592 unsigned layoutEndOffset) {
1593 ASTContext &Context = CGF.getContext();
1594 const ASTRecordLayout &Layout =
1595 Context.getASTRecordLayout(Dtor->getParent());
1596
1597 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get(
1598 CGF.SizeTy,
1599 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset))
1600 .getQuantity());
1601
1602 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP(
1603 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy),
1604 OffsetSizePtr);
1605
1606 CharUnits::QuantityType PoisonSize;
1607 if (layoutEndOffset >= Layout.getFieldCount()) {
1608 PoisonSize = Layout.getNonVirtualSize().getQuantity() -
1609 Context.toCharUnitsFromBits(
1610 Layout.getFieldOffset(layoutStartOffset))
1611 .getQuantity();
1612 } else {
1613 PoisonSize = Context.toCharUnitsFromBits(
1614 Layout.getFieldOffset(layoutEndOffset) -
1615 Layout.getFieldOffset(layoutStartOffset))
1616 .getQuantity();
1617 }
1618
1619 if (PoisonSize == 0)
1620 return;
1621
1622 // Pass in void pointer and size of region as arguments to runtime
1623 // function
1624 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(OffsetPtr, CGF.VoidPtrTy),
1625 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)};
1626
1627 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy};
1628
1629 llvm::FunctionType *FnType =
1630 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false);
1631 llvm::Value *Fn =
1632 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback");
1633 CGF.EmitNounwindRuntimeCall(Fn, Args);
1634 }
1635 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001636}
John McCallf99a6312010-07-21 05:30:47 +00001637
Hans Wennborgdeff7032013-12-18 01:39:59 +00001638/// \brief Emit all code that comes at the end of class's
Anders Carlssonfb404882009-12-24 22:46:43 +00001639/// destructor. This is to call destructors on members and base classes
1640/// in reverse order of their construction.
John McCallf99a6312010-07-21 05:30:47 +00001641void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD,
1642 CXXDtorType DtorType) {
Hans Wennborg853ae942014-05-30 16:59:42 +00001643 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) &&
1644 "Should not emit dtor epilogue for non-exported trivial dtor!");
Anders Carlssonfb404882009-12-24 22:46:43 +00001645
John McCallf99a6312010-07-21 05:30:47 +00001646 // The deleting-destructor phase just needs to call the appropriate
1647 // operator delete that Sema picked up.
John McCall5c60a6f2010-02-18 19:59:28 +00001648 if (DtorType == Dtor_Deleting) {
Justin Bogner1cd11f12015-05-20 15:53:59 +00001649 assert(DD->getOperatorDelete() &&
Hans Wennborgdeff7032013-12-18 01:39:59 +00001650 "operator delete missing - EnterDtorCleanups");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001651 if (CXXStructorImplicitParamValue) {
1652 // If there is an implicit param to the deleting dtor, it's a boolean
1653 // telling whether we should call delete at the end of the dtor.
1654 EHStack.pushCleanup<CallDtorDeleteConditional>(
1655 NormalAndEHCleanup, CXXStructorImplicitParamValue);
1656 } else {
1657 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup);
1658 }
John McCall5c60a6f2010-02-18 19:59:28 +00001659 return;
1660 }
1661
John McCallf99a6312010-07-21 05:30:47 +00001662 const CXXRecordDecl *ClassDecl = DD->getParent();
1663
Richard Smith20104042011-09-18 12:11:43 +00001664 // Unions have no bases and do not call field destructors.
1665 if (ClassDecl->isUnion())
1666 return;
1667
John McCallf99a6312010-07-21 05:30:47 +00001668 // The complete-destructor phase just destructs all the virtual bases.
John McCall5c60a6f2010-02-18 19:59:28 +00001669 if (DtorType == Dtor_Complete) {
John McCallf99a6312010-07-21 05:30:47 +00001670
1671 // We push them in the forward order so that they'll be popped in
1672 // the reverse order.
Aaron Ballman445a9392014-03-13 16:15:17 +00001673 for (const auto &Base : ClassDecl->vbases()) {
John McCall5c60a6f2010-02-18 19:59:28 +00001674 CXXRecordDecl *BaseClassDecl
1675 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl());
Justin Bogner1cd11f12015-05-20 15:53:59 +00001676
John McCall5c60a6f2010-02-18 19:59:28 +00001677 // Ignore trivial destructors.
1678 if (BaseClassDecl->hasTrivialDestructor())
1679 continue;
John McCallf99a6312010-07-21 05:30:47 +00001680
John McCallcda666c2010-07-21 07:22:38 +00001681 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1682 BaseClassDecl,
1683 /*BaseIsVirtual*/ true);
John McCall5c60a6f2010-02-18 19:59:28 +00001684 }
John McCallf99a6312010-07-21 05:30:47 +00001685
John McCall5c60a6f2010-02-18 19:59:28 +00001686 return;
1687 }
1688
1689 assert(DtorType == Dtor_Base);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001690
John McCallf99a6312010-07-21 05:30:47 +00001691 // Destroy non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001692 for (const auto &Base : ClassDecl->bases()) {
John McCallf99a6312010-07-21 05:30:47 +00001693 // Ignore virtual bases.
1694 if (Base.isVirtual())
1695 continue;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001696
John McCallf99a6312010-07-21 05:30:47 +00001697 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001698
John McCallf99a6312010-07-21 05:30:47 +00001699 // Ignore trivial destructors.
1700 if (BaseClassDecl->hasTrivialDestructor())
1701 continue;
John McCall5c60a6f2010-02-18 19:59:28 +00001702
John McCallcda666c2010-07-21 07:22:38 +00001703 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup,
1704 BaseClassDecl,
1705 /*BaseIsVirtual*/ false);
John McCallf99a6312010-07-21 05:30:47 +00001706 }
1707
Naomi Musgrave866af2d2015-09-03 23:02:30 +00001708 // Poison fields such that access after their destructors are
1709 // invoked, and before the base class destructor runs, is invalid.
1710 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
1711 SanOpts.has(SanitizerKind::Memory))
1712 EHStack.pushCleanup<SanitizeDtor>(NormalAndEHCleanup, DD);
1713
John McCallf99a6312010-07-21 05:30:47 +00001714 // Destroy direct fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001715 for (const auto *Field : ClassDecl->fields()) {
1716 QualType type = Field->getType();
John McCall4bd0fb12011-07-12 16:41:08 +00001717 QualType::DestructionKind dtorKind = type.isDestructedType();
1718 if (!dtorKind) continue;
John McCallf99a6312010-07-21 05:30:47 +00001719
Richard Smith921bd202012-02-26 09:11:52 +00001720 // Anonymous union members do not have their destructors called.
1721 const RecordType *RT = type->getAsUnionType();
1722 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue;
1723
John McCall4bd0fb12011-07-12 16:41:08 +00001724 CleanupKind cleanupKind = getCleanupKind(dtorKind);
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001725 EHStack.pushCleanup<DestroyField>(cleanupKind, Field,
John McCall4bd0fb12011-07-12 16:41:08 +00001726 getDestroyer(dtorKind),
1727 cleanupKind & EHCleanup);
Anders Carlssonfb404882009-12-24 22:46:43 +00001728 }
Anders Carlssonfb404882009-12-24 22:46:43 +00001729}
1730
John McCallf677a8e2011-07-13 06:10:41 +00001731/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1732/// constructor for each of several members of an array.
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001733///
John McCallf677a8e2011-07-13 06:10:41 +00001734/// \param ctor the constructor to call for each element
John McCallf677a8e2011-07-13 06:10:41 +00001735/// \param arrayType the type of the array to initialize
1736/// \param arrayBegin an arrayType*
1737/// \param zeroInitialize true if each element should be
1738/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001739void CodeGenFunction::EmitCXXAggrConstructorCall(
1740 const CXXConstructorDecl *ctor, const ConstantArrayType *arrayType,
1741 llvm::Value *arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) {
John McCallf677a8e2011-07-13 06:10:41 +00001742 QualType elementType;
1743 llvm::Value *numElements =
1744 emitArrayLength(arrayType, elementType, arrayBegin);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001745
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001746 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001747}
1748
John McCallf677a8e2011-07-13 06:10:41 +00001749/// EmitCXXAggrConstructorCall - Emit a loop to call a particular
1750/// constructor for each of several members of an array.
1751///
1752/// \param ctor the constructor to call for each element
1753/// \param numElements the number of elements in the array;
John McCall6549b312011-07-13 07:37:11 +00001754/// may be zero
John McCallf677a8e2011-07-13 06:10:41 +00001755/// \param arrayBegin a T*, where T is the type constructed by ctor
1756/// \param zeroInitialize true if each element should be
1757/// zero-initialized before it is constructed
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001758void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor,
1759 llvm::Value *numElements,
1760 llvm::Value *arrayBegin,
1761 const CXXConstructExpr *E,
1762 bool zeroInitialize) {
John McCall6549b312011-07-13 07:37:11 +00001763
1764 // It's legal for numElements to be zero. This can happen both
1765 // dynamically, because x can be zero in 'new A[x]', and statically,
1766 // because of GCC extensions that permit zero-length arrays. There
1767 // are probably legitimate places where we could assume that this
1768 // doesn't happen, but it's not clear that it's worth it.
Craig Topper8a13c412014-05-21 05:09:00 +00001769 llvm::BranchInst *zeroCheckBranch = nullptr;
John McCall6549b312011-07-13 07:37:11 +00001770
1771 // Optimize for a constant count.
1772 llvm::ConstantInt *constantCount
1773 = dyn_cast<llvm::ConstantInt>(numElements);
1774 if (constantCount) {
1775 // Just skip out if the constant count is zero.
1776 if (constantCount->isZero()) return;
1777
1778 // Otherwise, emit the check.
1779 } else {
1780 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop");
1781 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty");
1782 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB);
1783 EmitBlock(loopBB);
1784 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00001785
John McCallf677a8e2011-07-13 06:10:41 +00001786 // Find the end of the array.
1787 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements,
1788 "arrayctor.end");
Anders Carlsson27da15b2010-01-01 20:29:01 +00001789
John McCallf677a8e2011-07-13 06:10:41 +00001790 // Enter the loop, setting up a phi for the current location to initialize.
1791 llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1792 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop");
1793 EmitBlock(loopBB);
1794 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2,
1795 "arrayctor.cur");
1796 cur->addIncoming(arrayBegin, entryBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001797
Anders Carlsson27da15b2010-01-01 20:29:01 +00001798 // Inside the loop body, emit the constructor call on the array element.
John McCallf677a8e2011-07-13 06:10:41 +00001799
1800 QualType type = getContext().getTypeDeclType(ctor->getParent());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001801
Douglas Gregor05fc5be2010-07-21 01:10:17 +00001802 // Zero initialize the storage, if requested.
John McCallf677a8e2011-07-13 06:10:41 +00001803 if (zeroInitialize)
1804 EmitNullInitialization(cur, type);
Justin Bogner1cd11f12015-05-20 15:53:59 +00001805
1806 // C++ [class.temporary]p4:
Anders Carlsson27da15b2010-01-01 20:29:01 +00001807 // There are two contexts in which temporaries are destroyed at a different
1808 // point than the end of the full-expression. The first context is when a
Justin Bogner1cd11f12015-05-20 15:53:59 +00001809 // default constructor is called to initialize an element of an array.
1810 // If the constructor has one or more default arguments, the destruction of
1811 // every temporary created in a default argument expression is sequenced
Anders Carlsson27da15b2010-01-01 20:29:01 +00001812 // before the construction of the next array element, if any.
Justin Bogner1cd11f12015-05-20 15:53:59 +00001813
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001814 {
John McCallbd309292010-07-06 01:34:17 +00001815 RunCleanupsScope Scope(*this);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001816
John McCallf677a8e2011-07-13 06:10:41 +00001817 // Evaluate the constructor and its arguments in a regular
1818 // partial-destroy cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001819 if (getLangOpts().Exceptions &&
John McCallf677a8e2011-07-13 06:10:41 +00001820 !ctor->getParent()->hasTrivialDestructor()) {
1821 Destroyer *destroyer = destroyCXXObject;
1822 pushRegularPartialArrayCleanup(arrayBegin, cur, type, *destroyer);
1823 }
1824
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001825 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false,
1826 /*Delegating=*/false, cur, E);
Anders Carlssonb9fd57f2010-03-30 03:14:41 +00001827 }
Anders Carlsson27da15b2010-01-01 20:29:01 +00001828
John McCallf677a8e2011-07-13 06:10:41 +00001829 // Go to the next element.
1830 llvm::Value *next =
1831 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1),
1832 "arrayctor.next");
1833 cur->addIncoming(next, Builder.GetInsertBlock());
Anders Carlsson27da15b2010-01-01 20:29:01 +00001834
John McCallf677a8e2011-07-13 06:10:41 +00001835 // Check whether that's the end of the loop.
1836 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done");
1837 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont");
1838 Builder.CreateCondBr(done, contBB, loopBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001839
John McCall6549b312011-07-13 07:37:11 +00001840 // Patch the earlier check to skip over the loop.
1841 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB);
1842
John McCallf677a8e2011-07-13 06:10:41 +00001843 EmitBlock(contBB);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001844}
1845
John McCall82fe67b2011-07-09 01:37:26 +00001846void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF,
1847 llvm::Value *addr,
1848 QualType type) {
1849 const RecordType *rtype = type->castAs<RecordType>();
1850 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl());
1851 const CXXDestructorDecl *dtor = record->getDestructor();
1852 assert(!dtor->isTrivial());
1853 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false,
Douglas Gregor61535002013-01-31 05:50:40 +00001854 /*Delegating=*/false, addr);
John McCall82fe67b2011-07-09 01:37:26 +00001855}
1856
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001857void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D,
1858 CXXCtorType Type,
1859 bool ForVirtualBase,
1860 bool Delegating, llvm::Value *This,
1861 const CXXConstructExpr *E) {
Richard Smith419bd092015-04-29 19:26:57 +00001862 // C++11 [class.mfct.non-static]p2:
1863 // If a non-static member function of a class X is called for an object that
1864 // is not of type X, or of a type derived from X, the behavior is undefined.
1865 // FIXME: Provide a source location here.
1866 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), This,
Steven Wu5528da72015-08-28 07:14:10 +00001867 getContext().getRecordType(D->getParent()));
John McCallca972cd2010-02-06 00:25:16 +00001868
Richard Smith419bd092015-04-29 19:26:57 +00001869 if (D->isTrivial() && D->isDefaultConstructor()) {
1870 assert(E->getNumArgs() == 0 && "trivial default ctor with args");
1871 return;
1872 }
1873
1874 // If this is a trivial constructor, just emit what's needed. If this is a
1875 // union copy constructor, we must emit a memcpy, because the AST does not
1876 // model that copy.
1877 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001878 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
John McCallca972cd2010-02-06 00:25:16 +00001879
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001880 const Expr *Arg = E->getArg(0);
David Majnemerfd1e7392015-02-03 23:04:06 +00001881 QualType SrcTy = Arg->getType();
Alexey Samsonov70b9c012014-08-21 20:26:47 +00001882 llvm::Value *Src = EmitLValue(Arg).getAddress();
Steven Wu5528da72015-08-28 07:14:10 +00001883 QualType DestTy = getContext().getTypeDeclType(D->getParent());
David Majnemerfd1e7392015-02-03 23:04:06 +00001884 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001885 return;
1886 }
1887
Reid Kleckner89077a12013-12-17 19:46:40 +00001888 CallArgList Args;
1889
1890 // Push the this ptr.
1891 Args.add(RValue::get(This), D->getThisType(getContext()));
1892
1893 // Add the rest of the user-supplied arguments.
1894 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
David Blaikief05779e2015-07-21 18:37:18 +00001895 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor());
Reid Kleckner89077a12013-12-17 19:46:40 +00001896
1897 // Insert any ABI-specific implicit constructor arguments.
1898 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs(
1899 *this, D, Type, ForVirtualBase, Delegating, Args);
1900
1901 // Emit the call.
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001902 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, getFromCtorType(Type));
Reid Kleckner89077a12013-12-17 19:46:40 +00001903 const CGFunctionInfo &Info =
Reid Kleckner314ef7b2014-02-01 00:04:45 +00001904 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs);
Reid Kleckner89077a12013-12-17 19:46:40 +00001905 EmitCall(Info, Callee, ReturnValueSlot(), Args, D);
Anders Carlsson27da15b2010-01-01 20:29:01 +00001906}
1907
John McCallf8ff7b92010-02-23 00:48:20 +00001908void
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001909CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D,
1910 llvm::Value *This, llvm::Value *Src,
Alexey Samsonov525bf652014-08-25 21:58:56 +00001911 const CXXConstructExpr *E) {
Richard Smith419bd092015-04-29 19:26:57 +00001912 if (isMemcpyEquivalentSpecialMember(D)) {
Alexey Samsonov96fd0a42014-08-26 20:18:26 +00001913 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor");
Sebastian Redl22653ba2011-08-30 19:58:05 +00001914 assert(D->isCopyOrMoveConstructor() &&
1915 "trivial 1-arg ctor not a copy/move ctor");
David Majnemerfd1e7392015-02-03 23:04:06 +00001916 EmitAggregateCopyCtor(This, Src,
1917 getContext().getTypeDeclType(D->getParent()),
Benjamin Kramerf48ee442015-07-18 14:35:53 +00001918 (*E->arg_begin())->getType());
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001919 return;
1920 }
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001921 llvm::Value *Callee = CGM.getAddrOfCXXStructor(D, StructorType::Complete);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001922 assert(D->isInstance() &&
1923 "Trying to emit a member call expr on a static method!");
Justin Bogner1cd11f12015-05-20 15:53:59 +00001924
Reid Kleckner739756c2013-12-04 19:23:12 +00001925 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>();
Justin Bogner1cd11f12015-05-20 15:53:59 +00001926
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001927 CallArgList Args;
Justin Bogner1cd11f12015-05-20 15:53:59 +00001928
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001929 // Push the this ptr.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001930 Args.add(RValue::get(This), D->getThisType(getContext()));
Justin Bogner1cd11f12015-05-20 15:53:59 +00001931
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001932 // Push the src ptr.
Alp Toker9cacbab2014-01-20 20:26:09 +00001933 QualType QT = *(FPT->param_type_begin());
Chris Lattner2192fe52011-07-18 04:24:23 +00001934 llvm::Type *t = CGM.getTypes().ConvertType(QT);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001935 Src = Builder.CreateBitCast(Src, t);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001936 Args.add(RValue::get(Src), QT);
Reid Kleckner739756c2013-12-04 19:23:12 +00001937
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001938 // Skip over first argument (Src).
David Blaikief05779e2015-07-21 18:37:18 +00001939 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(),
Alexey Samsonov8e1162c2014-09-08 17:22:45 +00001940 /*ParamsToSkip*/ 1);
Reid Kleckner739756c2013-12-04 19:23:12 +00001941
John McCall8dda7b22012-07-07 06:41:13 +00001942 EmitCall(CGM.getTypes().arrangeCXXMethodCall(Args, FPT, RequiredArgs::All),
1943 Callee, ReturnValueSlot(), Args, D);
Fariborz Jahaniane988bda2010-11-13 21:53:34 +00001944}
1945
1946void
John McCallf8ff7b92010-02-23 00:48:20 +00001947CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor,
1948 CXXCtorType CtorType,
Nick Lewycky2d84e842013-10-02 02:29:49 +00001949 const FunctionArgList &Args,
1950 SourceLocation Loc) {
John McCallf8ff7b92010-02-23 00:48:20 +00001951 CallArgList DelegateArgs;
1952
1953 FunctionArgList::const_iterator I = Args.begin(), E = Args.end();
1954 assert(I != E && "no parameters to constructor");
1955
1956 // this
Eli Friedman43dca6a2011-05-02 17:57:46 +00001957 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType());
John McCallf8ff7b92010-02-23 00:48:20 +00001958 ++I;
1959
1960 // vtt
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +00001961 if (llvm::Value *VTT = GetVTTParameter(GlobalDecl(Ctor, CtorType),
Douglas Gregor61535002013-01-31 05:50:40 +00001962 /*ForVirtualBase=*/false,
1963 /*Delegating=*/true)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001964 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001965 DelegateArgs.add(RValue::get(VTT), VoidPP);
John McCallf8ff7b92010-02-23 00:48:20 +00001966
Peter Collingbourne66f82e62013-06-28 20:45:28 +00001967 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) {
John McCallf8ff7b92010-02-23 00:48:20 +00001968 assert(I != E && "cannot skip vtt parameter, already done with args");
John McCalla738c252011-03-09 04:27:21 +00001969 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type");
John McCallf8ff7b92010-02-23 00:48:20 +00001970 ++I;
1971 }
1972 }
1973
1974 // Explicit arguments.
1975 for (; I != E; ++I) {
John McCall32ea9692011-03-11 20:59:21 +00001976 const VarDecl *param = *I;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001977 // FIXME: per-argument source location
1978 EmitDelegateCallArg(DelegateArgs, param, Loc);
John McCallf8ff7b92010-02-23 00:48:20 +00001979 }
1980
Rafael Espindola1ac0ec82014-09-11 15:42:06 +00001981 llvm::Value *Callee =
1982 CGM.getAddrOfCXXStructor(Ctor, getFromCtorType(CtorType));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +00001983 EmitCall(CGM.getTypes()
1984 .arrangeCXXStructorDeclaration(Ctor, getFromCtorType(CtorType)),
Manman Ren01754612013-03-20 16:59:38 +00001985 Callee, ReturnValueSlot(), DelegateArgs, Ctor);
John McCallf8ff7b92010-02-23 00:48:20 +00001986}
1987
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001988namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00001989 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001990 const CXXDestructorDecl *Dtor;
1991 llvm::Value *Addr;
1992 CXXDtorType Type;
1993
1994 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr,
1995 CXXDtorType Type)
1996 : Dtor(D), Addr(Addr), Type(Type) {}
1997
Craig Topper4f12f102014-03-12 06:41:41 +00001998 void Emit(CodeGenFunction &CGF, Flags flags) override {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00001999 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false,
Douglas Gregor61535002013-01-31 05:50:40 +00002000 /*Delegating=*/true, Addr);
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002001 }
2002 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002003}
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002004
Alexis Hunt61bc1732011-05-01 07:04:31 +00002005void
2006CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor,
2007 const FunctionArgList &Args) {
2008 assert(Ctor->isDelegatingConstructor());
2009
2010 llvm::Value *ThisPtr = LoadCXXThis();
2011
Eli Friedmanc1d85b92011-12-03 00:54:26 +00002012 QualType Ty = getContext().getTagDeclType(Ctor->getParent());
Eli Friedman38cd36d2011-12-03 02:13:40 +00002013 CharUnits Alignment = getContext().getTypeAlignInChars(Ty);
John McCall31168b02011-06-15 23:02:42 +00002014 AggValueSlot AggSlot =
Eli Friedmanc1d85b92011-12-03 00:54:26 +00002015 AggValueSlot::forAddr(ThisPtr, Alignment, Qualifiers(),
John McCall8d6fc952011-08-25 20:40:09 +00002016 AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00002017 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002018 AggValueSlot::IsNotAliased);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002019
2020 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot);
Alexis Hunt61bc1732011-05-01 07:04:31 +00002021
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002022 const CXXRecordDecl *ClassDecl = Ctor->getParent();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002023 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) {
Alexis Hunt9d47faf2011-05-03 23:05:34 +00002024 CXXDtorType Type =
2025 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base;
2026
2027 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup,
2028 ClassDecl->getDestructor(),
2029 ThisPtr, Type);
2030 }
2031}
Alexis Hunt61bc1732011-05-01 07:04:31 +00002032
Anders Carlsson27da15b2010-01-01 20:29:01 +00002033void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD,
2034 CXXDtorType Type,
Anders Carlssonf8a71f02010-05-02 23:29:11 +00002035 bool ForVirtualBase,
Douglas Gregor61535002013-01-31 05:50:40 +00002036 bool Delegating,
Anders Carlsson27da15b2010-01-01 20:29:01 +00002037 llvm::Value *This) {
Reid Kleckner6fe771a2013-12-13 00:53:54 +00002038 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase,
2039 Delegating, This);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002040}
2041
John McCall53cad2e2010-07-21 01:41:18 +00002042namespace {
David Blaikie7e70d682015-08-18 22:40:54 +00002043 struct CallLocalDtor final : EHScopeStack::Cleanup {
John McCall53cad2e2010-07-21 01:41:18 +00002044 const CXXDestructorDecl *Dtor;
2045 llvm::Value *Addr;
2046
2047 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr)
2048 : Dtor(D), Addr(Addr) {}
2049
Craig Topper4f12f102014-03-12 06:41:41 +00002050 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall53cad2e2010-07-21 01:41:18 +00002051 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
Douglas Gregor61535002013-01-31 05:50:40 +00002052 /*ForVirtualBase=*/false,
2053 /*Delegating=*/false, Addr);
John McCall53cad2e2010-07-21 01:41:18 +00002054 }
2055 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00002056}
John McCall53cad2e2010-07-21 01:41:18 +00002057
John McCall8680f872010-07-21 06:29:51 +00002058void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D,
2059 llvm::Value *Addr) {
John McCallcda666c2010-07-21 07:22:38 +00002060 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr);
John McCall8680f872010-07-21 06:29:51 +00002061}
2062
John McCallbd309292010-07-06 01:34:17 +00002063void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) {
2064 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl();
2065 if (!ClassDecl) return;
2066 if (ClassDecl->hasTrivialDestructor()) return;
2067
2068 const CXXDestructorDecl *D = ClassDecl->getDestructor();
John McCalla85af562011-04-28 02:15:35 +00002069 assert(D && D->isUsed() && "destructor not marked as used!");
John McCall8680f872010-07-21 06:29:51 +00002070 PushDestructorCleanup(D, Addr);
John McCallbd309292010-07-06 01:34:17 +00002071}
2072
Steven Wu5528da72015-08-28 07:14:10 +00002073void
2074CodeGenFunction::InitializeVTablePointer(BaseSubobject Base,
2075 const CXXRecordDecl *NearestVBase,
2076 CharUnits OffsetFromNearestVBase,
2077 const CXXRecordDecl *VTableClass) {
2078 const CXXRecordDecl *RD = Base.getBase();
2079
2080 // Don't initialize the vtable pointer if the class is marked with the
2081 // 'novtable' attribute.
2082 if ((RD == VTableClass || RD == NearestVBase) &&
2083 VTableClass->hasAttr<MSNoVTableAttr>())
2084 return;
2085
Anders Carlssone87fae92010-03-28 19:40:00 +00002086 // Compute the address point.
Steven Wu5528da72015-08-28 07:14:10 +00002087 bool NeedsVirtualOffset;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002088 llvm::Value *VTableAddressPoint =
2089 CGM.getCXXABI().getVTableAddressPointInStructor(
Steven Wu5528da72015-08-28 07:14:10 +00002090 *this, VTableClass, Base, NearestVBase, NeedsVirtualOffset);
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002091 if (!VTableAddressPoint)
2092 return;
Anders Carlssone87fae92010-03-28 19:40:00 +00002093
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002094 // Compute where to store the address point.
Craig Topper8a13c412014-05-21 05:09:00 +00002095 llvm::Value *VirtualOffset = nullptr;
Ken Dyckcfc332c2011-03-23 00:45:26 +00002096 CharUnits NonVirtualOffset = CharUnits::Zero();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002097
Steven Wu5528da72015-08-28 07:14:10 +00002098 if (NeedsVirtualOffset) {
Anders Carlsson91baecf2010-04-20 18:05:10 +00002099 // We need to use the virtual base offset offset because the virtual base
2100 // might have a different offset in the most derived class.
Steven Wu5528da72015-08-28 07:14:10 +00002101 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset(*this,
2102 LoadCXXThis(),
2103 VTableClass,
2104 NearestVBase);
2105 NonVirtualOffset = OffsetFromNearestVBase;
Anders Carlsson91baecf2010-04-20 18:05:10 +00002106 } else {
Anders Carlssonc58fb552010-05-03 00:29:58 +00002107 // We can just use the base offset in the complete class.
Steven Wu5528da72015-08-28 07:14:10 +00002108 NonVirtualOffset = Base.getBaseOffset();
Anders Carlsson91baecf2010-04-20 18:05:10 +00002109 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002110
Anders Carlssonc58fb552010-05-03 00:29:58 +00002111 // Apply the offsets.
2112 llvm::Value *VTableField = LoadCXXThis();
Justin Bogner1cd11f12015-05-20 15:53:59 +00002113
Ken Dyckcfc332c2011-03-23 00:45:26 +00002114 if (!NonVirtualOffset.isZero() || VirtualOffset)
Justin Bogner1cd11f12015-05-20 15:53:59 +00002115 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField,
Anders Carlssonc58fb552010-05-03 00:29:58 +00002116 NonVirtualOffset,
2117 VirtualOffset);
Anders Carlsson6a0227d2010-04-20 16:22:16 +00002118
Reid Kleckner8d585132014-12-03 21:00:21 +00002119 // Finally, store the address point. Use the same LLVM types as the field to
2120 // support optimization.
2121 llvm::Type *VTablePtrTy =
2122 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true)
2123 ->getPointerTo()
2124 ->getPointerTo();
2125 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo());
2126 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy);
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002127 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField);
2128 CGM.DecorateInstruction(Store, CGM.getTBAAInfoForVTablePtr());
Anders Carlssone87fae92010-03-28 19:40:00 +00002129}
2130
Steven Wu5528da72015-08-28 07:14:10 +00002131void
2132CodeGenFunction::InitializeVTablePointers(BaseSubobject Base,
2133 const CXXRecordDecl *NearestVBase,
2134 CharUnits OffsetFromNearestVBase,
2135 bool BaseIsNonVirtualPrimaryBase,
2136 const CXXRecordDecl *VTableClass,
2137 VisitedVirtualBasesSetTy& VBases) {
Anders Carlssond5895932010-03-28 21:07:49 +00002138 // If this base is a non-virtual primary base the address point has already
2139 // been set.
2140 if (!BaseIsNonVirtualPrimaryBase) {
2141 // Initialize the vtable pointer for this base.
Steven Wu5528da72015-08-28 07:14:10 +00002142 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase,
2143 VTableClass);
Anders Carlssond5895932010-03-28 21:07:49 +00002144 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002145
Anders Carlssond5895932010-03-28 21:07:49 +00002146 const CXXRecordDecl *RD = Base.getBase();
2147
2148 // Traverse bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002149 for (const auto &I : RD->bases()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002150 CXXRecordDecl *BaseDecl
Aaron Ballman574705e2014-03-13 15:41:46 +00002151 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssond5895932010-03-28 21:07:49 +00002152
2153 // Ignore classes without a vtable.
2154 if (!BaseDecl->isDynamicClass())
2155 continue;
2156
Ken Dyck3fb4c892011-03-23 01:04:18 +00002157 CharUnits BaseOffset;
2158 CharUnits BaseOffsetFromNearestVBase;
Anders Carlsson948d3f42010-03-29 01:16:41 +00002159 bool BaseDeclIsNonVirtualPrimaryBase;
Anders Carlssond5895932010-03-28 21:07:49 +00002160
Aaron Ballman574705e2014-03-13 15:41:46 +00002161 if (I.isVirtual()) {
Anders Carlssond5895932010-03-28 21:07:49 +00002162 // Check if we've visited this virtual base before.
David Blaikie82e95a32014-11-19 07:49:47 +00002163 if (!VBases.insert(BaseDecl).second)
Anders Carlssond5895932010-03-28 21:07:49 +00002164 continue;
2165
Justin Bogner1cd11f12015-05-20 15:53:59 +00002166 const ASTRecordLayout &Layout =
Anders Carlssond5895932010-03-28 21:07:49 +00002167 getContext().getASTRecordLayout(VTableClass);
2168
Ken Dyck3fb4c892011-03-23 01:04:18 +00002169 BaseOffset = Layout.getVBaseClassOffset(BaseDecl);
2170 BaseOffsetFromNearestVBase = CharUnits::Zero();
Anders Carlsson948d3f42010-03-29 01:16:41 +00002171 BaseDeclIsNonVirtualPrimaryBase = false;
Anders Carlssond5895932010-03-28 21:07:49 +00002172 } else {
2173 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD);
2174
Ken Dyck16ffcac2011-03-24 01:21:01 +00002175 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl);
Justin Bogner1cd11f12015-05-20 15:53:59 +00002176 BaseOffsetFromNearestVBase =
Ken Dyck3fb4c892011-03-23 01:04:18 +00002177 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson948d3f42010-03-29 01:16:41 +00002178 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl;
Anders Carlssond5895932010-03-28 21:07:49 +00002179 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002180
Steven Wu5528da72015-08-28 07:14:10 +00002181 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset),
2182 I.isVirtual() ? BaseDecl : NearestVBase,
2183 BaseOffsetFromNearestVBase,
2184 BaseDeclIsNonVirtualPrimaryBase,
2185 VTableClass, VBases);
Anders Carlssond5895932010-03-28 21:07:49 +00002186 }
2187}
2188
2189void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) {
2190 // Ignore classes without a vtable.
Anders Carlsson1f9348c2010-03-26 04:39:42 +00002191 if (!RD->isDynamicClass())
Anders Carlsson27da15b2010-01-01 20:29:01 +00002192 return;
2193
Anders Carlssond5895932010-03-28 21:07:49 +00002194 // Initialize the vtable pointers for this class and all of its bases.
Steven Wu5528da72015-08-28 07:14:10 +00002195 VisitedVirtualBasesSetTy VBases;
2196 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()),
2197 /*NearestVBase=*/nullptr,
2198 /*OffsetFromNearestVBase=*/CharUnits::Zero(),
2199 /*BaseIsNonVirtualPrimaryBase=*/false, RD, VBases);
Timur Iskhodzhanovb6487322013-10-09 18:16:58 +00002200
2201 if (RD->getNumVBases())
2202 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD);
Anders Carlsson27da15b2010-01-01 20:29:01 +00002203}
Dan Gohman8fc50c22010-10-26 18:44:08 +00002204
2205llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This,
Chris Lattner2192fe52011-07-18 04:24:23 +00002206 llvm::Type *Ty) {
Dan Gohman8fc50c22010-10-26 18:44:08 +00002207 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo());
Kostya Serebryany141e46f2012-03-26 17:03:51 +00002208 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable");
2209 CGM.DecorateInstruction(VTable, CGM.getTBAAInfoForVTablePtr());
2210 return VTable;
Dan Gohman8fc50c22010-10-26 18:44:08 +00002211}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002212
Peter Collingbourned2926c92015-03-14 02:42:25 +00002213// If a class has a single non-virtual base and does not introduce or override
2214// virtual member functions or fields, it will have the same layout as its base.
2215// This function returns the least derived such class.
2216//
2217// Casting an instance of a base class to such a derived class is technically
2218// undefined behavior, but it is a relatively common hack for introducing member
2219// functions on class instances with specific properties (e.g. llvm::Operator)
2220// that works under most compilers and should not have security implications, so
2221// we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict.
2222static const CXXRecordDecl *
2223LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) {
2224 if (!RD->field_empty())
2225 return RD;
2226
2227 if (RD->getNumVBases() != 0)
2228 return RD;
2229
2230 if (RD->getNumBases() != 1)
2231 return RD;
2232
2233 for (const CXXMethodDecl *MD : RD->methods()) {
2234 if (MD->isVirtual()) {
2235 // Virtual member functions are only ok if they are implicit destructors
2236 // because the implicit destructor will have the same semantics as the
2237 // base class's destructor if no fields are added.
2238 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit())
2239 continue;
2240 return RD;
2241 }
2242 }
2243
2244 return LeastDerivedClassWithSameLayout(
2245 RD->bases_begin()->getType()->getAsCXXRecordDecl());
2246}
2247
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002248void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXMethodDecl *MD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002249 llvm::Value *VTable,
2250 CFITypeCheckKind TCK,
2251 SourceLocation Loc) {
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002252 const CXXRecordDecl *ClassDecl = MD->getParent();
2253 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2254 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2255
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002256 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourne1a7488a2015-04-02 00:23:30 +00002257}
2258
Peter Collingbourned2926c92015-03-14 02:42:25 +00002259void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T,
2260 llvm::Value *Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002261 bool MayBeNull,
2262 CFITypeCheckKind TCK,
2263 SourceLocation Loc) {
Peter Collingbourned2926c92015-03-14 02:42:25 +00002264 if (!getLangOpts().CPlusPlus)
2265 return;
2266
2267 auto *ClassTy = T->getAs<RecordType>();
2268 if (!ClassTy)
2269 return;
2270
2271 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl());
2272
2273 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass())
2274 return;
2275
Peter Collingbourned2926c92015-03-14 02:42:25 +00002276 if (!SanOpts.has(SanitizerKind::CFICastStrict))
2277 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl);
2278
2279 llvm::BasicBlock *ContBlock = 0;
2280
2281 if (MayBeNull) {
2282 llvm::Value *DerivedNotNull =
2283 Builder.CreateIsNotNull(Derived, "cast.nonnull");
2284
2285 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check");
2286 ContBlock = createBasicBlock("cast.cont");
2287
2288 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock);
2289
2290 EmitBlock(CheckBlock);
2291 }
2292
2293 llvm::Value *VTable = GetVTablePtr(Derived, Int8PtrTy);
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002294 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc);
Peter Collingbourned2926c92015-03-14 02:42:25 +00002295
2296 if (MayBeNull) {
2297 Builder.CreateBr(ContBlock);
2298 EmitBlock(ContBlock);
2299 }
2300}
2301
2302void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002303 llvm::Value *VTable,
2304 CFITypeCheckKind TCK,
2305 SourceLocation Loc) {
Peter Collingbournee5706442015-07-09 19:56:14 +00002306 if (CGM.IsCFIBlacklistedRecord(RD))
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002307 return;
2308
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002309 SanitizerScope SanScope(this);
2310
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002311 std::string OutName;
2312 llvm::raw_string_ostream Out(OutName);
2313 CGM.getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
2314
2315 llvm::Value *BitSetName = llvm::MetadataAsValue::get(
2316 getLLVMContext(), llvm::MDString::get(getLLVMContext(), Out.str()));
2317
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002318 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy);
2319 llvm::Value *BitSetTest =
2320 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::bitset_test),
2321 {CastedVTable, BitSetName});
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002322
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002323 SanitizerMask M;
2324 switch (TCK) {
2325 case CFITCK_VCall:
2326 M = SanitizerKind::CFIVCall;
2327 break;
2328 case CFITCK_NVCall:
2329 M = SanitizerKind::CFINVCall;
2330 break;
2331 case CFITCK_DerivedCast:
2332 M = SanitizerKind::CFIDerivedCast;
2333 break;
2334 case CFITCK_UnrelatedCast:
2335 M = SanitizerKind::CFIUnrelatedCast;
2336 break;
2337 }
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002338
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002339 llvm::Constant *StaticData[] = {
2340 EmitCheckSourceLocation(Loc),
2341 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)),
2342 llvm::ConstantInt::get(Int8Ty, TCK),
2343 };
2344 EmitCheck(std::make_pair(BitSetTest, M), "cfi_bad_type", StaticData,
2345 CastedVTable);
Peter Collingbournea4ccff32015-02-20 20:30:56 +00002346}
Anders Carlssonc36783e2011-05-08 20:32:23 +00002347
2348// FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do
2349// quite what we want.
2350static const Expr *skipNoOpCastsAndParens(const Expr *E) {
2351 while (true) {
2352 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
2353 E = PE->getSubExpr();
2354 continue;
2355 }
2356
2357 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
2358 if (CE->getCastKind() == CK_NoOp) {
2359 E = CE->getSubExpr();
2360 continue;
2361 }
2362 }
2363 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
2364 if (UO->getOpcode() == UO_Extension) {
2365 E = UO->getSubExpr();
2366 continue;
2367 }
2368 }
2369 return E;
2370 }
2371}
2372
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002373bool
2374CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base,
2375 const CXXMethodDecl *MD) {
2376 // When building with -fapple-kext, all calls must go through the vtable since
2377 // the kernel linker can do runtime patching of vtables.
2378 if (getLangOpts().AppleKext)
2379 return false;
2380
Anders Carlssonc36783e2011-05-08 20:32:23 +00002381 // If the most derived class is marked final, we know that no subclass can
2382 // override this member function and so we can devirtualize it. For example:
2383 //
2384 // struct A { virtual void f(); }
2385 // struct B final : A { };
2386 //
2387 // void f(B *b) {
2388 // b->f();
2389 // }
2390 //
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002391 const CXXRecordDecl *MostDerivedClassDecl = Base->getBestDynamicClassType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002392 if (MostDerivedClassDecl->hasAttr<FinalAttr>())
2393 return true;
2394
2395 // If the member function is marked 'final', we know that it can't be
2396 // overridden and can therefore devirtualize it.
2397 if (MD->hasAttr<FinalAttr>())
2398 return true;
2399
2400 // Similarly, if the class itself is marked 'final' it can't be overridden
2401 // and we can therefore devirtualize the member function call.
2402 if (MD->getParent()->hasAttr<FinalAttr>())
2403 return true;
2404
2405 Base = skipNoOpCastsAndParens(Base);
2406 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
2407 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) {
2408 // This is a record decl. We know the type and can devirtualize it.
2409 return VD->getType()->isRecordType();
2410 }
Justin Bogner1cd11f12015-05-20 15:53:59 +00002411
Anders Carlssonc36783e2011-05-08 20:32:23 +00002412 return false;
2413 }
Benjamin Kramer7463ed72013-08-25 22:46:27 +00002414
2415 // We can devirtualize calls on an object accessed by a class member access
2416 // expression, since by C++11 [basic.life]p6 we know that it can't refer to
2417 // a derived class object constructed in the same location.
2418 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base))
2419 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl()))
2420 return VD->getType()->isRecordType();
2421
Anders Carlssonc36783e2011-05-08 20:32:23 +00002422 // We can always devirtualize calls on temporary object expressions.
2423 if (isa<CXXConstructExpr>(Base))
2424 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002425
Anders Carlssonc36783e2011-05-08 20:32:23 +00002426 // And calls on bound temporaries.
2427 if (isa<CXXBindTemporaryExpr>(Base))
2428 return true;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002429
Anders Carlssonc36783e2011-05-08 20:32:23 +00002430 // Check if this is a call expr that returns a record type.
2431 if (const CallExpr *CE = dyn_cast<CallExpr>(Base))
David Majnemerced8bdf2015-02-25 17:36:15 +00002432 return CE->getCallReturnType(getContext())->isRecordType();
Anders Carlssonc36783e2011-05-08 20:32:23 +00002433
2434 // We can't devirtualize the call.
2435 return false;
2436}
2437
Faisal Vali571df122013-09-29 08:45:24 +00002438void CodeGenFunction::EmitForwardingCallToLambda(
2439 const CXXMethodDecl *callOperator,
2440 CallArgList &callArgs) {
Eli Friedman5b446882012-02-16 03:47:28 +00002441 // Get the address of the call operator.
John McCall8dda7b22012-07-07 06:41:13 +00002442 const CGFunctionInfo &calleeFnInfo =
2443 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator);
2444 llvm::Value *callee =
2445 CGM.GetAddrOfFunction(GlobalDecl(callOperator),
2446 CGM.getTypes().GetFunctionType(calleeFnInfo));
Eli Friedman5b446882012-02-16 03:47:28 +00002447
John McCall8dda7b22012-07-07 06:41:13 +00002448 // Prepare the return slot.
2449 const FunctionProtoType *FPT =
2450 callOperator->getType()->castAs<FunctionProtoType>();
Alp Toker314cc812014-01-25 16:55:45 +00002451 QualType resultType = FPT->getReturnType();
John McCall8dda7b22012-07-07 06:41:13 +00002452 ReturnValueSlot returnSlot;
2453 if (!resultType->isVoidType() &&
2454 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect &&
John McCall47fb9502013-03-07 21:37:08 +00002455 !hasScalarEvaluationKind(calleeFnInfo.getReturnType()))
John McCall8dda7b22012-07-07 06:41:13 +00002456 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified());
2457
2458 // We don't need to separately arrange the call arguments because
2459 // the call can't be variadic anyway --- it's impossible to forward
2460 // variadic arguments.
Justin Bogner1cd11f12015-05-20 15:53:59 +00002461
Eli Friedman5b446882012-02-16 03:47:28 +00002462 // Now emit our call.
John McCall8dda7b22012-07-07 06:41:13 +00002463 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot,
2464 callArgs, callOperator);
Eli Friedman5b446882012-02-16 03:47:28 +00002465
John McCall8dda7b22012-07-07 06:41:13 +00002466 // If necessary, copy the returned value into the slot.
2467 if (!resultType->isVoidType() && returnSlot.isNull())
2468 EmitReturnOfRValue(RV, resultType);
Eli Friedmanf5f4d2f2012-12-13 23:37:17 +00002469 else
2470 EmitBranchThroughCleanup(ReturnBlock);
Eli Friedman5b446882012-02-16 03:47:28 +00002471}
2472
Eli Friedman2495ab02012-02-25 02:48:22 +00002473void CodeGenFunction::EmitLambdaBlockInvokeBody() {
2474 const BlockDecl *BD = BlockInfo->getBlockDecl();
2475 const VarDecl *variable = BD->capture_begin()->getVariable();
2476 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl();
2477
2478 // Start building arguments for forwarding call
2479 CallArgList CallArgs;
2480
2481 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2482 llvm::Value *ThisPtr = GetAddrOfBlockDecl(variable, false);
2483 CallArgs.add(RValue::get(ThisPtr), ThisType);
2484
2485 // Add the rest of the parameters.
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002486 for (auto param : BD->params())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002487 EmitDelegateCallArg(CallArgs, param, param->getLocStart());
Aaron Ballmanb2b8b1d2014-03-07 16:09:59 +00002488
Justin Bogner1cd11f12015-05-20 15:53:59 +00002489 assert(!Lambda->isGenericLambda() &&
Faisal Vali571df122013-09-29 08:45:24 +00002490 "generic lambda interconversion to block not implemented");
2491 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002492}
2493
2494void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
John McCalldec348f72013-05-03 07:33:41 +00002495 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
Eli Friedman2495ab02012-02-25 02:48:22 +00002496 // FIXME: Making this work correctly is nasty because it requires either
2497 // cloning the body of the call operator or making the call operator forward.
John McCalldec348f72013-05-03 07:33:41 +00002498 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002499 return;
2500 }
2501
Richard Smithb47c36f2013-11-05 09:12:18 +00002502 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody());
Eli Friedman2495ab02012-02-25 02:48:22 +00002503}
2504
2505void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) {
2506 const CXXRecordDecl *Lambda = MD->getParent();
2507
2508 // Start building arguments for forwarding call
2509 CallArgList CallArgs;
2510
2511 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda));
2512 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType));
2513 CallArgs.add(RValue::get(ThisPtr), ThisType);
2514
2515 // Add the rest of the parameters.
Aaron Ballmanf6bf62e2014-03-07 15:12:56 +00002516 for (auto Param : MD->params())
2517 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart());
2518
Faisal Vali571df122013-09-29 08:45:24 +00002519 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator();
2520 // For a generic lambda, find the corresponding call operator specialization
2521 // to which the call to the static-invoker shall be forwarded.
2522 if (Lambda->isGenericLambda()) {
2523 assert(MD->isFunctionTemplateSpecialization());
2524 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
2525 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate();
Craig Topper8a13c412014-05-21 05:09:00 +00002526 void *InsertPos = nullptr;
Justin Bogner1cd11f12015-05-20 15:53:59 +00002527 FunctionDecl *CorrespondingCallOpSpecialization =
Craig Topper7e0daca2014-06-26 04:58:53 +00002528 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
Faisal Vali571df122013-09-29 08:45:24 +00002529 assert(CorrespondingCallOpSpecialization);
2530 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
2531 }
2532 EmitForwardingCallToLambda(CallOp, CallArgs);
Eli Friedman2495ab02012-02-25 02:48:22 +00002533}
2534
Douglas Gregor355efbb2012-02-17 03:02:34 +00002535void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) {
2536 if (MD->isVariadic()) {
Eli Friedman5b446882012-02-16 03:47:28 +00002537 // FIXME: Making this work correctly is nasty because it requires either
2538 // cloning the body of the call operator or making the call operator forward.
2539 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function");
Eli Friedman2495ab02012-02-25 02:48:22 +00002540 return;
Eli Friedman5b446882012-02-16 03:47:28 +00002541 }
2542
Douglas Gregor355efbb2012-02-17 03:02:34 +00002543 EmitLambdaDelegatingInvokeBody(MD);
Eli Friedman5a6d5072012-02-16 01:37:33 +00002544}